scsi: megaraid_sas: Fix MSI-X vector print
[linux-2.6-microblaze.git] / drivers / scsi / megaraid / megaraid_sas_base.c
1 /*
2  *  Linux MegaRAID driver for SAS based RAID controllers
3  *
4  *  Copyright (c) 2003-2013  LSI Corporation
5  *  Copyright (c) 2013-2016  Avago Technologies
6  *  Copyright (c) 2016-2018  Broadcom Inc.
7  *
8  *  This program is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU General Public License
10  *  as published by the Free Software Foundation; either version 2
11  *  of the License, or (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  *
21  *  Authors: Broadcom Inc.
22  *           Sreenivas Bagalkote
23  *           Sumant Patro
24  *           Bo Yang
25  *           Adam Radford
26  *           Kashyap Desai <kashyap.desai@broadcom.com>
27  *           Sumit Saxena <sumit.saxena@broadcom.com>
28  *
29  *  Send feedback to: megaraidlinux.pdl@broadcom.com
30  */
31
32 #include <linux/kernel.h>
33 #include <linux/types.h>
34 #include <linux/pci.h>
35 #include <linux/list.h>
36 #include <linux/moduleparam.h>
37 #include <linux/module.h>
38 #include <linux/spinlock.h>
39 #include <linux/interrupt.h>
40 #include <linux/delay.h>
41 #include <linux/uio.h>
42 #include <linux/slab.h>
43 #include <linux/uaccess.h>
44 #include <asm/unaligned.h>
45 #include <linux/fs.h>
46 #include <linux/compat.h>
47 #include <linux/blkdev.h>
48 #include <linux/mutex.h>
49 #include <linux/poll.h>
50 #include <linux/vmalloc.h>
51 #include <linux/irq_poll.h>
52
53 #include <scsi/scsi.h>
54 #include <scsi/scsi_cmnd.h>
55 #include <scsi/scsi_device.h>
56 #include <scsi/scsi_host.h>
57 #include <scsi/scsi_tcq.h>
58 #include <scsi/scsi_dbg.h>
59 #include "megaraid_sas_fusion.h"
60 #include "megaraid_sas.h"
61
62 /*
63  * Number of sectors per IO command
64  * Will be set in megasas_init_mfi if user does not provide
65  */
66 static unsigned int max_sectors;
67 module_param_named(max_sectors, max_sectors, int, 0);
68 MODULE_PARM_DESC(max_sectors,
69         "Maximum number of sectors per IO command");
70
71 static int msix_disable;
72 module_param(msix_disable, int, S_IRUGO);
73 MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
74
75 static unsigned int msix_vectors;
76 module_param(msix_vectors, int, S_IRUGO);
77 MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW");
78
79 static int allow_vf_ioctls;
80 module_param(allow_vf_ioctls, int, S_IRUGO);
81 MODULE_PARM_DESC(allow_vf_ioctls, "Allow ioctls in SR-IOV VF mode. Default: 0");
82
83 static unsigned int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH;
84 module_param(throttlequeuedepth, int, S_IRUGO);
85 MODULE_PARM_DESC(throttlequeuedepth,
86         "Adapter queue depth when throttled due to I/O timeout. Default: 16");
87
88 unsigned int resetwaittime = MEGASAS_RESET_WAIT_TIME;
89 module_param(resetwaittime, int, S_IRUGO);
90 MODULE_PARM_DESC(resetwaittime, "Wait time in (1-180s) after I/O timeout before resetting adapter. Default: 180s");
91
92 int smp_affinity_enable = 1;
93 module_param(smp_affinity_enable, int, S_IRUGO);
94 MODULE_PARM_DESC(smp_affinity_enable, "SMP affinity feature enable/disable Default: enable(1)");
95
96 int rdpq_enable = 1;
97 module_param(rdpq_enable, int, S_IRUGO);
98 MODULE_PARM_DESC(rdpq_enable, "Allocate reply queue in chunks for large queue depth enable/disable Default: enable(1)");
99
100 unsigned int dual_qdepth_disable;
101 module_param(dual_qdepth_disable, int, S_IRUGO);
102 MODULE_PARM_DESC(dual_qdepth_disable, "Disable dual queue depth feature. Default: 0");
103
104 unsigned int scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
105 module_param(scmd_timeout, int, S_IRUGO);
106 MODULE_PARM_DESC(scmd_timeout, "scsi command timeout (10-90s), default 90s. See megasas_reset_timer.");
107
108 MODULE_LICENSE("GPL");
109 MODULE_VERSION(MEGASAS_VERSION);
110 MODULE_AUTHOR("megaraidlinux.pdl@broadcom.com");
111 MODULE_DESCRIPTION("Broadcom MegaRAID SAS Driver");
112
113 int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
114 static int megasas_get_pd_list(struct megasas_instance *instance);
115 static int megasas_ld_list_query(struct megasas_instance *instance,
116                                  u8 query_type);
117 static int megasas_issue_init_mfi(struct megasas_instance *instance);
118 static int megasas_register_aen(struct megasas_instance *instance,
119                                 u32 seq_num, u32 class_locale_word);
120 static void megasas_get_pd_info(struct megasas_instance *instance,
121                                 struct scsi_device *sdev);
122
123 /*
124  * PCI ID table for all supported controllers
125  */
126 static struct pci_device_id megasas_pci_table[] = {
127
128         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
129         /* xscale IOP */
130         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
131         /* ppc IOP */
132         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
133         /* ppc IOP */
134         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
135         /* gen2*/
136         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
137         /* gen2*/
138         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
139         /* skinny*/
140         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
141         /* skinny*/
142         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
143         /* xscale IOP, vega */
144         {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
145         /* xscale IOP */
146         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
147         /* Fusion */
148         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_PLASMA)},
149         /* Plasma */
150         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
151         /* Invader */
152         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FURY)},
153         /* Fury */
154         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER)},
155         /* Intruder */
156         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INTRUDER_24)},
157         /* Intruder 24 port*/
158         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_52)},
159         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CUTLASS_53)},
160         /* VENTURA */
161         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA)},
162         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER)},
163         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_HARPOON)},
164         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_TOMCAT)},
165         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VENTURA_4PORT)},
166         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_CRUSADER_4PORT)},
167         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E1)},
168         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E2)},
169         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E5)},
170         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_AERO_10E6)},
171         {}
172 };
173
174 MODULE_DEVICE_TABLE(pci, megasas_pci_table);
175
176 static int megasas_mgmt_majorno;
177 struct megasas_mgmt_info megasas_mgmt_info;
178 static struct fasync_struct *megasas_async_queue;
179 static DEFINE_MUTEX(megasas_async_queue_mutex);
180
181 static int megasas_poll_wait_aen;
182 static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
183 static u32 support_poll_for_event;
184 u32 megasas_dbg_lvl;
185 static u32 support_device_change;
186 static bool support_nvme_encapsulation;
187
188 /* define lock for aen poll */
189 spinlock_t poll_aen_lock;
190
191 void
192 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
193                      u8 alt_status);
194 static u32
195 megasas_read_fw_status_reg_gen2(struct megasas_instance *instance);
196 static int
197 megasas_adp_reset_gen2(struct megasas_instance *instance,
198                        struct megasas_register_set __iomem *reg_set);
199 static irqreturn_t megasas_isr(int irq, void *devp);
200 static u32
201 megasas_init_adapter_mfi(struct megasas_instance *instance);
202 u32
203 megasas_build_and_issue_cmd(struct megasas_instance *instance,
204                             struct scsi_cmnd *scmd);
205 static void megasas_complete_cmd_dpc(unsigned long instance_addr);
206 int
207 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
208         int seconds);
209 void megasas_fusion_ocr_wq(struct work_struct *work);
210 static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
211                                          int initial);
212 static int
213 megasas_set_dma_mask(struct megasas_instance *instance);
214 static int
215 megasas_alloc_ctrl_mem(struct megasas_instance *instance);
216 static inline void
217 megasas_free_ctrl_mem(struct megasas_instance *instance);
218 static inline int
219 megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance);
220 static inline void
221 megasas_free_ctrl_dma_buffers(struct megasas_instance *instance);
222 static inline void
223 megasas_init_ctrl_params(struct megasas_instance *instance);
224
225 u32 megasas_readl(struct megasas_instance *instance,
226                   const volatile void __iomem *addr)
227 {
228         u32 i = 0, ret_val;
229         /*
230          * Due to a HW errata in Aero controllers, reads to certain
231          * Fusion registers could intermittently return all zeroes.
232          * This behavior is transient in nature and subsequent reads will
233          * return valid value. As a workaround in driver, retry readl for
234          * upto three times until a non-zero value is read.
235          */
236         if (instance->adapter_type == AERO_SERIES) {
237                 do {
238                         ret_val = readl(addr);
239                         i++;
240                 } while (ret_val == 0 && i < 3);
241                 return ret_val;
242         } else {
243                 return readl(addr);
244         }
245 }
246
247 /**
248  * megasas_set_dma_settings -   Populate DMA address, length and flags for DCMDs
249  * @instance:                   Adapter soft state
250  * @dcmd:                       DCMD frame inside MFI command
251  * @dma_addr:                   DMA address of buffer to be passed to FW
252  * @dma_len:                    Length of DMA buffer to be passed to FW
253  * @return:                     void
254  */
255 void megasas_set_dma_settings(struct megasas_instance *instance,
256                               struct megasas_dcmd_frame *dcmd,
257                               dma_addr_t dma_addr, u32 dma_len)
258 {
259         if (instance->consistent_mask_64bit) {
260                 dcmd->sgl.sge64[0].phys_addr = cpu_to_le64(dma_addr);
261                 dcmd->sgl.sge64[0].length = cpu_to_le32(dma_len);
262                 dcmd->flags = cpu_to_le16(dcmd->flags | MFI_FRAME_SGL64);
263
264         } else {
265                 dcmd->sgl.sge32[0].phys_addr =
266                                 cpu_to_le32(lower_32_bits(dma_addr));
267                 dcmd->sgl.sge32[0].length = cpu_to_le32(dma_len);
268                 dcmd->flags = cpu_to_le16(dcmd->flags);
269         }
270 }
271
272 void
273 megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
274 {
275         instance->instancet->fire_cmd(instance,
276                 cmd->frame_phys_addr, 0, instance->reg_set);
277         return;
278 }
279
280 /**
281  * megasas_get_cmd -    Get a command from the free pool
282  * @instance:           Adapter soft state
283  *
284  * Returns a free command from the pool
285  */
286 struct megasas_cmd *megasas_get_cmd(struct megasas_instance
287                                                   *instance)
288 {
289         unsigned long flags;
290         struct megasas_cmd *cmd = NULL;
291
292         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
293
294         if (!list_empty(&instance->cmd_pool)) {
295                 cmd = list_entry((&instance->cmd_pool)->next,
296                                  struct megasas_cmd, list);
297                 list_del_init(&cmd->list);
298         } else {
299                 dev_err(&instance->pdev->dev, "Command pool empty!\n");
300         }
301
302         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
303         return cmd;
304 }
305
306 /**
307  * megasas_return_cmd - Return a cmd to free command pool
308  * @instance:           Adapter soft state
309  * @cmd:                Command packet to be returned to free command pool
310  */
311 void
312 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
313 {
314         unsigned long flags;
315         u32 blk_tags;
316         struct megasas_cmd_fusion *cmd_fusion;
317         struct fusion_context *fusion = instance->ctrl_context;
318
319         /* This flag is used only for fusion adapter.
320          * Wait for Interrupt for Polled mode DCMD
321          */
322         if (cmd->flags & DRV_DCMD_POLLED_MODE)
323                 return;
324
325         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
326
327         if (fusion) {
328                 blk_tags = instance->max_scsi_cmds + cmd->index;
329                 cmd_fusion = fusion->cmd_list[blk_tags];
330                 megasas_return_cmd_fusion(instance, cmd_fusion);
331         }
332         cmd->scmd = NULL;
333         cmd->frame_count = 0;
334         cmd->flags = 0;
335         memset(cmd->frame, 0, instance->mfi_frame_size);
336         cmd->frame->io.context = cpu_to_le32(cmd->index);
337         if (!fusion && reset_devices)
338                 cmd->frame->hdr.cmd = MFI_CMD_INVALID;
339         list_add(&cmd->list, (&instance->cmd_pool)->next);
340
341         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
342
343 }
344
345 static const char *
346 format_timestamp(uint32_t timestamp)
347 {
348         static char buffer[32];
349
350         if ((timestamp & 0xff000000) == 0xff000000)
351                 snprintf(buffer, sizeof(buffer), "boot + %us", timestamp &
352                 0x00ffffff);
353         else
354                 snprintf(buffer, sizeof(buffer), "%us", timestamp);
355         return buffer;
356 }
357
358 static const char *
359 format_class(int8_t class)
360 {
361         static char buffer[6];
362
363         switch (class) {
364         case MFI_EVT_CLASS_DEBUG:
365                 return "debug";
366         case MFI_EVT_CLASS_PROGRESS:
367                 return "progress";
368         case MFI_EVT_CLASS_INFO:
369                 return "info";
370         case MFI_EVT_CLASS_WARNING:
371                 return "WARN";
372         case MFI_EVT_CLASS_CRITICAL:
373                 return "CRIT";
374         case MFI_EVT_CLASS_FATAL:
375                 return "FATAL";
376         case MFI_EVT_CLASS_DEAD:
377                 return "DEAD";
378         default:
379                 snprintf(buffer, sizeof(buffer), "%d", class);
380                 return buffer;
381         }
382 }
383
384 /**
385   * megasas_decode_evt: Decode FW AEN event and print critical event
386   * for information.
387   * @instance:                  Adapter soft state
388   */
389 static void
390 megasas_decode_evt(struct megasas_instance *instance)
391 {
392         struct megasas_evt_detail *evt_detail = instance->evt_detail;
393         union megasas_evt_class_locale class_locale;
394         class_locale.word = le32_to_cpu(evt_detail->cl.word);
395
396         if (class_locale.members.class >= MFI_EVT_CLASS_CRITICAL)
397                 dev_info(&instance->pdev->dev, "%d (%s/0x%04x/%s) - %s\n",
398                         le32_to_cpu(evt_detail->seq_num),
399                         format_timestamp(le32_to_cpu(evt_detail->time_stamp)),
400                         (class_locale.members.locale),
401                         format_class(class_locale.members.class),
402                         evt_detail->description);
403 }
404
405 /**
406 *       The following functions are defined for xscale
407 *       (deviceid : 1064R, PERC5) controllers
408 */
409
410 /**
411  * megasas_enable_intr_xscale - Enables interrupts
412  * @regs:                       MFI register set
413  */
414 static inline void
415 megasas_enable_intr_xscale(struct megasas_instance *instance)
416 {
417         struct megasas_register_set __iomem *regs;
418
419         regs = instance->reg_set;
420         writel(0, &(regs)->outbound_intr_mask);
421
422         /* Dummy readl to force pci flush */
423         readl(&regs->outbound_intr_mask);
424 }
425
426 /**
427  * megasas_disable_intr_xscale -Disables interrupt
428  * @regs:                       MFI register set
429  */
430 static inline void
431 megasas_disable_intr_xscale(struct megasas_instance *instance)
432 {
433         struct megasas_register_set __iomem *regs;
434         u32 mask = 0x1f;
435
436         regs = instance->reg_set;
437         writel(mask, &regs->outbound_intr_mask);
438         /* Dummy readl to force pci flush */
439         readl(&regs->outbound_intr_mask);
440 }
441
442 /**
443  * megasas_read_fw_status_reg_xscale - returns the current FW status value
444  * @regs:                       MFI register set
445  */
446 static u32
447 megasas_read_fw_status_reg_xscale(struct megasas_instance *instance)
448 {
449         return readl(&instance->reg_set->outbound_msg_0);
450 }
451 /**
452  * megasas_clear_interrupt_xscale -     Check & clear interrupt
453  * @regs:                               MFI register set
454  */
455 static int
456 megasas_clear_intr_xscale(struct megasas_instance *instance)
457 {
458         u32 status;
459         u32 mfiStatus = 0;
460         struct megasas_register_set __iomem *regs;
461         regs = instance->reg_set;
462
463         /*
464          * Check if it is our interrupt
465          */
466         status = readl(&regs->outbound_intr_status);
467
468         if (status & MFI_OB_INTR_STATUS_MASK)
469                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
470         if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
471                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
472
473         /*
474          * Clear the interrupt by writing back the same value
475          */
476         if (mfiStatus)
477                 writel(status, &regs->outbound_intr_status);
478
479         /* Dummy readl to force pci flush */
480         readl(&regs->outbound_intr_status);
481
482         return mfiStatus;
483 }
484
485 /**
486  * megasas_fire_cmd_xscale -    Sends command to the FW
487  * @frame_phys_addr :           Physical address of cmd
488  * @frame_count :               Number of frames for the command
489  * @regs :                      MFI register set
490  */
491 static inline void
492 megasas_fire_cmd_xscale(struct megasas_instance *instance,
493                 dma_addr_t frame_phys_addr,
494                 u32 frame_count,
495                 struct megasas_register_set __iomem *regs)
496 {
497         unsigned long flags;
498
499         spin_lock_irqsave(&instance->hba_lock, flags);
500         writel((frame_phys_addr >> 3)|(frame_count),
501                &(regs)->inbound_queue_port);
502         spin_unlock_irqrestore(&instance->hba_lock, flags);
503 }
504
505 /**
506  * megasas_adp_reset_xscale -  For controller reset
507  * @regs:                              MFI register set
508  */
509 static int
510 megasas_adp_reset_xscale(struct megasas_instance *instance,
511         struct megasas_register_set __iomem *regs)
512 {
513         u32 i;
514         u32 pcidata;
515
516         writel(MFI_ADP_RESET, &regs->inbound_doorbell);
517
518         for (i = 0; i < 3; i++)
519                 msleep(1000); /* sleep for 3 secs */
520         pcidata  = 0;
521         pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
522         dev_notice(&instance->pdev->dev, "pcidata = %x\n", pcidata);
523         if (pcidata & 0x2) {
524                 dev_notice(&instance->pdev->dev, "mfi 1068 offset read=%x\n", pcidata);
525                 pcidata &= ~0x2;
526                 pci_write_config_dword(instance->pdev,
527                                 MFI_1068_PCSR_OFFSET, pcidata);
528
529                 for (i = 0; i < 2; i++)
530                         msleep(1000); /* need to wait 2 secs again */
531
532                 pcidata  = 0;
533                 pci_read_config_dword(instance->pdev,
534                                 MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
535                 dev_notice(&instance->pdev->dev, "1068 offset handshake read=%x\n", pcidata);
536                 if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
537                         dev_notice(&instance->pdev->dev, "1068 offset pcidt=%x\n", pcidata);
538                         pcidata = 0;
539                         pci_write_config_dword(instance->pdev,
540                                 MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
541                 }
542         }
543         return 0;
544 }
545
546 /**
547  * megasas_check_reset_xscale - For controller reset check
548  * @regs:                               MFI register set
549  */
550 static int
551 megasas_check_reset_xscale(struct megasas_instance *instance,
552                 struct megasas_register_set __iomem *regs)
553 {
554         if ((atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) &&
555             (le32_to_cpu(*instance->consumer) ==
556                 MEGASAS_ADPRESET_INPROG_SIGN))
557                 return 1;
558         return 0;
559 }
560
561 static struct megasas_instance_template megasas_instance_template_xscale = {
562
563         .fire_cmd = megasas_fire_cmd_xscale,
564         .enable_intr = megasas_enable_intr_xscale,
565         .disable_intr = megasas_disable_intr_xscale,
566         .clear_intr = megasas_clear_intr_xscale,
567         .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
568         .adp_reset = megasas_adp_reset_xscale,
569         .check_reset = megasas_check_reset_xscale,
570         .service_isr = megasas_isr,
571         .tasklet = megasas_complete_cmd_dpc,
572         .init_adapter = megasas_init_adapter_mfi,
573         .build_and_issue_cmd = megasas_build_and_issue_cmd,
574         .issue_dcmd = megasas_issue_dcmd,
575 };
576
577 /**
578 *       This is the end of set of functions & definitions specific
579 *       to xscale (deviceid : 1064R, PERC5) controllers
580 */
581
582 /**
583 *       The following functions are defined for ppc (deviceid : 0x60)
584 *       controllers
585 */
586
587 /**
588  * megasas_enable_intr_ppc -    Enables interrupts
589  * @regs:                       MFI register set
590  */
591 static inline void
592 megasas_enable_intr_ppc(struct megasas_instance *instance)
593 {
594         struct megasas_register_set __iomem *regs;
595
596         regs = instance->reg_set;
597         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
598
599         writel(~0x80000000, &(regs)->outbound_intr_mask);
600
601         /* Dummy readl to force pci flush */
602         readl(&regs->outbound_intr_mask);
603 }
604
605 /**
606  * megasas_disable_intr_ppc -   Disable interrupt
607  * @regs:                       MFI register set
608  */
609 static inline void
610 megasas_disable_intr_ppc(struct megasas_instance *instance)
611 {
612         struct megasas_register_set __iomem *regs;
613         u32 mask = 0xFFFFFFFF;
614
615         regs = instance->reg_set;
616         writel(mask, &regs->outbound_intr_mask);
617         /* Dummy readl to force pci flush */
618         readl(&regs->outbound_intr_mask);
619 }
620
621 /**
622  * megasas_read_fw_status_reg_ppc - returns the current FW status value
623  * @regs:                       MFI register set
624  */
625 static u32
626 megasas_read_fw_status_reg_ppc(struct megasas_instance *instance)
627 {
628         return readl(&instance->reg_set->outbound_scratch_pad_0);
629 }
630
631 /**
632  * megasas_clear_interrupt_ppc -        Check & clear interrupt
633  * @regs:                               MFI register set
634  */
635 static int
636 megasas_clear_intr_ppc(struct megasas_instance *instance)
637 {
638         u32 status, mfiStatus = 0;
639         struct megasas_register_set __iomem *regs;
640         regs = instance->reg_set;
641
642         /*
643          * Check if it is our interrupt
644          */
645         status = readl(&regs->outbound_intr_status);
646
647         if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
648                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
649
650         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
651                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
652
653         /*
654          * Clear the interrupt by writing back the same value
655          */
656         writel(status, &regs->outbound_doorbell_clear);
657
658         /* Dummy readl to force pci flush */
659         readl(&regs->outbound_doorbell_clear);
660
661         return mfiStatus;
662 }
663
664 /**
665  * megasas_fire_cmd_ppc -       Sends command to the FW
666  * @frame_phys_addr :           Physical address of cmd
667  * @frame_count :               Number of frames for the command
668  * @regs :                      MFI register set
669  */
670 static inline void
671 megasas_fire_cmd_ppc(struct megasas_instance *instance,
672                 dma_addr_t frame_phys_addr,
673                 u32 frame_count,
674                 struct megasas_register_set __iomem *regs)
675 {
676         unsigned long flags;
677
678         spin_lock_irqsave(&instance->hba_lock, flags);
679         writel((frame_phys_addr | (frame_count<<1))|1,
680                         &(regs)->inbound_queue_port);
681         spin_unlock_irqrestore(&instance->hba_lock, flags);
682 }
683
684 /**
685  * megasas_check_reset_ppc -    For controller reset check
686  * @regs:                               MFI register set
687  */
688 static int
689 megasas_check_reset_ppc(struct megasas_instance *instance,
690                         struct megasas_register_set __iomem *regs)
691 {
692         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
693                 return 1;
694
695         return 0;
696 }
697
698 static struct megasas_instance_template megasas_instance_template_ppc = {
699
700         .fire_cmd = megasas_fire_cmd_ppc,
701         .enable_intr = megasas_enable_intr_ppc,
702         .disable_intr = megasas_disable_intr_ppc,
703         .clear_intr = megasas_clear_intr_ppc,
704         .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
705         .adp_reset = megasas_adp_reset_xscale,
706         .check_reset = megasas_check_reset_ppc,
707         .service_isr = megasas_isr,
708         .tasklet = megasas_complete_cmd_dpc,
709         .init_adapter = megasas_init_adapter_mfi,
710         .build_and_issue_cmd = megasas_build_and_issue_cmd,
711         .issue_dcmd = megasas_issue_dcmd,
712 };
713
714 /**
715  * megasas_enable_intr_skinny - Enables interrupts
716  * @regs:                       MFI register set
717  */
718 static inline void
719 megasas_enable_intr_skinny(struct megasas_instance *instance)
720 {
721         struct megasas_register_set __iomem *regs;
722
723         regs = instance->reg_set;
724         writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
725
726         writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
727
728         /* Dummy readl to force pci flush */
729         readl(&regs->outbound_intr_mask);
730 }
731
732 /**
733  * megasas_disable_intr_skinny -        Disables interrupt
734  * @regs:                       MFI register set
735  */
736 static inline void
737 megasas_disable_intr_skinny(struct megasas_instance *instance)
738 {
739         struct megasas_register_set __iomem *regs;
740         u32 mask = 0xFFFFFFFF;
741
742         regs = instance->reg_set;
743         writel(mask, &regs->outbound_intr_mask);
744         /* Dummy readl to force pci flush */
745         readl(&regs->outbound_intr_mask);
746 }
747
748 /**
749  * megasas_read_fw_status_reg_skinny - returns the current FW status value
750  * @regs:                       MFI register set
751  */
752 static u32
753 megasas_read_fw_status_reg_skinny(struct megasas_instance *instance)
754 {
755         return readl(&instance->reg_set->outbound_scratch_pad_0);
756 }
757
758 /**
759  * megasas_clear_interrupt_skinny -     Check & clear interrupt
760  * @regs:                               MFI register set
761  */
762 static int
763 megasas_clear_intr_skinny(struct megasas_instance *instance)
764 {
765         u32 status;
766         u32 mfiStatus = 0;
767         struct megasas_register_set __iomem *regs;
768         regs = instance->reg_set;
769
770         /*
771          * Check if it is our interrupt
772          */
773         status = readl(&regs->outbound_intr_status);
774
775         if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
776                 return 0;
777         }
778
779         /*
780          * Check if it is our interrupt
781          */
782         if ((megasas_read_fw_status_reg_skinny(instance) & MFI_STATE_MASK) ==
783             MFI_STATE_FAULT) {
784                 mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
785         } else
786                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
787
788         /*
789          * Clear the interrupt by writing back the same value
790          */
791         writel(status, &regs->outbound_intr_status);
792
793         /*
794          * dummy read to flush PCI
795          */
796         readl(&regs->outbound_intr_status);
797
798         return mfiStatus;
799 }
800
801 /**
802  * megasas_fire_cmd_skinny -    Sends command to the FW
803  * @frame_phys_addr :           Physical address of cmd
804  * @frame_count :               Number of frames for the command
805  * @regs :                      MFI register set
806  */
807 static inline void
808 megasas_fire_cmd_skinny(struct megasas_instance *instance,
809                         dma_addr_t frame_phys_addr,
810                         u32 frame_count,
811                         struct megasas_register_set __iomem *regs)
812 {
813         unsigned long flags;
814
815         spin_lock_irqsave(&instance->hba_lock, flags);
816         writel(upper_32_bits(frame_phys_addr),
817                &(regs)->inbound_high_queue_port);
818         writel((lower_32_bits(frame_phys_addr) | (frame_count<<1))|1,
819                &(regs)->inbound_low_queue_port);
820         spin_unlock_irqrestore(&instance->hba_lock, flags);
821 }
822
823 /**
824  * megasas_check_reset_skinny - For controller reset check
825  * @regs:                               MFI register set
826  */
827 static int
828 megasas_check_reset_skinny(struct megasas_instance *instance,
829                                 struct megasas_register_set __iomem *regs)
830 {
831         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
832                 return 1;
833
834         return 0;
835 }
836
837 static struct megasas_instance_template megasas_instance_template_skinny = {
838
839         .fire_cmd = megasas_fire_cmd_skinny,
840         .enable_intr = megasas_enable_intr_skinny,
841         .disable_intr = megasas_disable_intr_skinny,
842         .clear_intr = megasas_clear_intr_skinny,
843         .read_fw_status_reg = megasas_read_fw_status_reg_skinny,
844         .adp_reset = megasas_adp_reset_gen2,
845         .check_reset = megasas_check_reset_skinny,
846         .service_isr = megasas_isr,
847         .tasklet = megasas_complete_cmd_dpc,
848         .init_adapter = megasas_init_adapter_mfi,
849         .build_and_issue_cmd = megasas_build_and_issue_cmd,
850         .issue_dcmd = megasas_issue_dcmd,
851 };
852
853
854 /**
855 *       The following functions are defined for gen2 (deviceid : 0x78 0x79)
856 *       controllers
857 */
858
859 /**
860  * megasas_enable_intr_gen2 -  Enables interrupts
861  * @regs:                      MFI register set
862  */
863 static inline void
864 megasas_enable_intr_gen2(struct megasas_instance *instance)
865 {
866         struct megasas_register_set __iomem *regs;
867
868         regs = instance->reg_set;
869         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
870
871         /* write ~0x00000005 (4 & 1) to the intr mask*/
872         writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
873
874         /* Dummy readl to force pci flush */
875         readl(&regs->outbound_intr_mask);
876 }
877
878 /**
879  * megasas_disable_intr_gen2 - Disables interrupt
880  * @regs:                      MFI register set
881  */
882 static inline void
883 megasas_disable_intr_gen2(struct megasas_instance *instance)
884 {
885         struct megasas_register_set __iomem *regs;
886         u32 mask = 0xFFFFFFFF;
887
888         regs = instance->reg_set;
889         writel(mask, &regs->outbound_intr_mask);
890         /* Dummy readl to force pci flush */
891         readl(&regs->outbound_intr_mask);
892 }
893
894 /**
895  * megasas_read_fw_status_reg_gen2 - returns the current FW status value
896  * @regs:                      MFI register set
897  */
898 static u32
899 megasas_read_fw_status_reg_gen2(struct megasas_instance *instance)
900 {
901         return readl(&instance->reg_set->outbound_scratch_pad_0);
902 }
903
904 /**
905  * megasas_clear_interrupt_gen2 -      Check & clear interrupt
906  * @regs:                              MFI register set
907  */
908 static int
909 megasas_clear_intr_gen2(struct megasas_instance *instance)
910 {
911         u32 status;
912         u32 mfiStatus = 0;
913         struct megasas_register_set __iomem *regs;
914         regs = instance->reg_set;
915
916         /*
917          * Check if it is our interrupt
918          */
919         status = readl(&regs->outbound_intr_status);
920
921         if (status & MFI_INTR_FLAG_REPLY_MESSAGE) {
922                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
923         }
924         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
925                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
926         }
927
928         /*
929          * Clear the interrupt by writing back the same value
930          */
931         if (mfiStatus)
932                 writel(status, &regs->outbound_doorbell_clear);
933
934         /* Dummy readl to force pci flush */
935         readl(&regs->outbound_intr_status);
936
937         return mfiStatus;
938 }
939 /**
940  * megasas_fire_cmd_gen2 -     Sends command to the FW
941  * @frame_phys_addr :          Physical address of cmd
942  * @frame_count :              Number of frames for the command
943  * @regs :                     MFI register set
944  */
945 static inline void
946 megasas_fire_cmd_gen2(struct megasas_instance *instance,
947                         dma_addr_t frame_phys_addr,
948                         u32 frame_count,
949                         struct megasas_register_set __iomem *regs)
950 {
951         unsigned long flags;
952
953         spin_lock_irqsave(&instance->hba_lock, flags);
954         writel((frame_phys_addr | (frame_count<<1))|1,
955                         &(regs)->inbound_queue_port);
956         spin_unlock_irqrestore(&instance->hba_lock, flags);
957 }
958
959 /**
960  * megasas_adp_reset_gen2 -     For controller reset
961  * @regs:                               MFI register set
962  */
963 static int
964 megasas_adp_reset_gen2(struct megasas_instance *instance,
965                         struct megasas_register_set __iomem *reg_set)
966 {
967         u32 retry = 0 ;
968         u32 HostDiag;
969         u32 __iomem *seq_offset = &reg_set->seq_offset;
970         u32 __iomem *hostdiag_offset = &reg_set->host_diag;
971
972         if (instance->instancet == &megasas_instance_template_skinny) {
973                 seq_offset = &reg_set->fusion_seq_offset;
974                 hostdiag_offset = &reg_set->fusion_host_diag;
975         }
976
977         writel(0, seq_offset);
978         writel(4, seq_offset);
979         writel(0xb, seq_offset);
980         writel(2, seq_offset);
981         writel(7, seq_offset);
982         writel(0xd, seq_offset);
983
984         msleep(1000);
985
986         HostDiag = (u32)readl(hostdiag_offset);
987
988         while (!(HostDiag & DIAG_WRITE_ENABLE)) {
989                 msleep(100);
990                 HostDiag = (u32)readl(hostdiag_offset);
991                 dev_notice(&instance->pdev->dev, "RESETGEN2: retry=%x, hostdiag=%x\n",
992                                         retry, HostDiag);
993
994                 if (retry++ >= 100)
995                         return 1;
996
997         }
998
999         dev_notice(&instance->pdev->dev, "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
1000
1001         writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
1002
1003         ssleep(10);
1004
1005         HostDiag = (u32)readl(hostdiag_offset);
1006         while (HostDiag & DIAG_RESET_ADAPTER) {
1007                 msleep(100);
1008                 HostDiag = (u32)readl(hostdiag_offset);
1009                 dev_notice(&instance->pdev->dev, "RESET_GEN2: retry=%x, hostdiag=%x\n",
1010                                 retry, HostDiag);
1011
1012                 if (retry++ >= 1000)
1013                         return 1;
1014
1015         }
1016         return 0;
1017 }
1018
1019 /**
1020  * megasas_check_reset_gen2 -   For controller reset check
1021  * @regs:                               MFI register set
1022  */
1023 static int
1024 megasas_check_reset_gen2(struct megasas_instance *instance,
1025                 struct megasas_register_set __iomem *regs)
1026 {
1027         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
1028                 return 1;
1029
1030         return 0;
1031 }
1032
1033 static struct megasas_instance_template megasas_instance_template_gen2 = {
1034
1035         .fire_cmd = megasas_fire_cmd_gen2,
1036         .enable_intr = megasas_enable_intr_gen2,
1037         .disable_intr = megasas_disable_intr_gen2,
1038         .clear_intr = megasas_clear_intr_gen2,
1039         .read_fw_status_reg = megasas_read_fw_status_reg_gen2,
1040         .adp_reset = megasas_adp_reset_gen2,
1041         .check_reset = megasas_check_reset_gen2,
1042         .service_isr = megasas_isr,
1043         .tasklet = megasas_complete_cmd_dpc,
1044         .init_adapter = megasas_init_adapter_mfi,
1045         .build_and_issue_cmd = megasas_build_and_issue_cmd,
1046         .issue_dcmd = megasas_issue_dcmd,
1047 };
1048
1049 /**
1050 *       This is the end of set of functions & definitions
1051 *       specific to gen2 (deviceid : 0x78, 0x79) controllers
1052 */
1053
1054 /*
1055  * Template added for TB (Fusion)
1056  */
1057 extern struct megasas_instance_template megasas_instance_template_fusion;
1058
1059 /**
1060  * megasas_issue_polled -       Issues a polling command
1061  * @instance:                   Adapter soft state
1062  * @cmd:                        Command packet to be issued
1063  *
1064  * For polling, MFI requires the cmd_status to be set to MFI_STAT_INVALID_STATUS before posting.
1065  */
1066 int
1067 megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
1068 {
1069         struct megasas_header *frame_hdr = &cmd->frame->hdr;
1070
1071         frame_hdr->cmd_status = MFI_STAT_INVALID_STATUS;
1072         frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
1073
1074         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1075                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1076                         __func__, __LINE__);
1077                 return DCMD_NOT_FIRED;
1078         }
1079
1080         instance->instancet->issue_dcmd(instance, cmd);
1081
1082         return wait_and_poll(instance, cmd, instance->requestorId ?
1083                         MEGASAS_ROUTINE_WAIT_TIME_VF : MFI_IO_TIMEOUT_SECS);
1084 }
1085
1086 /**
1087  * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
1088  * @instance:                   Adapter soft state
1089  * @cmd:                        Command to be issued
1090  * @timeout:                    Timeout in seconds
1091  *
1092  * This function waits on an event for the command to be returned from ISR.
1093  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
1094  * Used to issue ioctl commands.
1095  */
1096 int
1097 megasas_issue_blocked_cmd(struct megasas_instance *instance,
1098                           struct megasas_cmd *cmd, int timeout)
1099 {
1100         int ret = 0;
1101         cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS;
1102
1103         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1104                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1105                         __func__, __LINE__);
1106                 return DCMD_NOT_FIRED;
1107         }
1108
1109         instance->instancet->issue_dcmd(instance, cmd);
1110
1111         if (timeout) {
1112                 ret = wait_event_timeout(instance->int_cmd_wait_q,
1113                                 cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS, timeout * HZ);
1114                 if (!ret) {
1115                         dev_err(&instance->pdev->dev,
1116                                 "DCMD(opcode: 0x%x) is timed out, func:%s\n",
1117                                 cmd->frame->dcmd.opcode, __func__);
1118                         return DCMD_TIMEOUT;
1119                 }
1120         } else
1121                 wait_event(instance->int_cmd_wait_q,
1122                                 cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS);
1123
1124         return (cmd->cmd_status_drv == MFI_STAT_OK) ?
1125                 DCMD_SUCCESS : DCMD_FAILED;
1126 }
1127
1128 /**
1129  * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
1130  * @instance:                           Adapter soft state
1131  * @cmd_to_abort:                       Previously issued cmd to be aborted
1132  * @timeout:                            Timeout in seconds
1133  *
1134  * MFI firmware can abort previously issued AEN comamnd (automatic event
1135  * notification). The megasas_issue_blocked_abort_cmd() issues such abort
1136  * cmd and waits for return status.
1137  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
1138  */
1139 static int
1140 megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
1141                                 struct megasas_cmd *cmd_to_abort, int timeout)
1142 {
1143         struct megasas_cmd *cmd;
1144         struct megasas_abort_frame *abort_fr;
1145         int ret = 0;
1146         u32 opcode;
1147
1148         cmd = megasas_get_cmd(instance);
1149
1150         if (!cmd)
1151                 return -1;
1152
1153         abort_fr = &cmd->frame->abort;
1154
1155         /*
1156          * Prepare and issue the abort frame
1157          */
1158         abort_fr->cmd = MFI_CMD_ABORT;
1159         abort_fr->cmd_status = MFI_STAT_INVALID_STATUS;
1160         abort_fr->flags = cpu_to_le16(0);
1161         abort_fr->abort_context = cpu_to_le32(cmd_to_abort->index);
1162         abort_fr->abort_mfi_phys_addr_lo =
1163                 cpu_to_le32(lower_32_bits(cmd_to_abort->frame_phys_addr));
1164         abort_fr->abort_mfi_phys_addr_hi =
1165                 cpu_to_le32(upper_32_bits(cmd_to_abort->frame_phys_addr));
1166
1167         cmd->sync_cmd = 1;
1168         cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS;
1169
1170         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1171                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
1172                         __func__, __LINE__);
1173                 return DCMD_NOT_FIRED;
1174         }
1175
1176         instance->instancet->issue_dcmd(instance, cmd);
1177
1178         if (timeout) {
1179                 ret = wait_event_timeout(instance->abort_cmd_wait_q,
1180                                 cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS, timeout * HZ);
1181                 if (!ret) {
1182                         opcode = cmd_to_abort->frame->dcmd.opcode;
1183                         dev_err(&instance->pdev->dev,
1184                                 "Abort(to be aborted DCMD opcode: 0x%x) is timed out func:%s\n",
1185                                 opcode,  __func__);
1186                         return DCMD_TIMEOUT;
1187                 }
1188         } else
1189                 wait_event(instance->abort_cmd_wait_q,
1190                                 cmd->cmd_status_drv != MFI_STAT_INVALID_STATUS);
1191
1192         cmd->sync_cmd = 0;
1193
1194         megasas_return_cmd(instance, cmd);
1195         return (cmd->cmd_status_drv == MFI_STAT_OK) ?
1196                 DCMD_SUCCESS : DCMD_FAILED;
1197 }
1198
1199 /**
1200  * megasas_make_sgl32 - Prepares 32-bit SGL
1201  * @instance:           Adapter soft state
1202  * @scp:                SCSI command from the mid-layer
1203  * @mfi_sgl:            SGL to be filled in
1204  *
1205  * If successful, this function returns the number of SG elements. Otherwise,
1206  * it returnes -1.
1207  */
1208 static int
1209 megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
1210                    union megasas_sgl *mfi_sgl)
1211 {
1212         int i;
1213         int sge_count;
1214         struct scatterlist *os_sgl;
1215
1216         sge_count = scsi_dma_map(scp);
1217         BUG_ON(sge_count < 0);
1218
1219         if (sge_count) {
1220                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1221                         mfi_sgl->sge32[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1222                         mfi_sgl->sge32[i].phys_addr = cpu_to_le32(sg_dma_address(os_sgl));
1223                 }
1224         }
1225         return sge_count;
1226 }
1227
1228 /**
1229  * megasas_make_sgl64 - Prepares 64-bit SGL
1230  * @instance:           Adapter soft state
1231  * @scp:                SCSI command from the mid-layer
1232  * @mfi_sgl:            SGL to be filled in
1233  *
1234  * If successful, this function returns the number of SG elements. Otherwise,
1235  * it returnes -1.
1236  */
1237 static int
1238 megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
1239                    union megasas_sgl *mfi_sgl)
1240 {
1241         int i;
1242         int sge_count;
1243         struct scatterlist *os_sgl;
1244
1245         sge_count = scsi_dma_map(scp);
1246         BUG_ON(sge_count < 0);
1247
1248         if (sge_count) {
1249                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1250                         mfi_sgl->sge64[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1251                         mfi_sgl->sge64[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl));
1252                 }
1253         }
1254         return sge_count;
1255 }
1256
1257 /**
1258  * megasas_make_sgl_skinny - Prepares IEEE SGL
1259  * @instance:           Adapter soft state
1260  * @scp:                SCSI command from the mid-layer
1261  * @mfi_sgl:            SGL to be filled in
1262  *
1263  * If successful, this function returns the number of SG elements. Otherwise,
1264  * it returnes -1.
1265  */
1266 static int
1267 megasas_make_sgl_skinny(struct megasas_instance *instance,
1268                 struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
1269 {
1270         int i;
1271         int sge_count;
1272         struct scatterlist *os_sgl;
1273
1274         sge_count = scsi_dma_map(scp);
1275
1276         if (sge_count) {
1277                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1278                         mfi_sgl->sge_skinny[i].length =
1279                                 cpu_to_le32(sg_dma_len(os_sgl));
1280                         mfi_sgl->sge_skinny[i].phys_addr =
1281                                 cpu_to_le64(sg_dma_address(os_sgl));
1282                         mfi_sgl->sge_skinny[i].flag = cpu_to_le32(0);
1283                 }
1284         }
1285         return sge_count;
1286 }
1287
1288  /**
1289  * megasas_get_frame_count - Computes the number of frames
1290  * @frame_type          : type of frame- io or pthru frame
1291  * @sge_count           : number of sg elements
1292  *
1293  * Returns the number of frames required for numnber of sge's (sge_count)
1294  */
1295
1296 static u32 megasas_get_frame_count(struct megasas_instance *instance,
1297                         u8 sge_count, u8 frame_type)
1298 {
1299         int num_cnt;
1300         int sge_bytes;
1301         u32 sge_sz;
1302         u32 frame_count = 0;
1303
1304         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1305             sizeof(struct megasas_sge32);
1306
1307         if (instance->flag_ieee) {
1308                 sge_sz = sizeof(struct megasas_sge_skinny);
1309         }
1310
1311         /*
1312          * Main frame can contain 2 SGEs for 64-bit SGLs and
1313          * 3 SGEs for 32-bit SGLs for ldio &
1314          * 1 SGEs for 64-bit SGLs and
1315          * 2 SGEs for 32-bit SGLs for pthru frame
1316          */
1317         if (unlikely(frame_type == PTHRU_FRAME)) {
1318                 if (instance->flag_ieee == 1) {
1319                         num_cnt = sge_count - 1;
1320                 } else if (IS_DMA64)
1321                         num_cnt = sge_count - 1;
1322                 else
1323                         num_cnt = sge_count - 2;
1324         } else {
1325                 if (instance->flag_ieee == 1) {
1326                         num_cnt = sge_count - 1;
1327                 } else if (IS_DMA64)
1328                         num_cnt = sge_count - 2;
1329                 else
1330                         num_cnt = sge_count - 3;
1331         }
1332
1333         if (num_cnt > 0) {
1334                 sge_bytes = sge_sz * num_cnt;
1335
1336                 frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
1337                     ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
1338         }
1339         /* Main frame */
1340         frame_count += 1;
1341
1342         if (frame_count > 7)
1343                 frame_count = 8;
1344         return frame_count;
1345 }
1346
1347 /**
1348  * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
1349  * @instance:           Adapter soft state
1350  * @scp:                SCSI command
1351  * @cmd:                Command to be prepared in
1352  *
1353  * This function prepares CDB commands. These are typcially pass-through
1354  * commands to the devices.
1355  */
1356 static int
1357 megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
1358                    struct megasas_cmd *cmd)
1359 {
1360         u32 is_logical;
1361         u32 device_id;
1362         u16 flags = 0;
1363         struct megasas_pthru_frame *pthru;
1364
1365         is_logical = MEGASAS_IS_LOGICAL(scp->device);
1366         device_id = MEGASAS_DEV_INDEX(scp);
1367         pthru = (struct megasas_pthru_frame *)cmd->frame;
1368
1369         if (scp->sc_data_direction == DMA_TO_DEVICE)
1370                 flags = MFI_FRAME_DIR_WRITE;
1371         else if (scp->sc_data_direction == DMA_FROM_DEVICE)
1372                 flags = MFI_FRAME_DIR_READ;
1373         else if (scp->sc_data_direction == DMA_NONE)
1374                 flags = MFI_FRAME_DIR_NONE;
1375
1376         if (instance->flag_ieee == 1) {
1377                 flags |= MFI_FRAME_IEEE;
1378         }
1379
1380         /*
1381          * Prepare the DCDB frame
1382          */
1383         pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
1384         pthru->cmd_status = 0x0;
1385         pthru->scsi_status = 0x0;
1386         pthru->target_id = device_id;
1387         pthru->lun = scp->device->lun;
1388         pthru->cdb_len = scp->cmd_len;
1389         pthru->timeout = 0;
1390         pthru->pad_0 = 0;
1391         pthru->flags = cpu_to_le16(flags);
1392         pthru->data_xfer_len = cpu_to_le32(scsi_bufflen(scp));
1393
1394         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1395
1396         /*
1397          * If the command is for the tape device, set the
1398          * pthru timeout to the os layer timeout value.
1399          */
1400         if (scp->device->type == TYPE_TAPE) {
1401                 if ((scp->request->timeout / HZ) > 0xFFFF)
1402                         pthru->timeout = cpu_to_le16(0xFFFF);
1403                 else
1404                         pthru->timeout = cpu_to_le16(scp->request->timeout / HZ);
1405         }
1406
1407         /*
1408          * Construct SGL
1409          */
1410         if (instance->flag_ieee == 1) {
1411                 pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1412                 pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
1413                                                       &pthru->sgl);
1414         } else if (IS_DMA64) {
1415                 pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1416                 pthru->sge_count = megasas_make_sgl64(instance, scp,
1417                                                       &pthru->sgl);
1418         } else
1419                 pthru->sge_count = megasas_make_sgl32(instance, scp,
1420                                                       &pthru->sgl);
1421
1422         if (pthru->sge_count > instance->max_num_sge) {
1423                 dev_err(&instance->pdev->dev, "DCDB too many SGE NUM=%x\n",
1424                         pthru->sge_count);
1425                 return 0;
1426         }
1427
1428         /*
1429          * Sense info specific
1430          */
1431         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
1432         pthru->sense_buf_phys_addr_hi =
1433                 cpu_to_le32(upper_32_bits(cmd->sense_phys_addr));
1434         pthru->sense_buf_phys_addr_lo =
1435                 cpu_to_le32(lower_32_bits(cmd->sense_phys_addr));
1436
1437         /*
1438          * Compute the total number of frames this command consumes. FW uses
1439          * this number to pull sufficient number of frames from host memory.
1440          */
1441         cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
1442                                                         PTHRU_FRAME);
1443
1444         return cmd->frame_count;
1445 }
1446
1447 /**
1448  * megasas_build_ldio - Prepares IOs to logical devices
1449  * @instance:           Adapter soft state
1450  * @scp:                SCSI command
1451  * @cmd:                Command to be prepared
1452  *
1453  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
1454  */
1455 static int
1456 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
1457                    struct megasas_cmd *cmd)
1458 {
1459         u32 device_id;
1460         u8 sc = scp->cmnd[0];
1461         u16 flags = 0;
1462         struct megasas_io_frame *ldio;
1463
1464         device_id = MEGASAS_DEV_INDEX(scp);
1465         ldio = (struct megasas_io_frame *)cmd->frame;
1466
1467         if (scp->sc_data_direction == DMA_TO_DEVICE)
1468                 flags = MFI_FRAME_DIR_WRITE;
1469         else if (scp->sc_data_direction == DMA_FROM_DEVICE)
1470                 flags = MFI_FRAME_DIR_READ;
1471
1472         if (instance->flag_ieee == 1) {
1473                 flags |= MFI_FRAME_IEEE;
1474         }
1475
1476         /*
1477          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
1478          */
1479         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
1480         ldio->cmd_status = 0x0;
1481         ldio->scsi_status = 0x0;
1482         ldio->target_id = device_id;
1483         ldio->timeout = 0;
1484         ldio->reserved_0 = 0;
1485         ldio->pad_0 = 0;
1486         ldio->flags = cpu_to_le16(flags);
1487         ldio->start_lba_hi = 0;
1488         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
1489
1490         /*
1491          * 6-byte READ(0x08) or WRITE(0x0A) cdb
1492          */
1493         if (scp->cmd_len == 6) {
1494                 ldio->lba_count = cpu_to_le32((u32) scp->cmnd[4]);
1495                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[1] << 16) |
1496                                                  ((u32) scp->cmnd[2] << 8) |
1497                                                  (u32) scp->cmnd[3]);
1498
1499                 ldio->start_lba_lo &= cpu_to_le32(0x1FFFFF);
1500         }
1501
1502         /*
1503          * 10-byte READ(0x28) or WRITE(0x2A) cdb
1504          */
1505         else if (scp->cmd_len == 10) {
1506                 ldio->lba_count = cpu_to_le32((u32) scp->cmnd[8] |
1507                                               ((u32) scp->cmnd[7] << 8));
1508                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1509                                                  ((u32) scp->cmnd[3] << 16) |
1510                                                  ((u32) scp->cmnd[4] << 8) |
1511                                                  (u32) scp->cmnd[5]);
1512         }
1513
1514         /*
1515          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1516          */
1517         else if (scp->cmd_len == 12) {
1518                 ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1519                                               ((u32) scp->cmnd[7] << 16) |
1520                                               ((u32) scp->cmnd[8] << 8) |
1521                                               (u32) scp->cmnd[9]);
1522
1523                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1524                                                  ((u32) scp->cmnd[3] << 16) |
1525                                                  ((u32) scp->cmnd[4] << 8) |
1526                                                  (u32) scp->cmnd[5]);
1527         }
1528
1529         /*
1530          * 16-byte READ(0x88) or WRITE(0x8A) cdb
1531          */
1532         else if (scp->cmd_len == 16) {
1533                 ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[10] << 24) |
1534                                               ((u32) scp->cmnd[11] << 16) |
1535                                               ((u32) scp->cmnd[12] << 8) |
1536                                               (u32) scp->cmnd[13]);
1537
1538                 ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1539                                                  ((u32) scp->cmnd[7] << 16) |
1540                                                  ((u32) scp->cmnd[8] << 8) |
1541                                                  (u32) scp->cmnd[9]);
1542
1543                 ldio->start_lba_hi = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1544                                                  ((u32) scp->cmnd[3] << 16) |
1545                                                  ((u32) scp->cmnd[4] << 8) |
1546                                                  (u32) scp->cmnd[5]);
1547
1548         }
1549
1550         /*
1551          * Construct SGL
1552          */
1553         if (instance->flag_ieee) {
1554                 ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1555                 ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1556                                               &ldio->sgl);
1557         } else if (IS_DMA64) {
1558                 ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1559                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1560         } else
1561                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1562
1563         if (ldio->sge_count > instance->max_num_sge) {
1564                 dev_err(&instance->pdev->dev, "build_ld_io: sge_count = %x\n",
1565                         ldio->sge_count);
1566                 return 0;
1567         }
1568
1569         /*
1570          * Sense info specific
1571          */
1572         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1573         ldio->sense_buf_phys_addr_hi = 0;
1574         ldio->sense_buf_phys_addr_lo = cpu_to_le32(cmd->sense_phys_addr);
1575
1576         /*
1577          * Compute the total number of frames this command consumes. FW uses
1578          * this number to pull sufficient number of frames from host memory.
1579          */
1580         cmd->frame_count = megasas_get_frame_count(instance,
1581                         ldio->sge_count, IO_FRAME);
1582
1583         return cmd->frame_count;
1584 }
1585
1586 /**
1587  * megasas_cmd_type -           Checks if the cmd is for logical drive/sysPD
1588  *                              and whether it's RW or non RW
1589  * @scmd:                       SCSI command
1590  *
1591  */
1592 inline int megasas_cmd_type(struct scsi_cmnd *cmd)
1593 {
1594         int ret;
1595
1596         switch (cmd->cmnd[0]) {
1597         case READ_10:
1598         case WRITE_10:
1599         case READ_12:
1600         case WRITE_12:
1601         case READ_6:
1602         case WRITE_6:
1603         case READ_16:
1604         case WRITE_16:
1605                 ret = (MEGASAS_IS_LOGICAL(cmd->device)) ?
1606                         READ_WRITE_LDIO : READ_WRITE_SYSPDIO;
1607                 break;
1608         default:
1609                 ret = (MEGASAS_IS_LOGICAL(cmd->device)) ?
1610                         NON_READ_WRITE_LDIO : NON_READ_WRITE_SYSPDIO;
1611         }
1612         return ret;
1613 }
1614
1615  /**
1616  * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
1617  *                                      in FW
1618  * @instance:                           Adapter soft state
1619  */
1620 static inline void
1621 megasas_dump_pending_frames(struct megasas_instance *instance)
1622 {
1623         struct megasas_cmd *cmd;
1624         int i,n;
1625         union megasas_sgl *mfi_sgl;
1626         struct megasas_io_frame *ldio;
1627         struct megasas_pthru_frame *pthru;
1628         u32 sgcount;
1629         u16 max_cmd = instance->max_fw_cmds;
1630
1631         dev_err(&instance->pdev->dev, "[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1632         dev_err(&instance->pdev->dev, "[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1633         if (IS_DMA64)
1634                 dev_err(&instance->pdev->dev, "[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1635         else
1636                 dev_err(&instance->pdev->dev, "[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1637
1638         dev_err(&instance->pdev->dev, "[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1639         for (i = 0; i < max_cmd; i++) {
1640                 cmd = instance->cmd_list[i];
1641                 if (!cmd->scmd)
1642                         continue;
1643                 dev_err(&instance->pdev->dev, "[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1644                 if (megasas_cmd_type(cmd->scmd) == READ_WRITE_LDIO) {
1645                         ldio = (struct megasas_io_frame *)cmd->frame;
1646                         mfi_sgl = &ldio->sgl;
1647                         sgcount = ldio->sge_count;
1648                         dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x,"
1649                         " lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1650                         instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id,
1651                         le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi),
1652                         le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount);
1653                 } else {
1654                         pthru = (struct megasas_pthru_frame *) cmd->frame;
1655                         mfi_sgl = &pthru->sgl;
1656                         sgcount = pthru->sge_count;
1657                         dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, "
1658                         "lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1659                         instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id,
1660                         pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len),
1661                         le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount);
1662                 }
1663                 if (megasas_dbg_lvl & MEGASAS_DBG_LVL) {
1664                         for (n = 0; n < sgcount; n++) {
1665                                 if (IS_DMA64)
1666                                         dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%llx\n",
1667                                                 le32_to_cpu(mfi_sgl->sge64[n].length),
1668                                                 le64_to_cpu(mfi_sgl->sge64[n].phys_addr));
1669                                 else
1670                                         dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%x\n",
1671                                                 le32_to_cpu(mfi_sgl->sge32[n].length),
1672                                                 le32_to_cpu(mfi_sgl->sge32[n].phys_addr));
1673                         }
1674                 }
1675         } /*for max_cmd*/
1676         dev_err(&instance->pdev->dev, "[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1677         for (i = 0; i < max_cmd; i++) {
1678
1679                 cmd = instance->cmd_list[i];
1680
1681                 if (cmd->sync_cmd == 1)
1682                         dev_err(&instance->pdev->dev, "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1683         }
1684         dev_err(&instance->pdev->dev, "[%d]: Dumping Done\n\n",instance->host->host_no);
1685 }
1686
1687 u32
1688 megasas_build_and_issue_cmd(struct megasas_instance *instance,
1689                             struct scsi_cmnd *scmd)
1690 {
1691         struct megasas_cmd *cmd;
1692         u32 frame_count;
1693
1694         cmd = megasas_get_cmd(instance);
1695         if (!cmd)
1696                 return SCSI_MLQUEUE_HOST_BUSY;
1697
1698         /*
1699          * Logical drive command
1700          */
1701         if (megasas_cmd_type(scmd) == READ_WRITE_LDIO)
1702                 frame_count = megasas_build_ldio(instance, scmd, cmd);
1703         else
1704                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
1705
1706         if (!frame_count)
1707                 goto out_return_cmd;
1708
1709         cmd->scmd = scmd;
1710         scmd->SCp.ptr = (char *)cmd;
1711
1712         /*
1713          * Issue the command to the FW
1714          */
1715         atomic_inc(&instance->fw_outstanding);
1716
1717         instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1718                                 cmd->frame_count-1, instance->reg_set);
1719
1720         return 0;
1721 out_return_cmd:
1722         megasas_return_cmd(instance, cmd);
1723         return SCSI_MLQUEUE_HOST_BUSY;
1724 }
1725
1726
1727 /**
1728  * megasas_queue_command -      Queue entry point
1729  * @scmd:                       SCSI command to be queued
1730  * @done:                       Callback entry point
1731  */
1732 static int
1733 megasas_queue_command(struct Scsi_Host *shost, struct scsi_cmnd *scmd)
1734 {
1735         struct megasas_instance *instance;
1736         struct MR_PRIV_DEVICE *mr_device_priv_data;
1737
1738         instance = (struct megasas_instance *)
1739             scmd->device->host->hostdata;
1740
1741         if (instance->unload == 1) {
1742                 scmd->result = DID_NO_CONNECT << 16;
1743                 scmd->scsi_done(scmd);
1744                 return 0;
1745         }
1746
1747         if (instance->issuepend_done == 0)
1748                 return SCSI_MLQUEUE_HOST_BUSY;
1749
1750
1751         /* Check for an mpio path and adjust behavior */
1752         if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
1753                 if (megasas_check_mpio_paths(instance, scmd) ==
1754                     (DID_REQUEUE << 16)) {
1755                         return SCSI_MLQUEUE_HOST_BUSY;
1756                 } else {
1757                         scmd->result = DID_NO_CONNECT << 16;
1758                         scmd->scsi_done(scmd);
1759                         return 0;
1760                 }
1761         }
1762
1763         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
1764                 scmd->result = DID_NO_CONNECT << 16;
1765                 scmd->scsi_done(scmd);
1766                 return 0;
1767         }
1768
1769         mr_device_priv_data = scmd->device->hostdata;
1770         if (!mr_device_priv_data) {
1771                 scmd->result = DID_NO_CONNECT << 16;
1772                 scmd->scsi_done(scmd);
1773                 return 0;
1774         }
1775
1776         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL)
1777                 return SCSI_MLQUEUE_HOST_BUSY;
1778
1779         if (mr_device_priv_data->tm_busy)
1780                 return SCSI_MLQUEUE_DEVICE_BUSY;
1781
1782
1783         scmd->result = 0;
1784
1785         if (MEGASAS_IS_LOGICAL(scmd->device) &&
1786             (scmd->device->id >= instance->fw_supported_vd_count ||
1787                 scmd->device->lun)) {
1788                 scmd->result = DID_BAD_TARGET << 16;
1789                 goto out_done;
1790         }
1791
1792         if ((scmd->cmnd[0] == SYNCHRONIZE_CACHE) &&
1793             MEGASAS_IS_LOGICAL(scmd->device) &&
1794             (!instance->fw_sync_cache_support)) {
1795                 scmd->result = DID_OK << 16;
1796                 goto out_done;
1797         }
1798
1799         return instance->instancet->build_and_issue_cmd(instance, scmd);
1800
1801  out_done:
1802         scmd->scsi_done(scmd);
1803         return 0;
1804 }
1805
1806 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1807 {
1808         int i;
1809
1810         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1811
1812                 if ((megasas_mgmt_info.instance[i]) &&
1813                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1814                         return megasas_mgmt_info.instance[i];
1815         }
1816
1817         return NULL;
1818 }
1819
1820 /*
1821 * megasas_set_dynamic_target_properties -
1822 * Device property set by driver may not be static and it is required to be
1823 * updated after OCR
1824 *
1825 * set tm_capable.
1826 * set dma alignment (only for eedp protection enable vd).
1827 *
1828 * @sdev: OS provided scsi device
1829 *
1830 * Returns void
1831 */
1832 void megasas_set_dynamic_target_properties(struct scsi_device *sdev,
1833                                            bool is_target_prop)
1834 {
1835         u16 pd_index = 0, ld;
1836         u32 device_id;
1837         struct megasas_instance *instance;
1838         struct fusion_context *fusion;
1839         struct MR_PRIV_DEVICE *mr_device_priv_data;
1840         struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1841         struct MR_LD_RAID *raid;
1842         struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
1843
1844         instance = megasas_lookup_instance(sdev->host->host_no);
1845         fusion = instance->ctrl_context;
1846         mr_device_priv_data = sdev->hostdata;
1847
1848         if (!fusion || !mr_device_priv_data)
1849                 return;
1850
1851         if (MEGASAS_IS_LOGICAL(sdev)) {
1852                 device_id = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL)
1853                                         + sdev->id;
1854                 local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
1855                 ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
1856                 if (ld >= instance->fw_supported_vd_count)
1857                         return;
1858                 raid = MR_LdRaidGet(ld, local_map_ptr);
1859
1860                 if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER)
1861                 blk_queue_update_dma_alignment(sdev->request_queue, 0x7);
1862
1863                 mr_device_priv_data->is_tm_capable =
1864                         raid->capability.tmCapable;
1865         } else if (instance->use_seqnum_jbod_fp) {
1866                 pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1867                         sdev->id;
1868                 pd_sync = (void *)fusion->pd_seq_sync
1869                                 [(instance->pd_seq_map_id - 1) & 1];
1870                 mr_device_priv_data->is_tm_capable =
1871                         pd_sync->seq[pd_index].capability.tmCapable;
1872         }
1873
1874         if (is_target_prop && instance->tgt_prop->reset_tmo) {
1875                 /*
1876                  * If FW provides a target reset timeout value, driver will use
1877                  * it. If not set, fallback to default values.
1878                  */
1879                 mr_device_priv_data->target_reset_tmo =
1880                         min_t(u8, instance->max_reset_tmo,
1881                               instance->tgt_prop->reset_tmo);
1882                 mr_device_priv_data->task_abort_tmo = instance->task_abort_tmo;
1883         } else {
1884                 mr_device_priv_data->target_reset_tmo =
1885                                                 MEGASAS_DEFAULT_TM_TIMEOUT;
1886                 mr_device_priv_data->task_abort_tmo =
1887                                                 MEGASAS_DEFAULT_TM_TIMEOUT;
1888         }
1889 }
1890
1891 /*
1892  * megasas_set_nvme_device_properties -
1893  * set nomerges=2
1894  * set virtual page boundary = 4K (current mr_nvme_pg_size is 4K).
1895  * set maximum io transfer = MDTS of NVME device provided by MR firmware.
1896  *
1897  * MR firmware provides value in KB. Caller of this function converts
1898  * kb into bytes.
1899  *
1900  * e.a MDTS=5 means 2^5 * nvme page size. (In case of 4K page size,
1901  * MR firmware provides value 128 as (32 * 4K) = 128K.
1902  *
1903  * @sdev:                               scsi device
1904  * @max_io_size:                                maximum io transfer size
1905  *
1906  */
1907 static inline void
1908 megasas_set_nvme_device_properties(struct scsi_device *sdev, u32 max_io_size)
1909 {
1910         struct megasas_instance *instance;
1911         u32 mr_nvme_pg_size;
1912
1913         instance = (struct megasas_instance *)sdev->host->hostdata;
1914         mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
1915                                 MR_DEFAULT_NVME_PAGE_SIZE);
1916
1917         blk_queue_max_hw_sectors(sdev->request_queue, (max_io_size / 512));
1918
1919         blk_queue_flag_set(QUEUE_FLAG_NOMERGES, sdev->request_queue);
1920         blk_queue_virt_boundary(sdev->request_queue, mr_nvme_pg_size - 1);
1921 }
1922
1923
1924 /*
1925  * megasas_set_static_target_properties -
1926  * Device property set by driver are static and it is not required to be
1927  * updated after OCR.
1928  *
1929  * set io timeout
1930  * set device queue depth
1931  * set nvme device properties. see - megasas_set_nvme_device_properties
1932  *
1933  * @sdev:                               scsi device
1934  * @is_target_prop                      true, if fw provided target properties.
1935  */
1936 static void megasas_set_static_target_properties(struct scsi_device *sdev,
1937                                                  bool is_target_prop)
1938 {
1939         u8 interface_type;
1940         u32 device_qd = MEGASAS_DEFAULT_CMD_PER_LUN;
1941         u32 max_io_size_kb = MR_DEFAULT_NVME_MDTS_KB;
1942         u32 tgt_device_qd;
1943         struct megasas_instance *instance;
1944         struct MR_PRIV_DEVICE *mr_device_priv_data;
1945
1946         instance = megasas_lookup_instance(sdev->host->host_no);
1947         mr_device_priv_data = sdev->hostdata;
1948         interface_type  = mr_device_priv_data->interface_type;
1949
1950         /*
1951          * The RAID firmware may require extended timeouts.
1952          */
1953         blk_queue_rq_timeout(sdev->request_queue, scmd_timeout * HZ);
1954
1955         switch (interface_type) {
1956         case SAS_PD:
1957                 device_qd = MEGASAS_SAS_QD;
1958                 break;
1959         case SATA_PD:
1960                 device_qd = MEGASAS_SATA_QD;
1961                 break;
1962         case NVME_PD:
1963                 device_qd = MEGASAS_NVME_QD;
1964                 break;
1965         }
1966
1967         if (is_target_prop) {
1968                 tgt_device_qd = le32_to_cpu(instance->tgt_prop->device_qdepth);
1969                 if (tgt_device_qd &&
1970                     (tgt_device_qd <= instance->host->can_queue))
1971                         device_qd = tgt_device_qd;
1972
1973                 /* max_io_size_kb will be set to non zero for
1974                  * nvme based vd and syspd.
1975                  */
1976                 max_io_size_kb = le32_to_cpu(instance->tgt_prop->max_io_size_kb);
1977         }
1978
1979         if (instance->nvme_page_size && max_io_size_kb)
1980                 megasas_set_nvme_device_properties(sdev, (max_io_size_kb << 10));
1981
1982         scsi_change_queue_depth(sdev, device_qd);
1983
1984 }
1985
1986
1987 static int megasas_slave_configure(struct scsi_device *sdev)
1988 {
1989         u16 pd_index = 0;
1990         struct megasas_instance *instance;
1991         int ret_target_prop = DCMD_FAILED;
1992         bool is_target_prop = false;
1993
1994         instance = megasas_lookup_instance(sdev->host->host_no);
1995         if (instance->pd_list_not_supported) {
1996                 if (!MEGASAS_IS_LOGICAL(sdev) && sdev->type == TYPE_DISK) {
1997                         pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1998                                 sdev->id;
1999                         if (instance->pd_list[pd_index].driveState !=
2000                                 MR_PD_STATE_SYSTEM)
2001                                 return -ENXIO;
2002                 }
2003         }
2004
2005         mutex_lock(&instance->reset_mutex);
2006         /* Send DCMD to Firmware and cache the information */
2007         if ((instance->pd_info) && !MEGASAS_IS_LOGICAL(sdev))
2008                 megasas_get_pd_info(instance, sdev);
2009
2010         /* Some ventura firmware may not have instance->nvme_page_size set.
2011          * Do not send MR_DCMD_DRV_GET_TARGET_PROP
2012          */
2013         if ((instance->tgt_prop) && (instance->nvme_page_size))
2014                 ret_target_prop = megasas_get_target_prop(instance, sdev);
2015
2016         is_target_prop = (ret_target_prop == DCMD_SUCCESS) ? true : false;
2017         megasas_set_static_target_properties(sdev, is_target_prop);
2018
2019         /* This sdev property may change post OCR */
2020         megasas_set_dynamic_target_properties(sdev, is_target_prop);
2021
2022         mutex_unlock(&instance->reset_mutex);
2023
2024         return 0;
2025 }
2026
2027 static int megasas_slave_alloc(struct scsi_device *sdev)
2028 {
2029         u16 pd_index = 0;
2030         struct megasas_instance *instance ;
2031         struct MR_PRIV_DEVICE *mr_device_priv_data;
2032
2033         instance = megasas_lookup_instance(sdev->host->host_no);
2034         if (!MEGASAS_IS_LOGICAL(sdev)) {
2035                 /*
2036                  * Open the OS scan to the SYSTEM PD
2037                  */
2038                 pd_index =
2039                         (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
2040                         sdev->id;
2041                 if ((instance->pd_list_not_supported ||
2042                         instance->pd_list[pd_index].driveState ==
2043                         MR_PD_STATE_SYSTEM)) {
2044                         goto scan_target;
2045                 }
2046                 return -ENXIO;
2047         }
2048
2049 scan_target:
2050         mr_device_priv_data = kzalloc(sizeof(*mr_device_priv_data),
2051                                         GFP_KERNEL);
2052         if (!mr_device_priv_data)
2053                 return -ENOMEM;
2054         sdev->hostdata = mr_device_priv_data;
2055
2056         atomic_set(&mr_device_priv_data->r1_ldio_hint,
2057                    instance->r1_ldio_hint_default);
2058         return 0;
2059 }
2060
2061 static void megasas_slave_destroy(struct scsi_device *sdev)
2062 {
2063         kfree(sdev->hostdata);
2064         sdev->hostdata = NULL;
2065 }
2066
2067 /*
2068 * megasas_complete_outstanding_ioctls - Complete outstanding ioctls after a
2069 *                                       kill adapter
2070 * @instance:                            Adapter soft state
2071 *
2072 */
2073 static void megasas_complete_outstanding_ioctls(struct megasas_instance *instance)
2074 {
2075         int i;
2076         struct megasas_cmd *cmd_mfi;
2077         struct megasas_cmd_fusion *cmd_fusion;
2078         struct fusion_context *fusion = instance->ctrl_context;
2079
2080         /* Find all outstanding ioctls */
2081         if (fusion) {
2082                 for (i = 0; i < instance->max_fw_cmds; i++) {
2083                         cmd_fusion = fusion->cmd_list[i];
2084                         if (cmd_fusion->sync_cmd_idx != (u32)ULONG_MAX) {
2085                                 cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
2086                                 if (cmd_mfi->sync_cmd &&
2087                                     (cmd_mfi->frame->hdr.cmd != MFI_CMD_ABORT)) {
2088                                         cmd_mfi->frame->hdr.cmd_status =
2089                                                         MFI_STAT_WRONG_STATE;
2090                                         megasas_complete_cmd(instance,
2091                                                              cmd_mfi, DID_OK);
2092                                 }
2093                         }
2094                 }
2095         } else {
2096                 for (i = 0; i < instance->max_fw_cmds; i++) {
2097                         cmd_mfi = instance->cmd_list[i];
2098                         if (cmd_mfi->sync_cmd && cmd_mfi->frame->hdr.cmd !=
2099                                 MFI_CMD_ABORT)
2100                                 megasas_complete_cmd(instance, cmd_mfi, DID_OK);
2101                 }
2102         }
2103 }
2104
2105
2106 void megaraid_sas_kill_hba(struct megasas_instance *instance)
2107 {
2108         /* Set critical error to block I/O & ioctls in case caller didn't */
2109         atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR);
2110         /* Wait 1 second to ensure IO or ioctls in build have posted */
2111         msleep(1000);
2112         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2113                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
2114                 (instance->adapter_type != MFI_SERIES)) {
2115                 if (!instance->requestorId) {
2116                         writel(MFI_STOP_ADP, &instance->reg_set->doorbell);
2117                         /* Flush */
2118                         readl(&instance->reg_set->doorbell);
2119                 }
2120                 if (instance->requestorId && instance->peerIsPresent)
2121                         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
2122         } else {
2123                 writel(MFI_STOP_ADP,
2124                         &instance->reg_set->inbound_doorbell);
2125         }
2126         /* Complete outstanding ioctls when adapter is killed */
2127         megasas_complete_outstanding_ioctls(instance);
2128 }
2129
2130  /**
2131   * megasas_check_and_restore_queue_depth - Check if queue depth needs to be
2132   *                                     restored to max value
2133   * @instance:                  Adapter soft state
2134   *
2135   */
2136 void
2137 megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
2138 {
2139         unsigned long flags;
2140
2141         if (instance->flag & MEGASAS_FW_BUSY
2142             && time_after(jiffies, instance->last_time + 5 * HZ)
2143             && atomic_read(&instance->fw_outstanding) <
2144             instance->throttlequeuedepth + 1) {
2145
2146                 spin_lock_irqsave(instance->host->host_lock, flags);
2147                 instance->flag &= ~MEGASAS_FW_BUSY;
2148
2149                 instance->host->can_queue = instance->cur_can_queue;
2150                 spin_unlock_irqrestore(instance->host->host_lock, flags);
2151         }
2152 }
2153
2154 /**
2155  * megasas_complete_cmd_dpc      -      Returns FW's controller structure
2156  * @instance_addr:                      Address of adapter soft state
2157  *
2158  * Tasklet to complete cmds
2159  */
2160 static void megasas_complete_cmd_dpc(unsigned long instance_addr)
2161 {
2162         u32 producer;
2163         u32 consumer;
2164         u32 context;
2165         struct megasas_cmd *cmd;
2166         struct megasas_instance *instance =
2167                                 (struct megasas_instance *)instance_addr;
2168         unsigned long flags;
2169
2170         /* If we have already declared adapter dead, donot complete cmds */
2171         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
2172                 return;
2173
2174         spin_lock_irqsave(&instance->completion_lock, flags);
2175
2176         producer = le32_to_cpu(*instance->producer);
2177         consumer = le32_to_cpu(*instance->consumer);
2178
2179         while (consumer != producer) {
2180                 context = le32_to_cpu(instance->reply_queue[consumer]);
2181                 if (context >= instance->max_fw_cmds) {
2182                         dev_err(&instance->pdev->dev, "Unexpected context value %x\n",
2183                                 context);
2184                         BUG();
2185                 }
2186
2187                 cmd = instance->cmd_list[context];
2188
2189                 megasas_complete_cmd(instance, cmd, DID_OK);
2190
2191                 consumer++;
2192                 if (consumer == (instance->max_fw_cmds + 1)) {
2193                         consumer = 0;
2194                 }
2195         }
2196
2197         *instance->consumer = cpu_to_le32(producer);
2198
2199         spin_unlock_irqrestore(&instance->completion_lock, flags);
2200
2201         /*
2202          * Check if we can restore can_queue
2203          */
2204         megasas_check_and_restore_queue_depth(instance);
2205 }
2206
2207 static void megasas_sriov_heartbeat_handler(struct timer_list *t);
2208
2209 /**
2210  * megasas_start_timer - Initializes sriov heartbeat timer object
2211  * @instance:           Adapter soft state
2212  *
2213  */
2214 void megasas_start_timer(struct megasas_instance *instance)
2215 {
2216         struct timer_list *timer = &instance->sriov_heartbeat_timer;
2217
2218         timer_setup(timer, megasas_sriov_heartbeat_handler, 0);
2219         timer->expires = jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF;
2220         add_timer(timer);
2221 }
2222
2223 static void
2224 megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
2225
2226 static void
2227 process_fw_state_change_wq(struct work_struct *work);
2228
2229 void megasas_do_ocr(struct megasas_instance *instance)
2230 {
2231         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
2232         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
2233         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
2234                 *instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
2235         }
2236         instance->instancet->disable_intr(instance);
2237         atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
2238         instance->issuepend_done = 0;
2239
2240         atomic_set(&instance->fw_outstanding, 0);
2241         megasas_internal_reset_defer_cmds(instance);
2242         process_fw_state_change_wq(&instance->work_init);
2243 }
2244
2245 static int megasas_get_ld_vf_affiliation_111(struct megasas_instance *instance,
2246                                             int initial)
2247 {
2248         struct megasas_cmd *cmd;
2249         struct megasas_dcmd_frame *dcmd;
2250         struct MR_LD_VF_AFFILIATION_111 *new_affiliation_111 = NULL;
2251         dma_addr_t new_affiliation_111_h;
2252         int ld, retval = 0;
2253         u8 thisVf;
2254
2255         cmd = megasas_get_cmd(instance);
2256
2257         if (!cmd) {
2258                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation_111:"
2259                        "Failed to get cmd for scsi%d\n",
2260                         instance->host->host_no);
2261                 return -ENOMEM;
2262         }
2263
2264         dcmd = &cmd->frame->dcmd;
2265
2266         if (!instance->vf_affiliation_111) {
2267                 dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF "
2268                        "affiliation for scsi%d\n", instance->host->host_no);
2269                 megasas_return_cmd(instance, cmd);
2270                 return -ENOMEM;
2271         }
2272
2273         if (initial)
2274                         memset(instance->vf_affiliation_111, 0,
2275                                sizeof(struct MR_LD_VF_AFFILIATION_111));
2276         else {
2277                 new_affiliation_111 =
2278                         dma_alloc_coherent(&instance->pdev->dev,
2279                                            sizeof(struct MR_LD_VF_AFFILIATION_111),
2280                                            &new_affiliation_111_h, GFP_KERNEL);
2281                 if (!new_affiliation_111) {
2282                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate "
2283                                "memory for new affiliation for scsi%d\n",
2284                                instance->host->host_no);
2285                         megasas_return_cmd(instance, cmd);
2286                         return -ENOMEM;
2287                 }
2288         }
2289
2290         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2291
2292         dcmd->cmd = MFI_CMD_DCMD;
2293         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2294         dcmd->sge_count = 1;
2295         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2296         dcmd->timeout = 0;
2297         dcmd->pad_0 = 0;
2298         dcmd->data_xfer_len =
2299                 cpu_to_le32(sizeof(struct MR_LD_VF_AFFILIATION_111));
2300         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS_111);
2301
2302         if (initial)
2303                 dcmd->sgl.sge32[0].phys_addr =
2304                         cpu_to_le32(instance->vf_affiliation_111_h);
2305         else
2306                 dcmd->sgl.sge32[0].phys_addr =
2307                         cpu_to_le32(new_affiliation_111_h);
2308
2309         dcmd->sgl.sge32[0].length = cpu_to_le32(
2310                 sizeof(struct MR_LD_VF_AFFILIATION_111));
2311
2312         dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for "
2313                "scsi%d\n", instance->host->host_no);
2314
2315         if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {
2316                 dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD"
2317                        " failed with status 0x%x for scsi%d\n",
2318                        dcmd->cmd_status, instance->host->host_no);
2319                 retval = 1; /* Do a scan if we couldn't get affiliation */
2320                 goto out;
2321         }
2322
2323         if (!initial) {
2324                 thisVf = new_affiliation_111->thisVf;
2325                 for (ld = 0 ; ld < new_affiliation_111->vdCount; ld++)
2326                         if (instance->vf_affiliation_111->map[ld].policy[thisVf] !=
2327                             new_affiliation_111->map[ld].policy[thisVf]) {
2328                                 dev_warn(&instance->pdev->dev, "SR-IOV: "
2329                                        "Got new LD/VF affiliation for scsi%d\n",
2330                                        instance->host->host_no);
2331                                 memcpy(instance->vf_affiliation_111,
2332                                        new_affiliation_111,
2333                                        sizeof(struct MR_LD_VF_AFFILIATION_111));
2334                                 retval = 1;
2335                                 goto out;
2336                         }
2337         }
2338 out:
2339         if (new_affiliation_111) {
2340                 dma_free_coherent(&instance->pdev->dev,
2341                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
2342                                     new_affiliation_111,
2343                                     new_affiliation_111_h);
2344         }
2345
2346         megasas_return_cmd(instance, cmd);
2347
2348         return retval;
2349 }
2350
2351 static int megasas_get_ld_vf_affiliation_12(struct megasas_instance *instance,
2352                                             int initial)
2353 {
2354         struct megasas_cmd *cmd;
2355         struct megasas_dcmd_frame *dcmd;
2356         struct MR_LD_VF_AFFILIATION *new_affiliation = NULL;
2357         struct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL;
2358         dma_addr_t new_affiliation_h;
2359         int i, j, retval = 0, found = 0, doscan = 0;
2360         u8 thisVf;
2361
2362         cmd = megasas_get_cmd(instance);
2363
2364         if (!cmd) {
2365                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_vf_affiliation12: "
2366                        "Failed to get cmd for scsi%d\n",
2367                        instance->host->host_no);
2368                 return -ENOMEM;
2369         }
2370
2371         dcmd = &cmd->frame->dcmd;
2372
2373         if (!instance->vf_affiliation) {
2374                 dev_warn(&instance->pdev->dev, "SR-IOV: Couldn't get LD/VF "
2375                        "affiliation for scsi%d\n", instance->host->host_no);
2376                 megasas_return_cmd(instance, cmd);
2377                 return -ENOMEM;
2378         }
2379
2380         if (initial)
2381                 memset(instance->vf_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *
2382                        sizeof(struct MR_LD_VF_AFFILIATION));
2383         else {
2384                 new_affiliation =
2385                         dma_alloc_coherent(&instance->pdev->dev,
2386                                            (MAX_LOGICAL_DRIVES + 1) * sizeof(struct MR_LD_VF_AFFILIATION),
2387                                            &new_affiliation_h, GFP_KERNEL);
2388                 if (!new_affiliation) {
2389                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate "
2390                                "memory for new affiliation for scsi%d\n",
2391                                instance->host->host_no);
2392                         megasas_return_cmd(instance, cmd);
2393                         return -ENOMEM;
2394                 }
2395         }
2396
2397         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2398
2399         dcmd->cmd = MFI_CMD_DCMD;
2400         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2401         dcmd->sge_count = 1;
2402         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2403         dcmd->timeout = 0;
2404         dcmd->pad_0 = 0;
2405         dcmd->data_xfer_len = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2406                 sizeof(struct MR_LD_VF_AFFILIATION));
2407         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS);
2408
2409         if (initial)
2410                 dcmd->sgl.sge32[0].phys_addr =
2411                         cpu_to_le32(instance->vf_affiliation_h);
2412         else
2413                 dcmd->sgl.sge32[0].phys_addr =
2414                         cpu_to_le32(new_affiliation_h);
2415
2416         dcmd->sgl.sge32[0].length = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *
2417                 sizeof(struct MR_LD_VF_AFFILIATION));
2418
2419         dev_warn(&instance->pdev->dev, "SR-IOV: Getting LD/VF affiliation for "
2420                "scsi%d\n", instance->host->host_no);
2421
2422
2423         if (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {
2424                 dev_warn(&instance->pdev->dev, "SR-IOV: LD/VF affiliation DCMD"
2425                        " failed with status 0x%x for scsi%d\n",
2426                        dcmd->cmd_status, instance->host->host_no);
2427                 retval = 1; /* Do a scan if we couldn't get affiliation */
2428                 goto out;
2429         }
2430
2431         if (!initial) {
2432                 if (!new_affiliation->ldCount) {
2433                         dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF "
2434                                "affiliation for passive path for scsi%d\n",
2435                                instance->host->host_no);
2436                         retval = 1;
2437                         goto out;
2438                 }
2439                 newmap = new_affiliation->map;
2440                 savedmap = instance->vf_affiliation->map;
2441                 thisVf = new_affiliation->thisVf;
2442                 for (i = 0 ; i < new_affiliation->ldCount; i++) {
2443                         found = 0;
2444                         for (j = 0; j < instance->vf_affiliation->ldCount;
2445                              j++) {
2446                                 if (newmap->ref.targetId ==
2447                                     savedmap->ref.targetId) {
2448                                         found = 1;
2449                                         if (newmap->policy[thisVf] !=
2450                                             savedmap->policy[thisVf]) {
2451                                                 doscan = 1;
2452                                                 goto out;
2453                                         }
2454                                 }
2455                                 savedmap = (struct MR_LD_VF_MAP *)
2456                                         ((unsigned char *)savedmap +
2457                                          savedmap->size);
2458                         }
2459                         if (!found && newmap->policy[thisVf] !=
2460                             MR_LD_ACCESS_HIDDEN) {
2461                                 doscan = 1;
2462                                 goto out;
2463                         }
2464                         newmap = (struct MR_LD_VF_MAP *)
2465                                 ((unsigned char *)newmap + newmap->size);
2466                 }
2467
2468                 newmap = new_affiliation->map;
2469                 savedmap = instance->vf_affiliation->map;
2470
2471                 for (i = 0 ; i < instance->vf_affiliation->ldCount; i++) {
2472                         found = 0;
2473                         for (j = 0 ; j < new_affiliation->ldCount; j++) {
2474                                 if (savedmap->ref.targetId ==
2475                                     newmap->ref.targetId) {
2476                                         found = 1;
2477                                         if (savedmap->policy[thisVf] !=
2478                                             newmap->policy[thisVf]) {
2479                                                 doscan = 1;
2480                                                 goto out;
2481                                         }
2482                                 }
2483                                 newmap = (struct MR_LD_VF_MAP *)
2484                                         ((unsigned char *)newmap +
2485                                          newmap->size);
2486                         }
2487                         if (!found && savedmap->policy[thisVf] !=
2488                             MR_LD_ACCESS_HIDDEN) {
2489                                 doscan = 1;
2490                                 goto out;
2491                         }
2492                         savedmap = (struct MR_LD_VF_MAP *)
2493                                 ((unsigned char *)savedmap +
2494                                  savedmap->size);
2495                 }
2496         }
2497 out:
2498         if (doscan) {
2499                 dev_warn(&instance->pdev->dev, "SR-IOV: Got new LD/VF "
2500                        "affiliation for scsi%d\n", instance->host->host_no);
2501                 memcpy(instance->vf_affiliation, new_affiliation,
2502                        new_affiliation->size);
2503                 retval = 1;
2504         }
2505
2506         if (new_affiliation)
2507                 dma_free_coherent(&instance->pdev->dev,
2508                                     (MAX_LOGICAL_DRIVES + 1) *
2509                                     sizeof(struct MR_LD_VF_AFFILIATION),
2510                                     new_affiliation, new_affiliation_h);
2511         megasas_return_cmd(instance, cmd);
2512
2513         return retval;
2514 }
2515
2516 /* This function will get the current SR-IOV LD/VF affiliation */
2517 static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
2518         int initial)
2519 {
2520         int retval;
2521
2522         if (instance->PlasmaFW111)
2523                 retval = megasas_get_ld_vf_affiliation_111(instance, initial);
2524         else
2525                 retval = megasas_get_ld_vf_affiliation_12(instance, initial);
2526         return retval;
2527 }
2528
2529 /* This function will tell FW to start the SR-IOV heartbeat */
2530 int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
2531                                          int initial)
2532 {
2533         struct megasas_cmd *cmd;
2534         struct megasas_dcmd_frame *dcmd;
2535         int retval = 0;
2536
2537         cmd = megasas_get_cmd(instance);
2538
2539         if (!cmd) {
2540                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_sriov_start_heartbeat: "
2541                        "Failed to get cmd for scsi%d\n",
2542                        instance->host->host_no);
2543                 return -ENOMEM;
2544         }
2545
2546         dcmd = &cmd->frame->dcmd;
2547
2548         if (initial) {
2549                 instance->hb_host_mem =
2550                         dma_alloc_coherent(&instance->pdev->dev,
2551                                            sizeof(struct MR_CTRL_HB_HOST_MEM),
2552                                            &instance->hb_host_mem_h,
2553                                            GFP_KERNEL);
2554                 if (!instance->hb_host_mem) {
2555                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "SR-IOV: Couldn't allocate"
2556                                " memory for heartbeat host memory for scsi%d\n",
2557                                instance->host->host_no);
2558                         retval = -ENOMEM;
2559                         goto out;
2560                 }
2561         }
2562
2563         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2564
2565         dcmd->mbox.s[0] = cpu_to_le16(sizeof(struct MR_CTRL_HB_HOST_MEM));
2566         dcmd->cmd = MFI_CMD_DCMD;
2567         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
2568         dcmd->sge_count = 1;
2569         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);
2570         dcmd->timeout = 0;
2571         dcmd->pad_0 = 0;
2572         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_CTRL_HB_HOST_MEM));
2573         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SHARED_HOST_MEM_ALLOC);
2574
2575         megasas_set_dma_settings(instance, dcmd, instance->hb_host_mem_h,
2576                                  sizeof(struct MR_CTRL_HB_HOST_MEM));
2577
2578         dev_warn(&instance->pdev->dev, "SR-IOV: Starting heartbeat for scsi%d\n",
2579                instance->host->host_no);
2580
2581         if ((instance->adapter_type != MFI_SERIES) &&
2582             !instance->mask_interrupts)
2583                 retval = megasas_issue_blocked_cmd(instance, cmd,
2584                         MEGASAS_ROUTINE_WAIT_TIME_VF);
2585         else
2586                 retval = megasas_issue_polled(instance, cmd);
2587
2588         if (retval) {
2589                 dev_warn(&instance->pdev->dev, "SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2590                         "_MEM_ALLOC DCMD %s for scsi%d\n",
2591                         (dcmd->cmd_status == MFI_STAT_INVALID_STATUS) ?
2592                         "timed out" : "failed", instance->host->host_no);
2593                 retval = 1;
2594         }
2595
2596 out:
2597         megasas_return_cmd(instance, cmd);
2598
2599         return retval;
2600 }
2601
2602 /* Handler for SR-IOV heartbeat */
2603 static void megasas_sriov_heartbeat_handler(struct timer_list *t)
2604 {
2605         struct megasas_instance *instance =
2606                 from_timer(instance, t, sriov_heartbeat_timer);
2607
2608         if (instance->hb_host_mem->HB.fwCounter !=
2609             instance->hb_host_mem->HB.driverCounter) {
2610                 instance->hb_host_mem->HB.driverCounter =
2611                         instance->hb_host_mem->HB.fwCounter;
2612                 mod_timer(&instance->sriov_heartbeat_timer,
2613                           jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
2614         } else {
2615                 dev_warn(&instance->pdev->dev, "SR-IOV: Heartbeat never "
2616                        "completed for scsi%d\n", instance->host->host_no);
2617                 schedule_work(&instance->work_init);
2618         }
2619 }
2620
2621 /**
2622  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
2623  * @instance:                           Adapter soft state
2624  *
2625  * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
2626  * complete all its outstanding commands. Returns error if one or more IOs
2627  * are pending after this time period. It also marks the controller dead.
2628  */
2629 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
2630 {
2631         int i, sl, outstanding;
2632         u32 reset_index;
2633         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
2634         unsigned long flags;
2635         struct list_head clist_local;
2636         struct megasas_cmd *reset_cmd;
2637         u32 fw_state;
2638
2639         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2640                 dev_info(&instance->pdev->dev, "%s:%d HBA is killed.\n",
2641                 __func__, __LINE__);
2642                 return FAILED;
2643         }
2644
2645         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
2646
2647                 INIT_LIST_HEAD(&clist_local);
2648                 spin_lock_irqsave(&instance->hba_lock, flags);
2649                 list_splice_init(&instance->internal_reset_pending_q,
2650                                 &clist_local);
2651                 spin_unlock_irqrestore(&instance->hba_lock, flags);
2652
2653                 dev_notice(&instance->pdev->dev, "HBA reset wait ...\n");
2654                 for (i = 0; i < wait_time; i++) {
2655                         msleep(1000);
2656                         if (atomic_read(&instance->adprecovery) == MEGASAS_HBA_OPERATIONAL)
2657                                 break;
2658                 }
2659
2660                 if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
2661                         dev_notice(&instance->pdev->dev, "reset: Stopping HBA.\n");
2662                         atomic_set(&instance->adprecovery, MEGASAS_HW_CRITICAL_ERROR);
2663                         return FAILED;
2664                 }
2665
2666                 reset_index = 0;
2667                 while (!list_empty(&clist_local)) {
2668                         reset_cmd = list_entry((&clist_local)->next,
2669                                                 struct megasas_cmd, list);
2670                         list_del_init(&reset_cmd->list);
2671                         if (reset_cmd->scmd) {
2672                                 reset_cmd->scmd->result = DID_REQUEUE << 16;
2673                                 dev_notice(&instance->pdev->dev, "%d:%p reset [%02x]\n",
2674                                         reset_index, reset_cmd,
2675                                         reset_cmd->scmd->cmnd[0]);
2676
2677                                 reset_cmd->scmd->scsi_done(reset_cmd->scmd);
2678                                 megasas_return_cmd(instance, reset_cmd);
2679                         } else if (reset_cmd->sync_cmd) {
2680                                 dev_notice(&instance->pdev->dev, "%p synch cmds"
2681                                                 "reset queue\n",
2682                                                 reset_cmd);
2683
2684                                 reset_cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS;
2685                                 instance->instancet->fire_cmd(instance,
2686                                                 reset_cmd->frame_phys_addr,
2687                                                 0, instance->reg_set);
2688                         } else {
2689                                 dev_notice(&instance->pdev->dev, "%p unexpected"
2690                                         "cmds lst\n",
2691                                         reset_cmd);
2692                         }
2693                         reset_index++;
2694                 }
2695
2696                 return SUCCESS;
2697         }
2698
2699         for (i = 0; i < resetwaittime; i++) {
2700                 outstanding = atomic_read(&instance->fw_outstanding);
2701
2702                 if (!outstanding)
2703                         break;
2704
2705                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
2706                         dev_notice(&instance->pdev->dev, "[%2d]waiting for %d "
2707                                "commands to complete\n",i,outstanding);
2708                         /*
2709                          * Call cmd completion routine. Cmd to be
2710                          * be completed directly without depending on isr.
2711                          */
2712                         megasas_complete_cmd_dpc((unsigned long)instance);
2713                 }
2714
2715                 msleep(1000);
2716         }
2717
2718         i = 0;
2719         outstanding = atomic_read(&instance->fw_outstanding);
2720         fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK;
2721
2722         if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL)))
2723                 goto no_outstanding;
2724
2725         if (instance->disableOnlineCtrlReset)
2726                 goto kill_hba_and_failed;
2727         do {
2728                 if ((fw_state == MFI_STATE_FAULT) || atomic_read(&instance->fw_outstanding)) {
2729                         dev_info(&instance->pdev->dev,
2730                                 "%s:%d waiting_for_outstanding: before issue OCR. FW state = 0x%x, outstanding 0x%x\n",
2731                                 __func__, __LINE__, fw_state, atomic_read(&instance->fw_outstanding));
2732                         if (i == 3)
2733                                 goto kill_hba_and_failed;
2734                         megasas_do_ocr(instance);
2735
2736                         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2737                                 dev_info(&instance->pdev->dev, "%s:%d OCR failed and HBA is killed.\n",
2738                                 __func__, __LINE__);
2739                                 return FAILED;
2740                         }
2741                         dev_info(&instance->pdev->dev, "%s:%d waiting_for_outstanding: after issue OCR.\n",
2742                                 __func__, __LINE__);
2743
2744                         for (sl = 0; sl < 10; sl++)
2745                                 msleep(500);
2746
2747                         outstanding = atomic_read(&instance->fw_outstanding);
2748
2749                         fw_state = instance->instancet->read_fw_status_reg(instance) & MFI_STATE_MASK;
2750                         if ((!outstanding && (fw_state == MFI_STATE_OPERATIONAL)))
2751                                 goto no_outstanding;
2752                 }
2753                 i++;
2754         } while (i <= 3);
2755
2756 no_outstanding:
2757
2758         dev_info(&instance->pdev->dev, "%s:%d no more pending commands remain after reset handling.\n",
2759                 __func__, __LINE__);
2760         return SUCCESS;
2761
2762 kill_hba_and_failed:
2763
2764         /* Reset not supported, kill adapter */
2765         dev_info(&instance->pdev->dev, "%s:%d killing adapter scsi%d"
2766                 " disableOnlineCtrlReset %d fw_outstanding %d \n",
2767                 __func__, __LINE__, instance->host->host_no, instance->disableOnlineCtrlReset,
2768                 atomic_read(&instance->fw_outstanding));
2769         megasas_dump_pending_frames(instance);
2770         megaraid_sas_kill_hba(instance);
2771
2772         return FAILED;
2773 }
2774
2775 /**
2776  * megasas_generic_reset -      Generic reset routine
2777  * @scmd:                       Mid-layer SCSI command
2778  *
2779  * This routine implements a generic reset handler for device, bus and host
2780  * reset requests. Device, bus and host specific reset handlers can use this
2781  * function after they do their specific tasks.
2782  */
2783 static int megasas_generic_reset(struct scsi_cmnd *scmd)
2784 {
2785         int ret_val;
2786         struct megasas_instance *instance;
2787
2788         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2789
2790         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
2791                  scmd->cmnd[0], scmd->retries);
2792
2793         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
2794                 dev_err(&instance->pdev->dev, "cannot recover from previous reset failures\n");
2795                 return FAILED;
2796         }
2797
2798         ret_val = megasas_wait_for_outstanding(instance);
2799         if (ret_val == SUCCESS)
2800                 dev_notice(&instance->pdev->dev, "reset successful\n");
2801         else
2802                 dev_err(&instance->pdev->dev, "failed to do reset\n");
2803
2804         return ret_val;
2805 }
2806
2807 /**
2808  * megasas_reset_timer - quiesce the adapter if required
2809  * @scmd:               scsi cmnd
2810  *
2811  * Sets the FW busy flag and reduces the host->can_queue if the
2812  * cmd has not been completed within the timeout period.
2813  */
2814 static enum
2815 blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
2816 {
2817         struct megasas_instance *instance;
2818         unsigned long flags;
2819
2820         if (time_after(jiffies, scmd->jiffies_at_alloc +
2821                                 (scmd_timeout * 2) * HZ)) {
2822                 return BLK_EH_DONE;
2823         }
2824
2825         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2826         if (!(instance->flag & MEGASAS_FW_BUSY)) {
2827                 /* FW is busy, throttle IO */
2828                 spin_lock_irqsave(instance->host->host_lock, flags);
2829
2830                 instance->host->can_queue = instance->throttlequeuedepth;
2831                 instance->last_time = jiffies;
2832                 instance->flag |= MEGASAS_FW_BUSY;
2833
2834                 spin_unlock_irqrestore(instance->host->host_lock, flags);
2835         }
2836         return BLK_EH_RESET_TIMER;
2837 }
2838
2839 /**
2840  * megasas_dump -       This function will print hexdump of provided buffer.
2841  * @buf:                Buffer to be dumped
2842  * @sz:         Size in bytes
2843  * @format:             Different formats of dumping e.g. format=n will
2844  *                      cause only 'n' 32 bit words to be dumped in a single
2845  *                      line.
2846  */
2847 inline void
2848 megasas_dump(void *buf, int sz, int format)
2849 {
2850         int i;
2851         __le32 *buf_loc = (__le32 *)buf;
2852
2853         for (i = 0; i < (sz / sizeof(__le32)); i++) {
2854                 if ((i % format) == 0) {
2855                         if (i != 0)
2856                                 printk(KERN_CONT "\n");
2857                         printk(KERN_CONT "%08x: ", (i * 4));
2858                 }
2859                 printk(KERN_CONT "%08x ", le32_to_cpu(buf_loc[i]));
2860         }
2861         printk(KERN_CONT "\n");
2862 }
2863
2864 /**
2865  * megasas_dump_reg_set -       This function will print hexdump of register set
2866  * @buf:                        Buffer to be dumped
2867  * @sz:                         Size in bytes
2868  * @format:                     Different formats of dumping e.g. format=n will
2869  *                              cause only 'n' 32 bit words to be dumped in a
2870  *                              single line.
2871  */
2872 inline void
2873 megasas_dump_reg_set(void __iomem *reg_set)
2874 {
2875         unsigned int i, sz = 256;
2876         u32 __iomem *reg = (u32 __iomem *)reg_set;
2877
2878         for (i = 0; i < (sz / sizeof(u32)); i++)
2879                 printk("%08x: %08x\n", (i * 4), readl(&reg[i]));
2880 }
2881
2882 /**
2883  * megasas_dump_fusion_io -     This function will print key details
2884  *                              of SCSI IO
2885  * @scmd:                       SCSI command pointer of SCSI IO
2886  */
2887 void
2888 megasas_dump_fusion_io(struct scsi_cmnd *scmd)
2889 {
2890         struct megasas_cmd_fusion *cmd;
2891         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2892         struct megasas_instance *instance;
2893
2894         cmd = (struct megasas_cmd_fusion *)scmd->SCp.ptr;
2895         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2896
2897         scmd_printk(KERN_INFO, scmd,
2898                     "scmd: (0x%p)  retries: 0x%x  allowed: 0x%x\n",
2899                     scmd, scmd->retries, scmd->allowed);
2900         scsi_print_command(scmd);
2901
2902         if (cmd) {
2903                 req_desc = (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)cmd->request_desc;
2904                 scmd_printk(KERN_INFO, scmd, "Request descriptor details:\n");
2905                 scmd_printk(KERN_INFO, scmd,
2906                             "RequestFlags:0x%x  MSIxIndex:0x%x  SMID:0x%x  LMID:0x%x  DevHandle:0x%x\n",
2907                             req_desc->SCSIIO.RequestFlags,
2908                             req_desc->SCSIIO.MSIxIndex, req_desc->SCSIIO.SMID,
2909                             req_desc->SCSIIO.LMID, req_desc->SCSIIO.DevHandle);
2910
2911                 printk(KERN_INFO "IO request frame:\n");
2912                 megasas_dump(cmd->io_request,
2913                              MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE, 8);
2914                 printk(KERN_INFO "Chain frame:\n");
2915                 megasas_dump(cmd->sg_frame,
2916                              instance->max_chain_frame_sz, 8);
2917         }
2918
2919 }
2920
2921 /*
2922  * megasas_dump_sys_regs - This function will dump system registers through
2923  *                          sysfs.
2924  * @reg_set:                Pointer to System register set.
2925  * @buf:                    Buffer to which output is to be written.
2926  * @return:                 Number of bytes written to buffer.
2927  */
2928 static inline ssize_t
2929 megasas_dump_sys_regs(void __iomem *reg_set, char *buf)
2930 {
2931         unsigned int i, sz = 256;
2932         int bytes_wrote = 0;
2933         char *loc = (char *)buf;
2934         u32 __iomem *reg = (u32 __iomem *)reg_set;
2935
2936         for (i = 0; i < sz / sizeof(u32); i++) {
2937                 bytes_wrote += snprintf(loc + bytes_wrote, PAGE_SIZE,
2938                                         "%08x: %08x\n", (i * 4),
2939                                         readl(&reg[i]));
2940         }
2941         return bytes_wrote;
2942 }
2943
2944 /**
2945  * megasas_reset_bus_host -     Bus & host reset handler entry point
2946  */
2947 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
2948 {
2949         int ret;
2950         struct megasas_instance *instance;
2951
2952         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2953
2954         scmd_printk(KERN_INFO, scmd,
2955                 "OCR is requested due to IO timeout!!\n");
2956
2957         scmd_printk(KERN_INFO, scmd,
2958                 "SCSI host state: %d  SCSI host busy: %d  FW outstanding: %d\n",
2959                 scmd->device->host->shost_state,
2960                 scsi_host_busy(scmd->device->host),
2961                 atomic_read(&instance->fw_outstanding));
2962         /*
2963          * First wait for all commands to complete
2964          */
2965         if (instance->adapter_type == MFI_SERIES) {
2966                 ret = megasas_generic_reset(scmd);
2967         } else {
2968                 megasas_dump_fusion_io(scmd);
2969                 ret = megasas_reset_fusion(scmd->device->host,
2970                                 SCSIIO_TIMEOUT_OCR);
2971         }
2972
2973         return ret;
2974 }
2975
2976 /**
2977  * megasas_task_abort - Issues task abort request to firmware
2978  *                      (supported only for fusion adapters)
2979  * @scmd:               SCSI command pointer
2980  */
2981 static int megasas_task_abort(struct scsi_cmnd *scmd)
2982 {
2983         int ret;
2984         struct megasas_instance *instance;
2985
2986         instance = (struct megasas_instance *)scmd->device->host->hostdata;
2987
2988         if (instance->adapter_type != MFI_SERIES)
2989                 ret = megasas_task_abort_fusion(scmd);
2990         else {
2991                 sdev_printk(KERN_NOTICE, scmd->device, "TASK ABORT not supported\n");
2992                 ret = FAILED;
2993         }
2994
2995         return ret;
2996 }
2997
2998 /**
2999  * megasas_reset_target:  Issues target reset request to firmware
3000  *                        (supported only for fusion adapters)
3001  * @scmd:                 SCSI command pointer
3002  */
3003 static int megasas_reset_target(struct scsi_cmnd *scmd)
3004 {
3005         int ret;
3006         struct megasas_instance *instance;
3007
3008         instance = (struct megasas_instance *)scmd->device->host->hostdata;
3009
3010         if (instance->adapter_type != MFI_SERIES)
3011                 ret = megasas_reset_target_fusion(scmd);
3012         else {
3013                 sdev_printk(KERN_NOTICE, scmd->device, "TARGET RESET not supported\n");
3014                 ret = FAILED;
3015         }
3016
3017         return ret;
3018 }
3019
3020 /**
3021  * megasas_bios_param - Returns disk geometry for a disk
3022  * @sdev:               device handle
3023  * @bdev:               block device
3024  * @capacity:           drive capacity
3025  * @geom:               geometry parameters
3026  */
3027 static int
3028 megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
3029                  sector_t capacity, int geom[])
3030 {
3031         int heads;
3032         int sectors;
3033         sector_t cylinders;
3034         unsigned long tmp;
3035
3036         /* Default heads (64) & sectors (32) */
3037         heads = 64;
3038         sectors = 32;
3039
3040         tmp = heads * sectors;
3041         cylinders = capacity;
3042
3043         sector_div(cylinders, tmp);
3044
3045         /*
3046          * Handle extended translation size for logical drives > 1Gb
3047          */
3048
3049         if (capacity >= 0x200000) {
3050                 heads = 255;
3051                 sectors = 63;
3052                 tmp = heads*sectors;
3053                 cylinders = capacity;
3054                 sector_div(cylinders, tmp);
3055         }
3056
3057         geom[0] = heads;
3058         geom[1] = sectors;
3059         geom[2] = cylinders;
3060
3061         return 0;
3062 }
3063
3064 static void megasas_aen_polling(struct work_struct *work);
3065
3066 /**
3067  * megasas_service_aen -        Processes an event notification
3068  * @instance:                   Adapter soft state
3069  * @cmd:                        AEN command completed by the ISR
3070  *
3071  * For AEN, driver sends a command down to FW that is held by the FW till an
3072  * event occurs. When an event of interest occurs, FW completes the command
3073  * that it was previously holding.
3074  *
3075  * This routines sends SIGIO signal to processes that have registered with the
3076  * driver for AEN.
3077  */
3078 static void
3079 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
3080 {
3081         unsigned long flags;
3082
3083         /*
3084          * Don't signal app if it is just an aborted previously registered aen
3085          */
3086         if ((!cmd->abort_aen) && (instance->unload == 0)) {
3087                 spin_lock_irqsave(&poll_aen_lock, flags);
3088                 megasas_poll_wait_aen = 1;
3089                 spin_unlock_irqrestore(&poll_aen_lock, flags);
3090                 wake_up(&megasas_poll_wait);
3091                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
3092         }
3093         else
3094                 cmd->abort_aen = 0;
3095
3096         instance->aen_cmd = NULL;
3097
3098         megasas_return_cmd(instance, cmd);
3099
3100         if ((instance->unload == 0) &&
3101                 ((instance->issuepend_done == 1))) {
3102                 struct megasas_aen_event *ev;
3103
3104                 ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
3105                 if (!ev) {
3106                         dev_err(&instance->pdev->dev, "megasas_service_aen: out of memory\n");
3107                 } else {
3108                         ev->instance = instance;
3109                         instance->ev = ev;
3110                         INIT_DELAYED_WORK(&ev->hotplug_work,
3111                                           megasas_aen_polling);
3112                         schedule_delayed_work(&ev->hotplug_work, 0);
3113                 }
3114         }
3115 }
3116
3117 static ssize_t
3118 megasas_fw_crash_buffer_store(struct device *cdev,
3119         struct device_attribute *attr, const char *buf, size_t count)
3120 {
3121         struct Scsi_Host *shost = class_to_shost(cdev);
3122         struct megasas_instance *instance =
3123                 (struct megasas_instance *) shost->hostdata;
3124         int val = 0;
3125         unsigned long flags;
3126
3127         if (kstrtoint(buf, 0, &val) != 0)
3128                 return -EINVAL;
3129
3130         spin_lock_irqsave(&instance->crashdump_lock, flags);
3131         instance->fw_crash_buffer_offset = val;
3132         spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3133         return strlen(buf);
3134 }
3135
3136 static ssize_t
3137 megasas_fw_crash_buffer_show(struct device *cdev,
3138         struct device_attribute *attr, char *buf)
3139 {
3140         struct Scsi_Host *shost = class_to_shost(cdev);
3141         struct megasas_instance *instance =
3142                 (struct megasas_instance *) shost->hostdata;
3143         u32 size;
3144         unsigned long buff_addr;
3145         unsigned long dmachunk = CRASH_DMA_BUF_SIZE;
3146         unsigned long src_addr;
3147         unsigned long flags;
3148         u32 buff_offset;
3149
3150         spin_lock_irqsave(&instance->crashdump_lock, flags);
3151         buff_offset = instance->fw_crash_buffer_offset;
3152         if (!instance->crash_dump_buf &&
3153                 !((instance->fw_crash_state == AVAILABLE) ||
3154                 (instance->fw_crash_state == COPYING))) {
3155                 dev_err(&instance->pdev->dev,
3156                         "Firmware crash dump is not available\n");
3157                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3158                 return -EINVAL;
3159         }
3160
3161         buff_addr = (unsigned long) buf;
3162
3163         if (buff_offset > (instance->fw_crash_buffer_size * dmachunk)) {
3164                 dev_err(&instance->pdev->dev,
3165                         "Firmware crash dump offset is out of range\n");
3166                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3167                 return 0;
3168         }
3169
3170         size = (instance->fw_crash_buffer_size * dmachunk) - buff_offset;
3171         size = (size >= PAGE_SIZE) ? (PAGE_SIZE - 1) : size;
3172
3173         src_addr = (unsigned long)instance->crash_buf[buff_offset / dmachunk] +
3174                 (buff_offset % dmachunk);
3175         memcpy(buf, (void *)src_addr, size);
3176         spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3177
3178         return size;
3179 }
3180
3181 static ssize_t
3182 megasas_fw_crash_buffer_size_show(struct device *cdev,
3183         struct device_attribute *attr, char *buf)
3184 {
3185         struct Scsi_Host *shost = class_to_shost(cdev);
3186         struct megasas_instance *instance =
3187                 (struct megasas_instance *) shost->hostdata;
3188
3189         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)
3190                 ((instance->fw_crash_buffer_size) * 1024 * 1024)/PAGE_SIZE);
3191 }
3192
3193 static ssize_t
3194 megasas_fw_crash_state_store(struct device *cdev,
3195         struct device_attribute *attr, const char *buf, size_t count)
3196 {
3197         struct Scsi_Host *shost = class_to_shost(cdev);
3198         struct megasas_instance *instance =
3199                 (struct megasas_instance *) shost->hostdata;
3200         int val = 0;
3201         unsigned long flags;
3202
3203         if (kstrtoint(buf, 0, &val) != 0)
3204                 return -EINVAL;
3205
3206         if ((val <= AVAILABLE || val > COPY_ERROR)) {
3207                 dev_err(&instance->pdev->dev, "application updates invalid "
3208                         "firmware crash state\n");
3209                 return -EINVAL;
3210         }
3211
3212         instance->fw_crash_state = val;
3213
3214         if ((val == COPIED) || (val == COPY_ERROR)) {
3215                 spin_lock_irqsave(&instance->crashdump_lock, flags);
3216                 megasas_free_host_crash_buffer(instance);
3217                 spin_unlock_irqrestore(&instance->crashdump_lock, flags);
3218                 if (val == COPY_ERROR)
3219                         dev_info(&instance->pdev->dev, "application failed to "
3220                                 "copy Firmware crash dump\n");
3221                 else
3222                         dev_info(&instance->pdev->dev, "Firmware crash dump "
3223                                 "copied successfully\n");
3224         }
3225         return strlen(buf);
3226 }
3227
3228 static ssize_t
3229 megasas_fw_crash_state_show(struct device *cdev,
3230         struct device_attribute *attr, char *buf)
3231 {
3232         struct Scsi_Host *shost = class_to_shost(cdev);
3233         struct megasas_instance *instance =
3234                 (struct megasas_instance *) shost->hostdata;
3235
3236         return snprintf(buf, PAGE_SIZE, "%d\n", instance->fw_crash_state);
3237 }
3238
3239 static ssize_t
3240 megasas_page_size_show(struct device *cdev,
3241         struct device_attribute *attr, char *buf)
3242 {
3243         return snprintf(buf, PAGE_SIZE, "%ld\n", (unsigned long)PAGE_SIZE - 1);
3244 }
3245
3246 static ssize_t
3247 megasas_ldio_outstanding_show(struct device *cdev, struct device_attribute *attr,
3248         char *buf)
3249 {
3250         struct Scsi_Host *shost = class_to_shost(cdev);
3251         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3252
3253         return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->ldio_outstanding));
3254 }
3255
3256 static ssize_t
3257 megasas_fw_cmds_outstanding_show(struct device *cdev,
3258                                  struct device_attribute *attr, char *buf)
3259 {
3260         struct Scsi_Host *shost = class_to_shost(cdev);
3261         struct megasas_instance *instance = (struct megasas_instance *)shost->hostdata;
3262
3263         return snprintf(buf, PAGE_SIZE, "%d\n", atomic_read(&instance->fw_outstanding));
3264 }
3265
3266 static ssize_t
3267 megasas_dump_system_regs_show(struct device *cdev,
3268                                struct device_attribute *attr, char *buf)
3269 {
3270         struct Scsi_Host *shost = class_to_shost(cdev);
3271         struct megasas_instance *instance =
3272                         (struct megasas_instance *)shost->hostdata;
3273
3274         return megasas_dump_sys_regs(instance->reg_set, buf);
3275 }
3276
3277 static ssize_t
3278 megasas_raid_map_id_show(struct device *cdev, struct device_attribute *attr,
3279                           char *buf)
3280 {
3281         struct Scsi_Host *shost = class_to_shost(cdev);
3282         struct megasas_instance *instance =
3283                         (struct megasas_instance *)shost->hostdata;
3284
3285         return snprintf(buf, PAGE_SIZE, "%ld\n",
3286                         (unsigned long)instance->map_id);
3287 }
3288
3289 static DEVICE_ATTR(fw_crash_buffer, S_IRUGO | S_IWUSR,
3290         megasas_fw_crash_buffer_show, megasas_fw_crash_buffer_store);
3291 static DEVICE_ATTR(fw_crash_buffer_size, S_IRUGO,
3292         megasas_fw_crash_buffer_size_show, NULL);
3293 static DEVICE_ATTR(fw_crash_state, S_IRUGO | S_IWUSR,
3294         megasas_fw_crash_state_show, megasas_fw_crash_state_store);
3295 static DEVICE_ATTR(page_size, S_IRUGO,
3296         megasas_page_size_show, NULL);
3297 static DEVICE_ATTR(ldio_outstanding, S_IRUGO,
3298         megasas_ldio_outstanding_show, NULL);
3299 static DEVICE_ATTR(fw_cmds_outstanding, S_IRUGO,
3300         megasas_fw_cmds_outstanding_show, NULL);
3301 static DEVICE_ATTR(dump_system_regs, S_IRUGO,
3302         megasas_dump_system_regs_show, NULL);
3303 static DEVICE_ATTR(raid_map_id, S_IRUGO,
3304         megasas_raid_map_id_show, NULL);
3305
3306 struct device_attribute *megaraid_host_attrs[] = {
3307         &dev_attr_fw_crash_buffer_size,
3308         &dev_attr_fw_crash_buffer,
3309         &dev_attr_fw_crash_state,
3310         &dev_attr_page_size,
3311         &dev_attr_ldio_outstanding,
3312         &dev_attr_fw_cmds_outstanding,
3313         &dev_attr_dump_system_regs,
3314         &dev_attr_raid_map_id,
3315         NULL,
3316 };
3317
3318 /*
3319  * Scsi host template for megaraid_sas driver
3320  */
3321 static struct scsi_host_template megasas_template = {
3322
3323         .module = THIS_MODULE,
3324         .name = "Avago SAS based MegaRAID driver",
3325         .proc_name = "megaraid_sas",
3326         .slave_configure = megasas_slave_configure,
3327         .slave_alloc = megasas_slave_alloc,
3328         .slave_destroy = megasas_slave_destroy,
3329         .queuecommand = megasas_queue_command,
3330         .eh_target_reset_handler = megasas_reset_target,
3331         .eh_abort_handler = megasas_task_abort,
3332         .eh_host_reset_handler = megasas_reset_bus_host,
3333         .eh_timed_out = megasas_reset_timer,
3334         .shost_attrs = megaraid_host_attrs,
3335         .bios_param = megasas_bios_param,
3336         .change_queue_depth = scsi_change_queue_depth,
3337         .no_write_same = 1,
3338 };
3339
3340 /**
3341  * megasas_complete_int_cmd -   Completes an internal command
3342  * @instance:                   Adapter soft state
3343  * @cmd:                        Command to be completed
3344  *
3345  * The megasas_issue_blocked_cmd() function waits for a command to complete
3346  * after it issues a command. This function wakes up that waiting routine by
3347  * calling wake_up() on the wait queue.
3348  */
3349 static void
3350 megasas_complete_int_cmd(struct megasas_instance *instance,
3351                          struct megasas_cmd *cmd)
3352 {
3353         cmd->cmd_status_drv = cmd->frame->io.cmd_status;
3354         wake_up(&instance->int_cmd_wait_q);
3355 }
3356
3357 /**
3358  * megasas_complete_abort -     Completes aborting a command
3359  * @instance:                   Adapter soft state
3360  * @cmd:                        Cmd that was issued to abort another cmd
3361  *
3362  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
3363  * after it issues an abort on a previously issued command. This function
3364  * wakes up all functions waiting on the same wait queue.
3365  */
3366 static void
3367 megasas_complete_abort(struct megasas_instance *instance,
3368                        struct megasas_cmd *cmd)
3369 {
3370         if (cmd->sync_cmd) {
3371                 cmd->sync_cmd = 0;
3372                 cmd->cmd_status_drv = 0;
3373                 wake_up(&instance->abort_cmd_wait_q);
3374         }
3375 }
3376
3377 /**
3378  * megasas_complete_cmd -       Completes a command
3379  * @instance:                   Adapter soft state
3380  * @cmd:                        Command to be completed
3381  * @alt_status:                 If non-zero, use this value as status to
3382  *                              SCSI mid-layer instead of the value returned
3383  *                              by the FW. This should be used if caller wants
3384  *                              an alternate status (as in the case of aborted
3385  *                              commands)
3386  */
3387 void
3388 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
3389                      u8 alt_status)
3390 {
3391         int exception = 0;
3392         struct megasas_header *hdr = &cmd->frame->hdr;
3393         unsigned long flags;
3394         struct fusion_context *fusion = instance->ctrl_context;
3395         u32 opcode, status;
3396
3397         /* flag for the retry reset */
3398         cmd->retry_for_fw_reset = 0;
3399
3400         if (cmd->scmd)
3401                 cmd->scmd->SCp.ptr = NULL;
3402
3403         switch (hdr->cmd) {
3404         case MFI_CMD_INVALID:
3405                 /* Some older 1068 controller FW may keep a pended
3406                    MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
3407                    when booting the kdump kernel.  Ignore this command to
3408                    prevent a kernel panic on shutdown of the kdump kernel. */
3409                 dev_warn(&instance->pdev->dev, "MFI_CMD_INVALID command "
3410                        "completed\n");
3411                 dev_warn(&instance->pdev->dev, "If you have a controller "
3412                        "other than PERC5, please upgrade your firmware\n");
3413                 break;
3414         case MFI_CMD_PD_SCSI_IO:
3415         case MFI_CMD_LD_SCSI_IO:
3416
3417                 /*
3418                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
3419                  * issued either through an IO path or an IOCTL path. If it
3420                  * was via IOCTL, we will send it to internal completion.
3421                  */
3422                 if (cmd->sync_cmd) {
3423                         cmd->sync_cmd = 0;
3424                         megasas_complete_int_cmd(instance, cmd);
3425                         break;
3426                 }
3427                 /* fall through */
3428
3429         case MFI_CMD_LD_READ:
3430         case MFI_CMD_LD_WRITE:
3431
3432                 if (alt_status) {
3433                         cmd->scmd->result = alt_status << 16;
3434                         exception = 1;
3435                 }
3436
3437                 if (exception) {
3438
3439                         atomic_dec(&instance->fw_outstanding);
3440
3441                         scsi_dma_unmap(cmd->scmd);
3442                         cmd->scmd->scsi_done(cmd->scmd);
3443                         megasas_return_cmd(instance, cmd);
3444
3445                         break;
3446                 }
3447
3448                 switch (hdr->cmd_status) {
3449
3450                 case MFI_STAT_OK:
3451                         cmd->scmd->result = DID_OK << 16;
3452                         break;
3453
3454                 case MFI_STAT_SCSI_IO_FAILED:
3455                 case MFI_STAT_LD_INIT_IN_PROGRESS:
3456                         cmd->scmd->result =
3457                             (DID_ERROR << 16) | hdr->scsi_status;
3458                         break;
3459
3460                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
3461
3462                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
3463
3464                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
3465                                 memset(cmd->scmd->sense_buffer, 0,
3466                                        SCSI_SENSE_BUFFERSIZE);
3467                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
3468                                        hdr->sense_len);
3469
3470                                 cmd->scmd->result |= DRIVER_SENSE << 24;
3471                         }
3472
3473                         break;
3474
3475                 case MFI_STAT_LD_OFFLINE:
3476                 case MFI_STAT_DEVICE_NOT_FOUND:
3477                         cmd->scmd->result = DID_BAD_TARGET << 16;
3478                         break;
3479
3480                 default:
3481                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "MFI FW status %#x\n",
3482                                hdr->cmd_status);
3483                         cmd->scmd->result = DID_ERROR << 16;
3484                         break;
3485                 }
3486
3487                 atomic_dec(&instance->fw_outstanding);
3488
3489                 scsi_dma_unmap(cmd->scmd);
3490                 cmd->scmd->scsi_done(cmd->scmd);
3491                 megasas_return_cmd(instance, cmd);
3492
3493                 break;
3494
3495         case MFI_CMD_SMP:
3496         case MFI_CMD_STP:
3497         case MFI_CMD_NVME:
3498                 megasas_complete_int_cmd(instance, cmd);
3499                 break;
3500
3501         case MFI_CMD_DCMD:
3502                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
3503                 /* Check for LD map update */
3504                 if ((opcode == MR_DCMD_LD_MAP_GET_INFO)
3505                         && (cmd->frame->dcmd.mbox.b[1] == 1)) {
3506                         fusion->fast_path_io = 0;
3507                         spin_lock_irqsave(instance->host->host_lock, flags);
3508                         status = cmd->frame->hdr.cmd_status;
3509                         instance->map_update_cmd = NULL;
3510                         if (status != MFI_STAT_OK) {
3511                                 if (status != MFI_STAT_NOT_FOUND)
3512                                         dev_warn(&instance->pdev->dev, "map syncfailed, status = 0x%x\n",
3513                                                cmd->frame->hdr.cmd_status);
3514                                 else {
3515                                         megasas_return_cmd(instance, cmd);
3516                                         spin_unlock_irqrestore(
3517                                                 instance->host->host_lock,
3518                                                 flags);
3519                                         break;
3520                                 }
3521                         }
3522
3523                         megasas_return_cmd(instance, cmd);
3524
3525                         /*
3526                          * Set fast path IO to ZERO.
3527                          * Validate Map will set proper value.
3528                          * Meanwhile all IOs will go as LD IO.
3529                          */
3530                         if (status == MFI_STAT_OK &&
3531                             (MR_ValidateMapInfo(instance, (instance->map_id + 1)))) {
3532                                 instance->map_id++;
3533                                 fusion->fast_path_io = 1;
3534                         } else {
3535                                 fusion->fast_path_io = 0;
3536                         }
3537
3538                         megasas_sync_map_info(instance);
3539                         spin_unlock_irqrestore(instance->host->host_lock,
3540                                                flags);
3541                         break;
3542                 }
3543                 if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
3544                     opcode == MR_DCMD_CTRL_EVENT_GET) {
3545                         spin_lock_irqsave(&poll_aen_lock, flags);
3546                         megasas_poll_wait_aen = 0;
3547                         spin_unlock_irqrestore(&poll_aen_lock, flags);
3548                 }
3549
3550                 /* FW has an updated PD sequence */
3551                 if ((opcode == MR_DCMD_SYSTEM_PD_MAP_GET_INFO) &&
3552                         (cmd->frame->dcmd.mbox.b[0] == 1)) {
3553
3554                         spin_lock_irqsave(instance->host->host_lock, flags);
3555                         status = cmd->frame->hdr.cmd_status;
3556                         instance->jbod_seq_cmd = NULL;
3557                         megasas_return_cmd(instance, cmd);
3558
3559                         if (status == MFI_STAT_OK) {
3560                                 instance->pd_seq_map_id++;
3561                                 /* Re-register a pd sync seq num cmd */
3562                                 if (megasas_sync_pd_seq_num(instance, true))
3563                                         instance->use_seqnum_jbod_fp = false;
3564                         } else
3565                                 instance->use_seqnum_jbod_fp = false;
3566
3567                         spin_unlock_irqrestore(instance->host->host_lock, flags);
3568                         break;
3569                 }
3570
3571                 /*
3572                  * See if got an event notification
3573                  */
3574                 if (opcode == MR_DCMD_CTRL_EVENT_WAIT)
3575                         megasas_service_aen(instance, cmd);
3576                 else
3577                         megasas_complete_int_cmd(instance, cmd);
3578
3579                 break;
3580
3581         case MFI_CMD_ABORT:
3582                 /*
3583                  * Cmd issued to abort another cmd returned
3584                  */
3585                 megasas_complete_abort(instance, cmd);
3586                 break;
3587
3588         default:
3589                 dev_info(&instance->pdev->dev, "Unknown command completed! [0x%X]\n",
3590                        hdr->cmd);
3591                 megasas_complete_int_cmd(instance, cmd);
3592                 break;
3593         }
3594 }
3595
3596 /**
3597  * megasas_issue_pending_cmds_again -   issue all pending cmds
3598  *                                      in FW again because of the fw reset
3599  * @instance:                           Adapter soft state
3600  */
3601 static inline void
3602 megasas_issue_pending_cmds_again(struct megasas_instance *instance)
3603 {
3604         struct megasas_cmd *cmd;
3605         struct list_head clist_local;
3606         union megasas_evt_class_locale class_locale;
3607         unsigned long flags;
3608         u32 seq_num;
3609
3610         INIT_LIST_HEAD(&clist_local);
3611         spin_lock_irqsave(&instance->hba_lock, flags);
3612         list_splice_init(&instance->internal_reset_pending_q, &clist_local);
3613         spin_unlock_irqrestore(&instance->hba_lock, flags);
3614
3615         while (!list_empty(&clist_local)) {
3616                 cmd = list_entry((&clist_local)->next,
3617                                         struct megasas_cmd, list);
3618                 list_del_init(&cmd->list);
3619
3620                 if (cmd->sync_cmd || cmd->scmd) {
3621                         dev_notice(&instance->pdev->dev, "command %p, %p:%d"
3622                                 "detected to be pending while HBA reset\n",
3623                                         cmd, cmd->scmd, cmd->sync_cmd);
3624
3625                         cmd->retry_for_fw_reset++;
3626
3627                         if (cmd->retry_for_fw_reset == 3) {
3628                                 dev_notice(&instance->pdev->dev, "cmd %p, %p:%d"
3629                                         "was tried multiple times during reset."
3630                                         "Shutting down the HBA\n",
3631                                         cmd, cmd->scmd, cmd->sync_cmd);
3632                                 instance->instancet->disable_intr(instance);
3633                                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3634                                 megaraid_sas_kill_hba(instance);
3635                                 return;
3636                         }
3637                 }
3638
3639                 if (cmd->sync_cmd == 1) {
3640                         if (cmd->scmd) {
3641                                 dev_notice(&instance->pdev->dev, "unexpected"
3642                                         "cmd attached to internal command!\n");
3643                         }
3644                         dev_notice(&instance->pdev->dev, "%p synchronous cmd"
3645                                                 "on the internal reset queue,"
3646                                                 "issue it again.\n", cmd);
3647                         cmd->cmd_status_drv = MFI_STAT_INVALID_STATUS;
3648                         instance->instancet->fire_cmd(instance,
3649                                                         cmd->frame_phys_addr,
3650                                                         0, instance->reg_set);
3651                 } else if (cmd->scmd) {
3652                         dev_notice(&instance->pdev->dev, "%p scsi cmd [%02x]"
3653                         "detected on the internal queue, issue again.\n",
3654                         cmd, cmd->scmd->cmnd[0]);
3655
3656                         atomic_inc(&instance->fw_outstanding);
3657                         instance->instancet->fire_cmd(instance,
3658                                         cmd->frame_phys_addr,
3659                                         cmd->frame_count-1, instance->reg_set);
3660                 } else {
3661                         dev_notice(&instance->pdev->dev, "%p unexpected cmd on the"
3662                                 "internal reset defer list while re-issue!!\n",
3663                                 cmd);
3664                 }
3665         }
3666
3667         if (instance->aen_cmd) {
3668                 dev_notice(&instance->pdev->dev, "aen_cmd in def process\n");
3669                 megasas_return_cmd(instance, instance->aen_cmd);
3670
3671                 instance->aen_cmd = NULL;
3672         }
3673
3674         /*
3675          * Initiate AEN (Asynchronous Event Notification)
3676          */
3677         seq_num = instance->last_seq_num;
3678         class_locale.members.reserved = 0;
3679         class_locale.members.locale = MR_EVT_LOCALE_ALL;
3680         class_locale.members.class = MR_EVT_CLASS_DEBUG;
3681
3682         megasas_register_aen(instance, seq_num, class_locale.word);
3683 }
3684
3685 /**
3686  * Move the internal reset pending commands to a deferred queue.
3687  *
3688  * We move the commands pending at internal reset time to a
3689  * pending queue. This queue would be flushed after successful
3690  * completion of the internal reset sequence. if the internal reset
3691  * did not complete in time, the kernel reset handler would flush
3692  * these commands.
3693  **/
3694 static void
3695 megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
3696 {
3697         struct megasas_cmd *cmd;
3698         int i;
3699         u16 max_cmd = instance->max_fw_cmds;
3700         u32 defer_index;
3701         unsigned long flags;
3702
3703         defer_index = 0;
3704         spin_lock_irqsave(&instance->mfi_pool_lock, flags);
3705         for (i = 0; i < max_cmd; i++) {
3706                 cmd = instance->cmd_list[i];
3707                 if (cmd->sync_cmd == 1 || cmd->scmd) {
3708                         dev_notice(&instance->pdev->dev, "moving cmd[%d]:%p:%d:%p"
3709                                         "on the defer queue as internal\n",
3710                                 defer_index, cmd, cmd->sync_cmd, cmd->scmd);
3711
3712                         if (!list_empty(&cmd->list)) {
3713                                 dev_notice(&instance->pdev->dev, "ERROR while"
3714                                         " moving this cmd:%p, %d %p, it was"
3715                                         "discovered on some list?\n",
3716                                         cmd, cmd->sync_cmd, cmd->scmd);
3717
3718                                 list_del_init(&cmd->list);
3719                         }
3720                         defer_index++;
3721                         list_add_tail(&cmd->list,
3722                                 &instance->internal_reset_pending_q);
3723                 }
3724         }
3725         spin_unlock_irqrestore(&instance->mfi_pool_lock, flags);
3726 }
3727
3728
3729 static void
3730 process_fw_state_change_wq(struct work_struct *work)
3731 {
3732         struct megasas_instance *instance =
3733                 container_of(work, struct megasas_instance, work_init);
3734         u32 wait;
3735         unsigned long flags;
3736
3737     if (atomic_read(&instance->adprecovery) != MEGASAS_ADPRESET_SM_INFAULT) {
3738                 dev_notice(&instance->pdev->dev, "error, recovery st %x\n",
3739                                 atomic_read(&instance->adprecovery));
3740                 return ;
3741         }
3742
3743         if (atomic_read(&instance->adprecovery) == MEGASAS_ADPRESET_SM_INFAULT) {
3744                 dev_notice(&instance->pdev->dev, "FW detected to be in fault"
3745                                         "state, restarting it...\n");
3746
3747                 instance->instancet->disable_intr(instance);
3748                 atomic_set(&instance->fw_outstanding, 0);
3749
3750                 atomic_set(&instance->fw_reset_no_pci_access, 1);
3751                 instance->instancet->adp_reset(instance, instance->reg_set);
3752                 atomic_set(&instance->fw_reset_no_pci_access, 0);
3753
3754                 dev_notice(&instance->pdev->dev, "FW restarted successfully,"
3755                                         "initiating next stage...\n");
3756
3757                 dev_notice(&instance->pdev->dev, "HBA recovery state machine,"
3758                                         "state 2 starting...\n");
3759
3760                 /* waiting for about 20 second before start the second init */
3761                 for (wait = 0; wait < 30; wait++) {
3762                         msleep(1000);
3763                 }
3764
3765                 if (megasas_transition_to_ready(instance, 1)) {
3766                         dev_notice(&instance->pdev->dev, "adapter not ready\n");
3767
3768                         atomic_set(&instance->fw_reset_no_pci_access, 1);
3769                         megaraid_sas_kill_hba(instance);
3770                         return ;
3771                 }
3772
3773                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
3774                         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
3775                         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
3776                         ) {
3777                         *instance->consumer = *instance->producer;
3778                 } else {
3779                         *instance->consumer = 0;
3780                         *instance->producer = 0;
3781                 }
3782
3783                 megasas_issue_init_mfi(instance);
3784
3785                 spin_lock_irqsave(&instance->hba_lock, flags);
3786                 atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
3787                 spin_unlock_irqrestore(&instance->hba_lock, flags);
3788                 instance->instancet->enable_intr(instance);
3789
3790                 megasas_issue_pending_cmds_again(instance);
3791                 instance->issuepend_done = 1;
3792         }
3793 }
3794
3795 /**
3796  * megasas_deplete_reply_queue -        Processes all completed commands
3797  * @instance:                           Adapter soft state
3798  * @alt_status:                         Alternate status to be returned to
3799  *                                      SCSI mid-layer instead of the status
3800  *                                      returned by the FW
3801  * Note: this must be called with hba lock held
3802  */
3803 static int
3804 megasas_deplete_reply_queue(struct megasas_instance *instance,
3805                                         u8 alt_status)
3806 {
3807         u32 mfiStatus;
3808         u32 fw_state;
3809
3810         if ((mfiStatus = instance->instancet->check_reset(instance,
3811                                         instance->reg_set)) == 1) {
3812                 return IRQ_HANDLED;
3813         }
3814
3815         mfiStatus = instance->instancet->clear_intr(instance);
3816         if (mfiStatus == 0) {
3817                 /* Hardware may not set outbound_intr_status in MSI-X mode */
3818                 if (!instance->msix_vectors)
3819                         return IRQ_NONE;
3820         }
3821
3822         instance->mfiStatus = mfiStatus;
3823
3824         if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
3825                 fw_state = instance->instancet->read_fw_status_reg(
3826                                 instance) & MFI_STATE_MASK;
3827
3828                 if (fw_state != MFI_STATE_FAULT) {
3829                         dev_notice(&instance->pdev->dev, "fw state:%x\n",
3830                                                 fw_state);
3831                 }
3832
3833                 if ((fw_state == MFI_STATE_FAULT) &&
3834                                 (instance->disableOnlineCtrlReset == 0)) {
3835                         dev_notice(&instance->pdev->dev, "wait adp restart\n");
3836
3837                         if ((instance->pdev->device ==
3838                                         PCI_DEVICE_ID_LSI_SAS1064R) ||
3839                                 (instance->pdev->device ==
3840                                         PCI_DEVICE_ID_DELL_PERC5) ||
3841                                 (instance->pdev->device ==
3842                                         PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
3843
3844                                 *instance->consumer =
3845                                         cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
3846                         }
3847
3848
3849                         instance->instancet->disable_intr(instance);
3850                         atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
3851                         instance->issuepend_done = 0;
3852
3853                         atomic_set(&instance->fw_outstanding, 0);
3854                         megasas_internal_reset_defer_cmds(instance);
3855
3856                         dev_notice(&instance->pdev->dev, "fwState=%x, stage:%d\n",
3857                                         fw_state, atomic_read(&instance->adprecovery));
3858
3859                         schedule_work(&instance->work_init);
3860                         return IRQ_HANDLED;
3861
3862                 } else {
3863                         dev_notice(&instance->pdev->dev, "fwstate:%x, dis_OCR=%x\n",
3864                                 fw_state, instance->disableOnlineCtrlReset);
3865                 }
3866         }
3867
3868         tasklet_schedule(&instance->isr_tasklet);
3869         return IRQ_HANDLED;
3870 }
3871 /**
3872  * megasas_isr - isr entry point
3873  */
3874 static irqreturn_t megasas_isr(int irq, void *devp)
3875 {
3876         struct megasas_irq_context *irq_context = devp;
3877         struct megasas_instance *instance = irq_context->instance;
3878         unsigned long flags;
3879         irqreturn_t rc;
3880
3881         if (atomic_read(&instance->fw_reset_no_pci_access))
3882                 return IRQ_HANDLED;
3883
3884         spin_lock_irqsave(&instance->hba_lock, flags);
3885         rc = megasas_deplete_reply_queue(instance, DID_OK);
3886         spin_unlock_irqrestore(&instance->hba_lock, flags);
3887
3888         return rc;
3889 }
3890
3891 /**
3892  * megasas_transition_to_ready -        Move the FW to READY state
3893  * @instance:                           Adapter soft state
3894  *
3895  * During the initialization, FW passes can potentially be in any one of
3896  * several possible states. If the FW in operational, waiting-for-handshake
3897  * states, driver must take steps to bring it to ready state. Otherwise, it
3898  * has to wait for the ready state.
3899  */
3900 int
3901 megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
3902 {
3903         int i;
3904         u8 max_wait;
3905         u32 fw_state;
3906         u32 cur_state;
3907         u32 abs_state, curr_abs_state;
3908
3909         abs_state = instance->instancet->read_fw_status_reg(instance);
3910         fw_state = abs_state & MFI_STATE_MASK;
3911
3912         if (fw_state != MFI_STATE_READY)
3913                 dev_info(&instance->pdev->dev, "Waiting for FW to come to ready"
3914                        " state\n");
3915
3916         while (fw_state != MFI_STATE_READY) {
3917
3918                 switch (fw_state) {
3919
3920                 case MFI_STATE_FAULT:
3921                         dev_printk(KERN_ERR, &instance->pdev->dev,
3922                                    "FW in FAULT state, Fault code:0x%x subcode:0x%x func:%s\n",
3923                                    abs_state & MFI_STATE_FAULT_CODE,
3924                                    abs_state & MFI_STATE_FAULT_SUBCODE, __func__);
3925                         if (ocr) {
3926                                 max_wait = MEGASAS_RESET_WAIT_TIME;
3927                                 cur_state = MFI_STATE_FAULT;
3928                                 break;
3929                         } else {
3930                                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
3931                                 megasas_dump_reg_set(instance->reg_set);
3932                                 return -ENODEV;
3933                         }
3934
3935                 case MFI_STATE_WAIT_HANDSHAKE:
3936                         /*
3937                          * Set the CLR bit in inbound doorbell
3938                          */
3939                         if ((instance->pdev->device ==
3940                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3941                                 (instance->pdev->device ==
3942                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
3943                                 (instance->adapter_type != MFI_SERIES))
3944                                 writel(
3945                                   MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
3946                                   &instance->reg_set->doorbell);
3947                         else
3948                                 writel(
3949                                     MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
3950                                         &instance->reg_set->inbound_doorbell);
3951
3952                         max_wait = MEGASAS_RESET_WAIT_TIME;
3953                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
3954                         break;
3955
3956                 case MFI_STATE_BOOT_MESSAGE_PENDING:
3957                         if ((instance->pdev->device ==
3958                              PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3959                                 (instance->pdev->device ==
3960                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
3961                                 (instance->adapter_type != MFI_SERIES))
3962                                 writel(MFI_INIT_HOTPLUG,
3963                                        &instance->reg_set->doorbell);
3964                         else
3965                                 writel(MFI_INIT_HOTPLUG,
3966                                         &instance->reg_set->inbound_doorbell);
3967
3968                         max_wait = MEGASAS_RESET_WAIT_TIME;
3969                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
3970                         break;
3971
3972                 case MFI_STATE_OPERATIONAL:
3973                         /*
3974                          * Bring it to READY state; assuming max wait 10 secs
3975                          */
3976                         instance->instancet->disable_intr(instance);
3977                         if ((instance->pdev->device ==
3978                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3979                                 (instance->pdev->device ==
3980                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
3981                                 (instance->adapter_type != MFI_SERIES)) {
3982                                 writel(MFI_RESET_FLAGS,
3983                                         &instance->reg_set->doorbell);
3984
3985                                 if (instance->adapter_type != MFI_SERIES) {
3986                                         for (i = 0; i < (10 * 1000); i += 20) {
3987                                                 if (megasas_readl(
3988                                                             instance,
3989                                                             &instance->
3990                                                             reg_set->
3991                                                             doorbell) & 1)
3992                                                         msleep(20);
3993                                                 else
3994                                                         break;
3995                                         }
3996                                 }
3997                         } else
3998                                 writel(MFI_RESET_FLAGS,
3999                                         &instance->reg_set->inbound_doorbell);
4000
4001                         max_wait = MEGASAS_RESET_WAIT_TIME;
4002                         cur_state = MFI_STATE_OPERATIONAL;
4003                         break;
4004
4005                 case MFI_STATE_UNDEFINED:
4006                         /*
4007                          * This state should not last for more than 2 seconds
4008                          */
4009                         max_wait = MEGASAS_RESET_WAIT_TIME;
4010                         cur_state = MFI_STATE_UNDEFINED;
4011                         break;
4012
4013                 case MFI_STATE_BB_INIT:
4014                         max_wait = MEGASAS_RESET_WAIT_TIME;
4015                         cur_state = MFI_STATE_BB_INIT;
4016                         break;
4017
4018                 case MFI_STATE_FW_INIT:
4019                         max_wait = MEGASAS_RESET_WAIT_TIME;
4020                         cur_state = MFI_STATE_FW_INIT;
4021                         break;
4022
4023                 case MFI_STATE_FW_INIT_2:
4024                         max_wait = MEGASAS_RESET_WAIT_TIME;
4025                         cur_state = MFI_STATE_FW_INIT_2;
4026                         break;
4027
4028                 case MFI_STATE_DEVICE_SCAN:
4029                         max_wait = MEGASAS_RESET_WAIT_TIME;
4030                         cur_state = MFI_STATE_DEVICE_SCAN;
4031                         break;
4032
4033                 case MFI_STATE_FLUSH_CACHE:
4034                         max_wait = MEGASAS_RESET_WAIT_TIME;
4035                         cur_state = MFI_STATE_FLUSH_CACHE;
4036                         break;
4037
4038                 default:
4039                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "Unknown state 0x%x\n",
4040                                fw_state);
4041                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4042                         megasas_dump_reg_set(instance->reg_set);
4043                         return -ENODEV;
4044                 }
4045
4046                 /*
4047                  * The cur_state should not last for more than max_wait secs
4048                  */
4049                 for (i = 0; i < max_wait * 50; i++) {
4050                         curr_abs_state = instance->instancet->
4051                                 read_fw_status_reg(instance);
4052
4053                         if (abs_state == curr_abs_state) {
4054                                 msleep(20);
4055                         } else
4056                                 break;
4057                 }
4058
4059                 /*
4060                  * Return error if fw_state hasn't changed after max_wait
4061                  */
4062                 if (curr_abs_state == abs_state) {
4063                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "FW state [%d] hasn't changed "
4064                                "in %d secs\n", fw_state, max_wait);
4065                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "System Register set:\n");
4066                         megasas_dump_reg_set(instance->reg_set);
4067                         return -ENODEV;
4068                 }
4069
4070                 abs_state = curr_abs_state;
4071                 fw_state = curr_abs_state & MFI_STATE_MASK;
4072         }
4073         dev_info(&instance->pdev->dev, "FW now in Ready state\n");
4074
4075         return 0;
4076 }
4077
4078 /**
4079  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
4080  * @instance:                           Adapter soft state
4081  */
4082 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
4083 {
4084         int i;
4085         u16 max_cmd = instance->max_mfi_cmds;
4086         struct megasas_cmd *cmd;
4087
4088         if (!instance->frame_dma_pool)
4089                 return;
4090
4091         /*
4092          * Return all frames to pool
4093          */
4094         for (i = 0; i < max_cmd; i++) {
4095
4096                 cmd = instance->cmd_list[i];
4097
4098                 if (cmd->frame)
4099                         dma_pool_free(instance->frame_dma_pool, cmd->frame,
4100                                       cmd->frame_phys_addr);
4101
4102                 if (cmd->sense)
4103                         dma_pool_free(instance->sense_dma_pool, cmd->sense,
4104                                       cmd->sense_phys_addr);
4105         }
4106
4107         /*
4108          * Now destroy the pool itself
4109          */
4110         dma_pool_destroy(instance->frame_dma_pool);
4111         dma_pool_destroy(instance->sense_dma_pool);
4112
4113         instance->frame_dma_pool = NULL;
4114         instance->sense_dma_pool = NULL;
4115 }
4116
4117 /**
4118  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
4119  * @instance:                   Adapter soft state
4120  *
4121  * Each command packet has an embedded DMA memory buffer that is used for
4122  * filling MFI frame and the SG list that immediately follows the frame. This
4123  * function creates those DMA memory buffers for each command packet by using
4124  * PCI pool facility.
4125  */
4126 static int megasas_create_frame_pool(struct megasas_instance *instance)
4127 {
4128         int i;
4129         u16 max_cmd;
4130         u32 sge_sz;
4131         u32 frame_count;
4132         struct megasas_cmd *cmd;
4133
4134         max_cmd = instance->max_mfi_cmds;
4135
4136         /*
4137          * Size of our frame is 64 bytes for MFI frame, followed by max SG
4138          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
4139          */
4140         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
4141             sizeof(struct megasas_sge32);
4142
4143         if (instance->flag_ieee)
4144                 sge_sz = sizeof(struct megasas_sge_skinny);
4145
4146         /*
4147          * For MFI controllers.
4148          * max_num_sge = 60
4149          * max_sge_sz  = 16 byte (sizeof megasas_sge_skinny)
4150          * Total 960 byte (15 MFI frame of 64 byte)
4151          *
4152          * Fusion adapter require only 3 extra frame.
4153          * max_num_sge = 16 (defined as MAX_IOCTL_SGE)
4154          * max_sge_sz  = 12 byte (sizeof  megasas_sge64)
4155          * Total 192 byte (3 MFI frame of 64 byte)
4156          */
4157         frame_count = (instance->adapter_type == MFI_SERIES) ?
4158                         (15 + 1) : (3 + 1);
4159         instance->mfi_frame_size = MEGAMFI_FRAME_SIZE * frame_count;
4160         /*
4161          * Use DMA pool facility provided by PCI layer
4162          */
4163         instance->frame_dma_pool = dma_pool_create("megasas frame pool",
4164                                         &instance->pdev->dev,
4165                                         instance->mfi_frame_size, 256, 0);
4166
4167         if (!instance->frame_dma_pool) {
4168                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup frame pool\n");
4169                 return -ENOMEM;
4170         }
4171
4172         instance->sense_dma_pool = dma_pool_create("megasas sense pool",
4173                                                    &instance->pdev->dev, 128,
4174                                                    4, 0);
4175
4176         if (!instance->sense_dma_pool) {
4177                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup sense pool\n");
4178
4179                 dma_pool_destroy(instance->frame_dma_pool);
4180                 instance->frame_dma_pool = NULL;
4181
4182                 return -ENOMEM;
4183         }
4184
4185         /*
4186          * Allocate and attach a frame to each of the commands in cmd_list.
4187          * By making cmd->index as the context instead of the &cmd, we can
4188          * always use 32bit context regardless of the architecture
4189          */
4190         for (i = 0; i < max_cmd; i++) {
4191
4192                 cmd = instance->cmd_list[i];
4193
4194                 cmd->frame = dma_pool_zalloc(instance->frame_dma_pool,
4195                                             GFP_KERNEL, &cmd->frame_phys_addr);
4196
4197                 cmd->sense = dma_pool_alloc(instance->sense_dma_pool,
4198                                             GFP_KERNEL, &cmd->sense_phys_addr);
4199
4200                 /*
4201                  * megasas_teardown_frame_pool() takes care of freeing
4202                  * whatever has been allocated
4203                  */
4204                 if (!cmd->frame || !cmd->sense) {
4205                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "dma_pool_alloc failed\n");
4206                         megasas_teardown_frame_pool(instance);
4207                         return -ENOMEM;
4208                 }
4209
4210                 cmd->frame->io.context = cpu_to_le32(cmd->index);
4211                 cmd->frame->io.pad_0 = 0;
4212                 if ((instance->adapter_type == MFI_SERIES) && reset_devices)
4213                         cmd->frame->hdr.cmd = MFI_CMD_INVALID;
4214         }
4215
4216         return 0;
4217 }
4218
4219 /**
4220  * megasas_free_cmds -  Free all the cmds in the free cmd pool
4221  * @instance:           Adapter soft state
4222  */
4223 void megasas_free_cmds(struct megasas_instance *instance)
4224 {
4225         int i;
4226
4227         /* First free the MFI frame pool */
4228         megasas_teardown_frame_pool(instance);
4229
4230         /* Free all the commands in the cmd_list */
4231         for (i = 0; i < instance->max_mfi_cmds; i++)
4232
4233                 kfree(instance->cmd_list[i]);
4234
4235         /* Free the cmd_list buffer itself */
4236         kfree(instance->cmd_list);
4237         instance->cmd_list = NULL;
4238
4239         INIT_LIST_HEAD(&instance->cmd_pool);
4240 }
4241
4242 /**
4243  * megasas_alloc_cmds - Allocates the command packets
4244  * @instance:           Adapter soft state
4245  *
4246  * Each command that is issued to the FW, whether IO commands from the OS or
4247  * internal commands like IOCTLs, are wrapped in local data structure called
4248  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
4249  * the FW.
4250  *
4251  * Each frame has a 32-bit field called context (tag). This context is used
4252  * to get back the megasas_cmd from the frame when a frame gets completed in
4253  * the ISR. Typically the address of the megasas_cmd itself would be used as
4254  * the context. But we wanted to keep the differences between 32 and 64 bit
4255  * systems to the mininum. We always use 32 bit integers for the context. In
4256  * this driver, the 32 bit values are the indices into an array cmd_list.
4257  * This array is used only to look up the megasas_cmd given the context. The
4258  * free commands themselves are maintained in a linked list called cmd_pool.
4259  */
4260 int megasas_alloc_cmds(struct megasas_instance *instance)
4261 {
4262         int i;
4263         int j;
4264         u16 max_cmd;
4265         struct megasas_cmd *cmd;
4266
4267         max_cmd = instance->max_mfi_cmds;
4268
4269         /*
4270          * instance->cmd_list is an array of struct megasas_cmd pointers.
4271          * Allocate the dynamic array first and then allocate individual
4272          * commands.
4273          */
4274         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
4275
4276         if (!instance->cmd_list) {
4277                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
4278                 return -ENOMEM;
4279         }
4280
4281         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
4282
4283         for (i = 0; i < max_cmd; i++) {
4284                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
4285                                                 GFP_KERNEL);
4286
4287                 if (!instance->cmd_list[i]) {
4288
4289                         for (j = 0; j < i; j++)
4290                                 kfree(instance->cmd_list[j]);
4291
4292                         kfree(instance->cmd_list);
4293                         instance->cmd_list = NULL;
4294
4295                         return -ENOMEM;
4296                 }
4297         }
4298
4299         for (i = 0; i < max_cmd; i++) {
4300                 cmd = instance->cmd_list[i];
4301                 memset(cmd, 0, sizeof(struct megasas_cmd));
4302                 cmd->index = i;
4303                 cmd->scmd = NULL;
4304                 cmd->instance = instance;
4305
4306                 list_add_tail(&cmd->list, &instance->cmd_pool);
4307         }
4308
4309         /*
4310          * Create a frame pool and assign one frame to each cmd
4311          */
4312         if (megasas_create_frame_pool(instance)) {
4313                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
4314                 megasas_free_cmds(instance);
4315                 return -ENOMEM;
4316         }
4317
4318         return 0;
4319 }
4320
4321 /*
4322  * dcmd_timeout_ocr_possible -  Check if OCR is possible based on Driver/FW state.
4323  * @instance:                           Adapter soft state
4324  *
4325  * Return 0 for only Fusion adapter, if driver load/unload is not in progress
4326  * or FW is not under OCR.
4327  */
4328 inline int
4329 dcmd_timeout_ocr_possible(struct megasas_instance *instance) {
4330
4331         if (instance->adapter_type == MFI_SERIES)
4332                 return KILL_ADAPTER;
4333         else if (instance->unload ||
4334                         test_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags))
4335                 return IGNORE_TIMEOUT;
4336         else
4337                 return INITIATE_OCR;
4338 }
4339
4340 static void
4341 megasas_get_pd_info(struct megasas_instance *instance, struct scsi_device *sdev)
4342 {
4343         int ret;
4344         struct megasas_cmd *cmd;
4345         struct megasas_dcmd_frame *dcmd;
4346
4347         struct MR_PRIV_DEVICE *mr_device_priv_data;
4348         u16 device_id = 0;
4349
4350         device_id = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) + sdev->id;
4351         cmd = megasas_get_cmd(instance);
4352
4353         if (!cmd) {
4354                 dev_err(&instance->pdev->dev, "Failed to get cmd %s\n", __func__);
4355                 return;
4356         }
4357
4358         dcmd = &cmd->frame->dcmd;
4359
4360         memset(instance->pd_info, 0, sizeof(*instance->pd_info));
4361         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4362
4363         dcmd->mbox.s[0] = cpu_to_le16(device_id);
4364         dcmd->cmd = MFI_CMD_DCMD;
4365         dcmd->cmd_status = 0xFF;
4366         dcmd->sge_count = 1;
4367         dcmd->flags = MFI_FRAME_DIR_READ;
4368         dcmd->timeout = 0;
4369         dcmd->pad_0 = 0;
4370         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_PD_INFO));
4371         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_GET_INFO);
4372
4373         megasas_set_dma_settings(instance, dcmd, instance->pd_info_h,
4374                                  sizeof(struct MR_PD_INFO));
4375
4376         if ((instance->adapter_type != MFI_SERIES) &&
4377             !instance->mask_interrupts)
4378                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4379         else
4380                 ret = megasas_issue_polled(instance, cmd);
4381
4382         switch (ret) {
4383         case DCMD_SUCCESS:
4384                 mr_device_priv_data = sdev->hostdata;
4385                 le16_to_cpus((u16 *)&instance->pd_info->state.ddf.pdType);
4386                 mr_device_priv_data->interface_type =
4387                                 instance->pd_info->state.ddf.pdType.intf;
4388                 break;
4389
4390         case DCMD_TIMEOUT:
4391
4392                 switch (dcmd_timeout_ocr_possible(instance)) {
4393                 case INITIATE_OCR:
4394                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4395                         megasas_reset_fusion(instance->host,
4396                                 MFI_IO_TIMEOUT_OCR);
4397                         break;
4398                 case KILL_ADAPTER:
4399                         megaraid_sas_kill_hba(instance);
4400                         break;
4401                 case IGNORE_TIMEOUT:
4402                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4403                                 __func__, __LINE__);
4404                         break;
4405                 }
4406
4407                 break;
4408         }
4409
4410         if (ret != DCMD_TIMEOUT)
4411                 megasas_return_cmd(instance, cmd);
4412
4413         return;
4414 }
4415 /*
4416  * megasas_get_pd_list_info -   Returns FW's pd_list structure
4417  * @instance:                           Adapter soft state
4418  * @pd_list:                            pd_list structure
4419  *
4420  * Issues an internal command (DCMD) to get the FW's controller PD
4421  * list structure.  This information is mainly used to find out SYSTEM
4422  * supported by the FW.
4423  */
4424 static int
4425 megasas_get_pd_list(struct megasas_instance *instance)
4426 {
4427         int ret = 0, pd_index = 0;
4428         struct megasas_cmd *cmd;
4429         struct megasas_dcmd_frame *dcmd;
4430         struct MR_PD_LIST *ci;
4431         struct MR_PD_ADDRESS *pd_addr;
4432         dma_addr_t ci_h = 0;
4433
4434         if (instance->pd_list_not_supported) {
4435                 dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4436                 "not supported by firmware\n");
4437                 return ret;
4438         }
4439
4440         ci = instance->pd_list_buf;
4441         ci_h = instance->pd_list_buf_h;
4442
4443         cmd = megasas_get_cmd(instance);
4444
4445         if (!cmd) {
4446                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "(get_pd_list): Failed to get cmd\n");
4447                 return -ENOMEM;
4448         }
4449
4450         dcmd = &cmd->frame->dcmd;
4451
4452         memset(ci, 0, sizeof(*ci));
4453         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4454
4455         dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
4456         dcmd->mbox.b[1] = 0;
4457         dcmd->cmd = MFI_CMD_DCMD;
4458         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4459         dcmd->sge_count = 1;
4460         dcmd->flags = MFI_FRAME_DIR_READ;
4461         dcmd->timeout = 0;
4462         dcmd->pad_0 = 0;
4463         dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
4464         dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY);
4465
4466         megasas_set_dma_settings(instance, dcmd, instance->pd_list_buf_h,
4467                                  (MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST)));
4468
4469         if ((instance->adapter_type != MFI_SERIES) &&
4470             !instance->mask_interrupts)
4471                 ret = megasas_issue_blocked_cmd(instance, cmd,
4472                         MFI_IO_TIMEOUT_SECS);
4473         else
4474                 ret = megasas_issue_polled(instance, cmd);
4475
4476         switch (ret) {
4477         case DCMD_FAILED:
4478                 dev_info(&instance->pdev->dev, "MR_DCMD_PD_LIST_QUERY "
4479                         "failed/not supported by firmware\n");
4480
4481                 if (instance->adapter_type != MFI_SERIES)
4482                         megaraid_sas_kill_hba(instance);
4483                 else
4484                         instance->pd_list_not_supported = 1;
4485                 break;
4486         case DCMD_TIMEOUT:
4487
4488                 switch (dcmd_timeout_ocr_possible(instance)) {
4489                 case INITIATE_OCR:
4490                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4491                         /*
4492                          * DCMD failed from AEN path.
4493                          * AEN path already hold reset_mutex to avoid PCI access
4494                          * while OCR is in progress.
4495                          */
4496                         mutex_unlock(&instance->reset_mutex);
4497                         megasas_reset_fusion(instance->host,
4498                                                 MFI_IO_TIMEOUT_OCR);
4499                         mutex_lock(&instance->reset_mutex);
4500                         break;
4501                 case KILL_ADAPTER:
4502                         megaraid_sas_kill_hba(instance);
4503                         break;
4504                 case IGNORE_TIMEOUT:
4505                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d \n",
4506                                 __func__, __LINE__);
4507                         break;
4508                 }
4509
4510                 break;
4511
4512         case DCMD_SUCCESS:
4513                 pd_addr = ci->addr;
4514                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4515                         dev_info(&instance->pdev->dev, "%s, sysPD count: 0x%x\n",
4516                                  __func__, le32_to_cpu(ci->count));
4517
4518                 if ((le32_to_cpu(ci->count) >
4519                         (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL)))
4520                         break;
4521
4522                 memset(instance->local_pd_list, 0,
4523                                 MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
4524
4525                 for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) {
4526                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid     =
4527                                         le16_to_cpu(pd_addr->deviceId);
4528                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType       =
4529                                         pd_addr->scsiDevType;
4530                         instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState      =
4531                                         MR_PD_STATE_SYSTEM;
4532                         if (megasas_dbg_lvl & LD_PD_DEBUG)
4533                                 dev_info(&instance->pdev->dev,
4534                                          "PD%d: targetID: 0x%03x deviceType:0x%x\n",
4535                                          pd_index, le16_to_cpu(pd_addr->deviceId),
4536                                          pd_addr->scsiDevType);
4537                         pd_addr++;
4538                 }
4539
4540                 memcpy(instance->pd_list, instance->local_pd_list,
4541                         sizeof(instance->pd_list));
4542                 break;
4543
4544         }
4545
4546         if (ret != DCMD_TIMEOUT)
4547                 megasas_return_cmd(instance, cmd);
4548
4549         return ret;
4550 }
4551
4552 /*
4553  * megasas_get_ld_list_info -   Returns FW's ld_list structure
4554  * @instance:                           Adapter soft state
4555  * @ld_list:                            ld_list structure
4556  *
4557  * Issues an internal command (DCMD) to get the FW's controller PD
4558  * list structure.  This information is mainly used to find out SYSTEM
4559  * supported by the FW.
4560  */
4561 static int
4562 megasas_get_ld_list(struct megasas_instance *instance)
4563 {
4564         int ret = 0, ld_index = 0, ids = 0;
4565         struct megasas_cmd *cmd;
4566         struct megasas_dcmd_frame *dcmd;
4567         struct MR_LD_LIST *ci;
4568         dma_addr_t ci_h = 0;
4569         u32 ld_count;
4570
4571         ci = instance->ld_list_buf;
4572         ci_h = instance->ld_list_buf_h;
4573
4574         cmd = megasas_get_cmd(instance);
4575
4576         if (!cmd) {
4577                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "megasas_get_ld_list: Failed to get cmd\n");
4578                 return -ENOMEM;
4579         }
4580
4581         dcmd = &cmd->frame->dcmd;
4582
4583         memset(ci, 0, sizeof(*ci));
4584         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4585
4586         if (instance->supportmax256vd)
4587                 dcmd->mbox.b[0] = 1;
4588         dcmd->cmd = MFI_CMD_DCMD;
4589         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4590         dcmd->sge_count = 1;
4591         dcmd->flags = MFI_FRAME_DIR_READ;
4592         dcmd->timeout = 0;
4593         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST));
4594         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST);
4595         dcmd->pad_0  = 0;
4596
4597         megasas_set_dma_settings(instance, dcmd, ci_h,
4598                                  sizeof(struct MR_LD_LIST));
4599
4600         if ((instance->adapter_type != MFI_SERIES) &&
4601             !instance->mask_interrupts)
4602                 ret = megasas_issue_blocked_cmd(instance, cmd,
4603                         MFI_IO_TIMEOUT_SECS);
4604         else
4605                 ret = megasas_issue_polled(instance, cmd);
4606
4607         ld_count = le32_to_cpu(ci->ldCount);
4608
4609         switch (ret) {
4610         case DCMD_FAILED:
4611                 megaraid_sas_kill_hba(instance);
4612                 break;
4613         case DCMD_TIMEOUT:
4614
4615                 switch (dcmd_timeout_ocr_possible(instance)) {
4616                 case INITIATE_OCR:
4617                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4618                         /*
4619                          * DCMD failed from AEN path.
4620                          * AEN path already hold reset_mutex to avoid PCI access
4621                          * while OCR is in progress.
4622                          */
4623                         mutex_unlock(&instance->reset_mutex);
4624                         megasas_reset_fusion(instance->host,
4625                                                 MFI_IO_TIMEOUT_OCR);
4626                         mutex_lock(&instance->reset_mutex);
4627                         break;
4628                 case KILL_ADAPTER:
4629                         megaraid_sas_kill_hba(instance);
4630                         break;
4631                 case IGNORE_TIMEOUT:
4632                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4633                                 __func__, __LINE__);
4634                         break;
4635                 }
4636
4637                 break;
4638
4639         case DCMD_SUCCESS:
4640                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4641                         dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4642                                  __func__, ld_count);
4643
4644                 if (ld_count > instance->fw_supported_vd_count)
4645                         break;
4646
4647                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
4648
4649                 for (ld_index = 0; ld_index < ld_count; ld_index++) {
4650                         if (ci->ldList[ld_index].state != 0) {
4651                                 ids = ci->ldList[ld_index].ref.targetId;
4652                                 instance->ld_ids[ids] = ci->ldList[ld_index].ref.targetId;
4653                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4654                                         dev_info(&instance->pdev->dev,
4655                                                  "LD%d: targetID: 0x%03x\n",
4656                                                  ld_index, ids);
4657                         }
4658                 }
4659
4660                 break;
4661         }
4662
4663         if (ret != DCMD_TIMEOUT)
4664                 megasas_return_cmd(instance, cmd);
4665
4666         return ret;
4667 }
4668
4669 /**
4670  * megasas_ld_list_query -      Returns FW's ld_list structure
4671  * @instance:                           Adapter soft state
4672  * @ld_list:                            ld_list structure
4673  *
4674  * Issues an internal command (DCMD) to get the FW's controller PD
4675  * list structure.  This information is mainly used to find out SYSTEM
4676  * supported by the FW.
4677  */
4678 static int
4679 megasas_ld_list_query(struct megasas_instance *instance, u8 query_type)
4680 {
4681         int ret = 0, ld_index = 0, ids = 0;
4682         struct megasas_cmd *cmd;
4683         struct megasas_dcmd_frame *dcmd;
4684         struct MR_LD_TARGETID_LIST *ci;
4685         dma_addr_t ci_h = 0;
4686         u32 tgtid_count;
4687
4688         ci = instance->ld_targetid_list_buf;
4689         ci_h = instance->ld_targetid_list_buf_h;
4690
4691         cmd = megasas_get_cmd(instance);
4692
4693         if (!cmd) {
4694                 dev_warn(&instance->pdev->dev,
4695                          "megasas_ld_list_query: Failed to get cmd\n");
4696                 return -ENOMEM;
4697         }
4698
4699         dcmd = &cmd->frame->dcmd;
4700
4701         memset(ci, 0, sizeof(*ci));
4702         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4703
4704         dcmd->mbox.b[0] = query_type;
4705         if (instance->supportmax256vd)
4706                 dcmd->mbox.b[2] = 1;
4707
4708         dcmd->cmd = MFI_CMD_DCMD;
4709         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4710         dcmd->sge_count = 1;
4711         dcmd->flags = MFI_FRAME_DIR_READ;
4712         dcmd->timeout = 0;
4713         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
4714         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY);
4715         dcmd->pad_0  = 0;
4716
4717         megasas_set_dma_settings(instance, dcmd, ci_h,
4718                                  sizeof(struct MR_LD_TARGETID_LIST));
4719
4720         if ((instance->adapter_type != MFI_SERIES) &&
4721             !instance->mask_interrupts)
4722                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
4723         else
4724                 ret = megasas_issue_polled(instance, cmd);
4725
4726         switch (ret) {
4727         case DCMD_FAILED:
4728                 dev_info(&instance->pdev->dev,
4729                         "DCMD not supported by firmware - %s %d\n",
4730                                 __func__, __LINE__);
4731                 ret = megasas_get_ld_list(instance);
4732                 break;
4733         case DCMD_TIMEOUT:
4734                 switch (dcmd_timeout_ocr_possible(instance)) {
4735                 case INITIATE_OCR:
4736                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4737                         /*
4738                          * DCMD failed from AEN path.
4739                          * AEN path already hold reset_mutex to avoid PCI access
4740                          * while OCR is in progress.
4741                          */
4742                         mutex_unlock(&instance->reset_mutex);
4743                         megasas_reset_fusion(instance->host,
4744                                                 MFI_IO_TIMEOUT_OCR);
4745                         mutex_lock(&instance->reset_mutex);
4746                         break;
4747                 case KILL_ADAPTER:
4748                         megaraid_sas_kill_hba(instance);
4749                         break;
4750                 case IGNORE_TIMEOUT:
4751                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4752                                 __func__, __LINE__);
4753                         break;
4754                 }
4755
4756                 break;
4757         case DCMD_SUCCESS:
4758                 tgtid_count = le32_to_cpu(ci->count);
4759
4760                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4761                         dev_info(&instance->pdev->dev, "%s, LD count: 0x%x\n",
4762                                  __func__, tgtid_count);
4763
4764                 if ((tgtid_count > (instance->fw_supported_vd_count)))
4765                         break;
4766
4767                 memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4768                 for (ld_index = 0; ld_index < tgtid_count; ld_index++) {
4769                         ids = ci->targetId[ld_index];
4770                         instance->ld_ids[ids] = ci->targetId[ld_index];
4771                         if (megasas_dbg_lvl & LD_PD_DEBUG)
4772                                 dev_info(&instance->pdev->dev, "LD%d: targetID: 0x%03x\n",
4773                                          ld_index, ci->targetId[ld_index]);
4774                 }
4775
4776                 break;
4777         }
4778
4779         if (ret != DCMD_TIMEOUT)
4780                 megasas_return_cmd(instance, cmd);
4781
4782         return ret;
4783 }
4784
4785 /**
4786  * dcmd.opcode            - MR_DCMD_CTRL_DEVICE_LIST_GET
4787  * dcmd.mbox              - reserved
4788  * dcmd.sge IN            - ptr to return MR_HOST_DEVICE_LIST structure
4789  * Desc:    This DCMD will return the combined device list
4790  * Status:  MFI_STAT_OK - List returned successfully
4791  *          MFI_STAT_INVALID_CMD - Firmware support for the feature has been
4792  *                                 disabled
4793  * @instance:                   Adapter soft state
4794  * @is_probe:                   Driver probe check
4795  * Return:                      0 if DCMD succeeded
4796  *                               non-zero if failed
4797  */
4798 static int
4799 megasas_host_device_list_query(struct megasas_instance *instance,
4800                                bool is_probe)
4801 {
4802         int ret, i, target_id;
4803         struct megasas_cmd *cmd;
4804         struct megasas_dcmd_frame *dcmd;
4805         struct MR_HOST_DEVICE_LIST *ci;
4806         u32 count;
4807         dma_addr_t ci_h;
4808
4809         ci = instance->host_device_list_buf;
4810         ci_h = instance->host_device_list_buf_h;
4811
4812         cmd = megasas_get_cmd(instance);
4813
4814         if (!cmd) {
4815                 dev_warn(&instance->pdev->dev,
4816                          "%s: failed to get cmd\n",
4817                          __func__);
4818                 return -ENOMEM;
4819         }
4820
4821         dcmd = &cmd->frame->dcmd;
4822
4823         memset(ci, 0, sizeof(*ci));
4824         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4825
4826         dcmd->mbox.b[0] = is_probe ? 0 : 1;
4827         dcmd->cmd = MFI_CMD_DCMD;
4828         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
4829         dcmd->sge_count = 1;
4830         dcmd->flags = MFI_FRAME_DIR_READ;
4831         dcmd->timeout = 0;
4832         dcmd->pad_0 = 0;
4833         dcmd->data_xfer_len = cpu_to_le32(HOST_DEVICE_LIST_SZ);
4834         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_DEVICE_LIST_GET);
4835
4836         megasas_set_dma_settings(instance, dcmd, ci_h, HOST_DEVICE_LIST_SZ);
4837
4838         if (!instance->mask_interrupts) {
4839                 ret = megasas_issue_blocked_cmd(instance, cmd,
4840                                                 MFI_IO_TIMEOUT_SECS);
4841         } else {
4842                 ret = megasas_issue_polled(instance, cmd);
4843                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4844         }
4845
4846         switch (ret) {
4847         case DCMD_SUCCESS:
4848                 /* Fill the internal pd_list and ld_ids array based on
4849                  * targetIds returned by FW
4850                  */
4851                 count = le32_to_cpu(ci->count);
4852
4853                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4854                         dev_info(&instance->pdev->dev, "%s, Device count: 0x%x\n",
4855                                  __func__, count);
4856
4857                 memset(instance->local_pd_list, 0,
4858                        MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
4859                 memset(instance->ld_ids, 0xff, MAX_LOGICAL_DRIVES_EXT);
4860                 for (i = 0; i < count; i++) {
4861                         target_id = le16_to_cpu(ci->host_device_list[i].target_id);
4862                         if (ci->host_device_list[i].flags.u.bits.is_sys_pd) {
4863                                 instance->local_pd_list[target_id].tid = target_id;
4864                                 instance->local_pd_list[target_id].driveType =
4865                                                 ci->host_device_list[i].scsi_type;
4866                                 instance->local_pd_list[target_id].driveState =
4867                                                 MR_PD_STATE_SYSTEM;
4868                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4869                                         dev_info(&instance->pdev->dev,
4870                                                  "Device %d: PD targetID: 0x%03x deviceType:0x%x\n",
4871                                                  i, target_id, ci->host_device_list[i].scsi_type);
4872                         } else {
4873                                 instance->ld_ids[target_id] = target_id;
4874                                 if (megasas_dbg_lvl & LD_PD_DEBUG)
4875                                         dev_info(&instance->pdev->dev,
4876                                                  "Device %d: LD targetID: 0x%03x\n",
4877                                                  i, target_id);
4878                         }
4879                 }
4880
4881                 memcpy(instance->pd_list, instance->local_pd_list,
4882                        sizeof(instance->pd_list));
4883                 break;
4884
4885         case DCMD_TIMEOUT:
4886                 switch (dcmd_timeout_ocr_possible(instance)) {
4887                 case INITIATE_OCR:
4888                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
4889                         megasas_reset_fusion(instance->host,
4890                                 MFI_IO_TIMEOUT_OCR);
4891                         break;
4892                 case KILL_ADAPTER:
4893                         megaraid_sas_kill_hba(instance);
4894                         break;
4895                 case IGNORE_TIMEOUT:
4896                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
4897                                  __func__, __LINE__);
4898                         break;
4899                 }
4900                 break;
4901         case DCMD_FAILED:
4902                 dev_err(&instance->pdev->dev,
4903                         "%s: MR_DCMD_CTRL_DEVICE_LIST_GET failed\n",
4904                         __func__);
4905                 break;
4906         }
4907
4908         if (ret != DCMD_TIMEOUT)
4909                 megasas_return_cmd(instance, cmd);
4910
4911         return ret;
4912 }
4913
4914 /*
4915  * megasas_update_ext_vd_details : Update details w.r.t Extended VD
4916  * instance                      : Controller's instance
4917 */
4918 static void megasas_update_ext_vd_details(struct megasas_instance *instance)
4919 {
4920         struct fusion_context *fusion;
4921         u32 ventura_map_sz = 0;
4922
4923         fusion = instance->ctrl_context;
4924         /* For MFI based controllers return dummy success */
4925         if (!fusion)
4926                 return;
4927
4928         instance->supportmax256vd =
4929                 instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs;
4930         /* Below is additional check to address future FW enhancement */
4931         if (instance->ctrl_info_buf->max_lds > 64)
4932                 instance->supportmax256vd = 1;
4933
4934         instance->drv_supported_vd_count = MEGASAS_MAX_LD_CHANNELS
4935                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
4936         instance->drv_supported_pd_count = MEGASAS_MAX_PD_CHANNELS
4937                                         * MEGASAS_MAX_DEV_PER_CHANNEL;
4938         if (instance->supportmax256vd) {
4939                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES_EXT;
4940                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
4941         } else {
4942                 instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
4943                 instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
4944         }
4945
4946         dev_info(&instance->pdev->dev,
4947                 "FW provided supportMaxExtLDs: %d\tmax_lds: %d\n",
4948                 instance->ctrl_info_buf->adapterOperations3.supportMaxExtLDs ? 1 : 0,
4949                 instance->ctrl_info_buf->max_lds);
4950
4951         if (instance->max_raid_mapsize) {
4952                 ventura_map_sz = instance->max_raid_mapsize *
4953                                                 MR_MIN_MAP_SIZE; /* 64k */
4954                 fusion->current_map_sz = ventura_map_sz;
4955                 fusion->max_map_sz = ventura_map_sz;
4956         } else {
4957                 fusion->old_map_sz =  sizeof(struct MR_FW_RAID_MAP) +
4958                                         (sizeof(struct MR_LD_SPAN_MAP) *
4959                                         (instance->fw_supported_vd_count - 1));
4960                 fusion->new_map_sz =  sizeof(struct MR_FW_RAID_MAP_EXT);
4961
4962                 fusion->max_map_sz =
4963                         max(fusion->old_map_sz, fusion->new_map_sz);
4964
4965                 if (instance->supportmax256vd)
4966                         fusion->current_map_sz = fusion->new_map_sz;
4967                 else
4968                         fusion->current_map_sz = fusion->old_map_sz;
4969         }
4970         /* irrespective of FW raid maps, driver raid map is constant */
4971         fusion->drv_map_sz = sizeof(struct MR_DRV_RAID_MAP_ALL);
4972 }
4973
4974 /*
4975  * dcmd.opcode                - MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES
4976  * dcmd.hdr.length            - number of bytes to read
4977  * dcmd.sge                   - Ptr to MR_SNAPDUMP_PROPERTIES
4978  * Desc:                         Fill in snapdump properties
4979  * Status:                       MFI_STAT_OK- Command successful
4980  */
4981 void megasas_get_snapdump_properties(struct megasas_instance *instance)
4982 {
4983         int ret = 0;
4984         struct megasas_cmd *cmd;
4985         struct megasas_dcmd_frame *dcmd;
4986         struct MR_SNAPDUMP_PROPERTIES *ci;
4987         dma_addr_t ci_h = 0;
4988
4989         ci = instance->snapdump_prop;
4990         ci_h = instance->snapdump_prop_h;
4991
4992         if (!ci)
4993                 return;
4994
4995         cmd = megasas_get_cmd(instance);
4996
4997         if (!cmd) {
4998                 dev_dbg(&instance->pdev->dev, "Failed to get a free cmd\n");
4999                 return;
5000         }
5001
5002         dcmd = &cmd->frame->dcmd;
5003
5004         memset(ci, 0, sizeof(*ci));
5005         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5006
5007         dcmd->cmd = MFI_CMD_DCMD;
5008         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5009         dcmd->sge_count = 1;
5010         dcmd->flags = MFI_FRAME_DIR_READ;
5011         dcmd->timeout = 0;
5012         dcmd->pad_0 = 0;
5013         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_SNAPDUMP_PROPERTIES));
5014         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SNAPDUMP_GET_PROPERTIES);
5015
5016         megasas_set_dma_settings(instance, dcmd, ci_h,
5017                                  sizeof(struct MR_SNAPDUMP_PROPERTIES));
5018
5019         if (!instance->mask_interrupts) {
5020                 ret = megasas_issue_blocked_cmd(instance, cmd,
5021                                                 MFI_IO_TIMEOUT_SECS);
5022         } else {
5023                 ret = megasas_issue_polled(instance, cmd);
5024                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5025         }
5026
5027         switch (ret) {
5028         case DCMD_SUCCESS:
5029                 instance->snapdump_wait_time =
5030                         min_t(u8, ci->trigger_min_num_sec_before_ocr,
5031                                 MEGASAS_MAX_SNAP_DUMP_WAIT_TIME);
5032                 break;
5033
5034         case DCMD_TIMEOUT:
5035                 switch (dcmd_timeout_ocr_possible(instance)) {
5036                 case INITIATE_OCR:
5037                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5038                         megasas_reset_fusion(instance->host,
5039                                 MFI_IO_TIMEOUT_OCR);
5040                         break;
5041                 case KILL_ADAPTER:
5042                         megaraid_sas_kill_hba(instance);
5043                         break;
5044                 case IGNORE_TIMEOUT:
5045                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5046                                 __func__, __LINE__);
5047                         break;
5048                 }
5049         }
5050
5051         if (ret != DCMD_TIMEOUT)
5052                 megasas_return_cmd(instance, cmd);
5053 }
5054
5055 /**
5056  * megasas_get_controller_info -        Returns FW's controller structure
5057  * @instance:                           Adapter soft state
5058  *
5059  * Issues an internal command (DCMD) to get the FW's controller structure.
5060  * This information is mainly used to find out the maximum IO transfer per
5061  * command supported by the FW.
5062  */
5063 int
5064 megasas_get_ctrl_info(struct megasas_instance *instance)
5065 {
5066         int ret = 0;
5067         struct megasas_cmd *cmd;
5068         struct megasas_dcmd_frame *dcmd;
5069         struct megasas_ctrl_info *ci;
5070         dma_addr_t ci_h = 0;
5071
5072         ci = instance->ctrl_info_buf;
5073         ci_h = instance->ctrl_info_buf_h;
5074
5075         cmd = megasas_get_cmd(instance);
5076
5077         if (!cmd) {
5078                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a free cmd\n");
5079                 return -ENOMEM;
5080         }
5081
5082         dcmd = &cmd->frame->dcmd;
5083
5084         memset(ci, 0, sizeof(*ci));
5085         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5086
5087         dcmd->cmd = MFI_CMD_DCMD;
5088         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5089         dcmd->sge_count = 1;
5090         dcmd->flags = MFI_FRAME_DIR_READ;
5091         dcmd->timeout = 0;
5092         dcmd->pad_0 = 0;
5093         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info));
5094         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO);
5095         dcmd->mbox.b[0] = 1;
5096
5097         megasas_set_dma_settings(instance, dcmd, ci_h,
5098                                  sizeof(struct megasas_ctrl_info));
5099
5100         if ((instance->adapter_type != MFI_SERIES) &&
5101             !instance->mask_interrupts) {
5102                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5103         } else {
5104                 ret = megasas_issue_polled(instance, cmd);
5105                 cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5106         }
5107
5108         switch (ret) {
5109         case DCMD_SUCCESS:
5110                 /* Save required controller information in
5111                  * CPU endianness format.
5112                  */
5113                 le32_to_cpus((u32 *)&ci->properties.OnOffProperties);
5114                 le16_to_cpus((u16 *)&ci->properties.on_off_properties2);
5115                 le32_to_cpus((u32 *)&ci->adapterOperations2);
5116                 le32_to_cpus((u32 *)&ci->adapterOperations3);
5117                 le16_to_cpus((u16 *)&ci->adapter_operations4);
5118
5119                 /* Update the latest Ext VD info.
5120                  * From Init path, store current firmware details.
5121                  * From OCR path, detect any firmware properties changes.
5122                  * in case of Firmware upgrade without system reboot.
5123                  */
5124                 megasas_update_ext_vd_details(instance);
5125                 instance->use_seqnum_jbod_fp =
5126                         ci->adapterOperations3.useSeqNumJbodFP;
5127                 instance->support_morethan256jbod =
5128                         ci->adapter_operations4.support_pd_map_target_id;
5129                 instance->support_nvme_passthru =
5130                         ci->adapter_operations4.support_nvme_passthru;
5131                 instance->task_abort_tmo = ci->TaskAbortTO;
5132                 instance->max_reset_tmo = ci->MaxResetTO;
5133
5134                 /*Check whether controller is iMR or MR */
5135                 instance->is_imr = (ci->memory_size ? 0 : 1);
5136
5137                 instance->snapdump_wait_time =
5138                         (ci->properties.on_off_properties2.enable_snap_dump ?
5139                          MEGASAS_DEFAULT_SNAP_DUMP_WAIT_TIME : 0);
5140
5141                 instance->enable_fw_dev_list =
5142                         ci->properties.on_off_properties2.enable_fw_dev_list;
5143
5144                 dev_info(&instance->pdev->dev,
5145                         "controller type\t: %s(%dMB)\n",
5146                         instance->is_imr ? "iMR" : "MR",
5147                         le16_to_cpu(ci->memory_size));
5148
5149                 instance->disableOnlineCtrlReset =
5150                         ci->properties.OnOffProperties.disableOnlineCtrlReset;
5151                 instance->secure_jbod_support =
5152                         ci->adapterOperations3.supportSecurityonJBOD;
5153                 dev_info(&instance->pdev->dev, "Online Controller Reset(OCR)\t: %s\n",
5154                         instance->disableOnlineCtrlReset ? "Disabled" : "Enabled");
5155                 dev_info(&instance->pdev->dev, "Secure JBOD support\t: %s\n",
5156                         instance->secure_jbod_support ? "Yes" : "No");
5157                 dev_info(&instance->pdev->dev, "NVMe passthru support\t: %s\n",
5158                          instance->support_nvme_passthru ? "Yes" : "No");
5159                 dev_info(&instance->pdev->dev,
5160                          "FW provided TM TaskAbort/Reset timeout\t: %d secs/%d secs\n",
5161                          instance->task_abort_tmo, instance->max_reset_tmo);
5162
5163                 break;
5164
5165         case DCMD_TIMEOUT:
5166                 switch (dcmd_timeout_ocr_possible(instance)) {
5167                 case INITIATE_OCR:
5168                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5169                         megasas_reset_fusion(instance->host,
5170                                 MFI_IO_TIMEOUT_OCR);
5171                         break;
5172                 case KILL_ADAPTER:
5173                         megaraid_sas_kill_hba(instance);
5174                         break;
5175                 case IGNORE_TIMEOUT:
5176                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5177                                 __func__, __LINE__);
5178                         break;
5179                 }
5180                 break;
5181         case DCMD_FAILED:
5182                 megaraid_sas_kill_hba(instance);
5183                 break;
5184
5185         }
5186
5187         if (ret != DCMD_TIMEOUT)
5188                 megasas_return_cmd(instance, cmd);
5189
5190         return ret;
5191 }
5192
5193 /*
5194  * megasas_set_crash_dump_params -      Sends address of crash dump DMA buffer
5195  *                                      to firmware
5196  *
5197  * @instance:                           Adapter soft state
5198  * @crash_buf_state             -       tell FW to turn ON/OFF crash dump feature
5199                                         MR_CRASH_BUF_TURN_OFF = 0
5200                                         MR_CRASH_BUF_TURN_ON = 1
5201  * @return 0 on success non-zero on failure.
5202  * Issues an internal command (DCMD) to set parameters for crash dump feature.
5203  * Driver will send address of crash dump DMA buffer and set mbox to tell FW
5204  * that driver supports crash dump feature. This DCMD will be sent only if
5205  * crash dump feature is supported by the FW.
5206  *
5207  */
5208 int megasas_set_crash_dump_params(struct megasas_instance *instance,
5209         u8 crash_buf_state)
5210 {
5211         int ret = 0;
5212         struct megasas_cmd *cmd;
5213         struct megasas_dcmd_frame *dcmd;
5214
5215         cmd = megasas_get_cmd(instance);
5216
5217         if (!cmd) {
5218                 dev_err(&instance->pdev->dev, "Failed to get a free cmd\n");
5219                 return -ENOMEM;
5220         }
5221
5222
5223         dcmd = &cmd->frame->dcmd;
5224
5225         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5226         dcmd->mbox.b[0] = crash_buf_state;
5227         dcmd->cmd = MFI_CMD_DCMD;
5228         dcmd->cmd_status = MFI_STAT_INVALID_STATUS;
5229         dcmd->sge_count = 1;
5230         dcmd->flags = MFI_FRAME_DIR_NONE;
5231         dcmd->timeout = 0;
5232         dcmd->pad_0 = 0;
5233         dcmd->data_xfer_len = cpu_to_le32(CRASH_DMA_BUF_SIZE);
5234         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_SET_CRASH_DUMP_PARAMS);
5235
5236         megasas_set_dma_settings(instance, dcmd, instance->crash_dump_h,
5237                                  CRASH_DMA_BUF_SIZE);
5238
5239         if ((instance->adapter_type != MFI_SERIES) &&
5240             !instance->mask_interrupts)
5241                 ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
5242         else
5243                 ret = megasas_issue_polled(instance, cmd);
5244
5245         if (ret == DCMD_TIMEOUT) {
5246                 switch (dcmd_timeout_ocr_possible(instance)) {
5247                 case INITIATE_OCR:
5248                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
5249                         megasas_reset_fusion(instance->host,
5250                                         MFI_IO_TIMEOUT_OCR);
5251                         break;
5252                 case KILL_ADAPTER:
5253                         megaraid_sas_kill_hba(instance);
5254                         break;
5255                 case IGNORE_TIMEOUT:
5256                         dev_info(&instance->pdev->dev, "Ignore DCMD timeout: %s %d\n",
5257                                 __func__, __LINE__);
5258                         break;
5259                 }
5260         } else
5261                 megasas_return_cmd(instance, cmd);
5262
5263         return ret;
5264 }
5265
5266 /**
5267  * megasas_issue_init_mfi -     Initializes the FW
5268  * @instance:           Adapter soft state
5269  *
5270  * Issues the INIT MFI cmd
5271  */
5272 static int
5273 megasas_issue_init_mfi(struct megasas_instance *instance)
5274 {
5275         __le32 context;
5276         struct megasas_cmd *cmd;
5277         struct megasas_init_frame *init_frame;
5278         struct megasas_init_queue_info *initq_info;
5279         dma_addr_t init_frame_h;
5280         dma_addr_t initq_info_h;
5281
5282         /*
5283          * Prepare a init frame. Note the init frame points to queue info
5284          * structure. Each frame has SGL allocated after first 64 bytes. For
5285          * this frame - since we don't need any SGL - we use SGL's space as
5286          * queue info structure
5287          *
5288          * We will not get a NULL command below. We just created the pool.
5289          */
5290         cmd = megasas_get_cmd(instance);
5291
5292         init_frame = (struct megasas_init_frame *)cmd->frame;
5293         initq_info = (struct megasas_init_queue_info *)
5294                 ((unsigned long)init_frame + 64);
5295
5296         init_frame_h = cmd->frame_phys_addr;
5297         initq_info_h = init_frame_h + 64;
5298
5299         context = init_frame->context;
5300         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
5301         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
5302         init_frame->context = context;
5303
5304         initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1);
5305         initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h);
5306
5307         initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h);
5308         initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h);
5309
5310         init_frame->cmd = MFI_CMD_INIT;
5311         init_frame->cmd_status = MFI_STAT_INVALID_STATUS;
5312         init_frame->queue_info_new_phys_addr_lo =
5313                 cpu_to_le32(lower_32_bits(initq_info_h));
5314         init_frame->queue_info_new_phys_addr_hi =
5315                 cpu_to_le32(upper_32_bits(initq_info_h));
5316
5317         init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info));
5318
5319         /*
5320          * disable the intr before firing the init frame to FW
5321          */
5322         instance->instancet->disable_intr(instance);
5323
5324         /*
5325          * Issue the init frame in polled mode
5326          */
5327
5328         if (megasas_issue_polled(instance, cmd)) {
5329                 dev_err(&instance->pdev->dev, "Failed to init firmware\n");
5330                 megasas_return_cmd(instance, cmd);
5331                 goto fail_fw_init;
5332         }
5333
5334         megasas_return_cmd(instance, cmd);
5335
5336         return 0;
5337
5338 fail_fw_init:
5339         return -EINVAL;
5340 }
5341
5342 static u32
5343 megasas_init_adapter_mfi(struct megasas_instance *instance)
5344 {
5345         u32 context_sz;
5346         u32 reply_q_sz;
5347
5348         /*
5349          * Get various operational parameters from status register
5350          */
5351         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(instance) & 0x00FFFF;
5352         /*
5353          * Reduce the max supported cmds by 1. This is to ensure that the
5354          * reply_q_sz (1 more than the max cmd that driver may send)
5355          * does not exceed max cmds that the FW can support
5356          */
5357         instance->max_fw_cmds = instance->max_fw_cmds-1;
5358         instance->max_mfi_cmds = instance->max_fw_cmds;
5359         instance->max_num_sge = (instance->instancet->read_fw_status_reg(instance) & 0xFF0000) >>
5360                                         0x10;
5361         /*
5362          * For MFI skinny adapters, MEGASAS_SKINNY_INT_CMDS commands
5363          * are reserved for IOCTL + driver's internal DCMDs.
5364          */
5365         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
5366                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
5367                 instance->max_scsi_cmds = (instance->max_fw_cmds -
5368                         MEGASAS_SKINNY_INT_CMDS);
5369                 sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
5370         } else {
5371                 instance->max_scsi_cmds = (instance->max_fw_cmds -
5372                         MEGASAS_INT_CMDS);
5373                 sema_init(&instance->ioctl_sem, (MEGASAS_MFI_IOCTL_CMDS));
5374         }
5375
5376         instance->cur_can_queue = instance->max_scsi_cmds;
5377         /*
5378          * Create a pool of commands
5379          */
5380         if (megasas_alloc_cmds(instance))
5381                 goto fail_alloc_cmds;
5382
5383         /*
5384          * Allocate memory for reply queue. Length of reply queue should
5385          * be _one_ more than the maximum commands handled by the firmware.
5386          *
5387          * Note: When FW completes commands, it places corresponding contex
5388          * values in this circular reply queue. This circular queue is a fairly
5389          * typical producer-consumer queue. FW is the producer (of completed
5390          * commands) and the driver is the consumer.
5391          */
5392         context_sz = sizeof(u32);
5393         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
5394
5395         instance->reply_queue = dma_alloc_coherent(&instance->pdev->dev,
5396                         reply_q_sz, &instance->reply_queue_h, GFP_KERNEL);
5397
5398         if (!instance->reply_queue) {
5399                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Out of DMA mem for reply queue\n");
5400                 goto fail_reply_queue;
5401         }
5402
5403         if (megasas_issue_init_mfi(instance))
5404                 goto fail_fw_init;
5405
5406         if (megasas_get_ctrl_info(instance)) {
5407                 dev_err(&instance->pdev->dev, "(%d): Could get controller info "
5408                         "Fail from %s %d\n", instance->unique_id,
5409                         __func__, __LINE__);
5410                 goto fail_fw_init;
5411         }
5412
5413         instance->fw_support_ieee = 0;
5414         instance->fw_support_ieee =
5415                 (instance->instancet->read_fw_status_reg(instance) &
5416                 0x04000000);
5417
5418         dev_notice(&instance->pdev->dev, "megasas_init_mfi: fw_support_ieee=%d",
5419                         instance->fw_support_ieee);
5420
5421         if (instance->fw_support_ieee)
5422                 instance->flag_ieee = 1;
5423
5424         return 0;
5425
5426 fail_fw_init:
5427
5428         dma_free_coherent(&instance->pdev->dev, reply_q_sz,
5429                             instance->reply_queue, instance->reply_queue_h);
5430 fail_reply_queue:
5431         megasas_free_cmds(instance);
5432
5433 fail_alloc_cmds:
5434         return 1;
5435 }
5436
5437 static
5438 void megasas_setup_irq_poll(struct megasas_instance *instance)
5439 {
5440         struct megasas_irq_context *irq_ctx;
5441         u32 count, i;
5442
5443         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5444
5445         /* Initialize IRQ poll */
5446         for (i = 0; i < count; i++) {
5447                 irq_ctx = &instance->irq_context[i];
5448                 irq_ctx->os_irq = pci_irq_vector(instance->pdev, i);
5449                 irq_ctx->irq_poll_scheduled = false;
5450                 irq_poll_init(&irq_ctx->irqpoll,
5451                               instance->threshold_reply_count,
5452                               megasas_irqpoll);
5453         }
5454 }
5455
5456 /*
5457  * megasas_setup_irqs_ioapic -          register legacy interrupts.
5458  * @instance:                           Adapter soft state
5459  *
5460  * Do not enable interrupt, only setup ISRs.
5461  *
5462  * Return 0 on success.
5463  */
5464 static int
5465 megasas_setup_irqs_ioapic(struct megasas_instance *instance)
5466 {
5467         struct pci_dev *pdev;
5468
5469         pdev = instance->pdev;
5470         instance->irq_context[0].instance = instance;
5471         instance->irq_context[0].MSIxIndex = 0;
5472         if (request_irq(pci_irq_vector(pdev, 0),
5473                         instance->instancet->service_isr, IRQF_SHARED,
5474                         "megasas", &instance->irq_context[0])) {
5475                 dev_err(&instance->pdev->dev,
5476                                 "Failed to register IRQ from %s %d\n",
5477                                 __func__, __LINE__);
5478                 return -1;
5479         }
5480         return 0;
5481 }
5482
5483 /**
5484  * megasas_setup_irqs_msix -            register MSI-x interrupts.
5485  * @instance:                           Adapter soft state
5486  * @is_probe:                           Driver probe check
5487  *
5488  * Do not enable interrupt, only setup ISRs.
5489  *
5490  * Return 0 on success.
5491  */
5492 static int
5493 megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe)
5494 {
5495         int i, j;
5496         struct pci_dev *pdev;
5497
5498         pdev = instance->pdev;
5499
5500         /* Try MSI-x */
5501         for (i = 0; i < instance->msix_vectors; i++) {
5502                 instance->irq_context[i].instance = instance;
5503                 instance->irq_context[i].MSIxIndex = i;
5504                 if (request_irq(pci_irq_vector(pdev, i),
5505                         instance->instancet->service_isr, 0, "megasas",
5506                         &instance->irq_context[i])) {
5507                         dev_err(&instance->pdev->dev,
5508                                 "Failed to register IRQ for vector %d.\n", i);
5509                         for (j = 0; j < i; j++)
5510                                 free_irq(pci_irq_vector(pdev, j),
5511                                          &instance->irq_context[j]);
5512                         /* Retry irq register for IO_APIC*/
5513                         instance->msix_vectors = 0;
5514                         instance->msix_load_balance = false;
5515                         if (is_probe) {
5516                                 pci_free_irq_vectors(instance->pdev);
5517                                 return megasas_setup_irqs_ioapic(instance);
5518                         } else {
5519                                 return -1;
5520                         }
5521                 }
5522         }
5523
5524         return 0;
5525 }
5526
5527 /*
5528  * megasas_destroy_irqs-                unregister interrupts.
5529  * @instance:                           Adapter soft state
5530  * return:                              void
5531  */
5532 static void
5533 megasas_destroy_irqs(struct megasas_instance *instance) {
5534
5535         int i;
5536         int count;
5537         struct megasas_irq_context *irq_ctx;
5538
5539         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
5540         if (instance->adapter_type != MFI_SERIES) {
5541                 for (i = 0; i < count; i++) {
5542                         irq_ctx = &instance->irq_context[i];
5543                         irq_poll_disable(&irq_ctx->irqpoll);
5544                 }
5545         }
5546
5547         if (instance->msix_vectors)
5548                 for (i = 0; i < instance->msix_vectors; i++) {
5549                         free_irq(pci_irq_vector(instance->pdev, i),
5550                                  &instance->irq_context[i]);
5551                 }
5552         else
5553                 free_irq(pci_irq_vector(instance->pdev, 0),
5554                          &instance->irq_context[0]);
5555 }
5556
5557 /**
5558  * megasas_setup_jbod_map -     setup jbod map for FP seq_number.
5559  * @instance:                           Adapter soft state
5560  * @is_probe:                           Driver probe check
5561  *
5562  * Return 0 on success.
5563  */
5564 void
5565 megasas_setup_jbod_map(struct megasas_instance *instance)
5566 {
5567         int i;
5568         struct fusion_context *fusion = instance->ctrl_context;
5569         u32 pd_seq_map_sz;
5570
5571         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
5572                 (sizeof(struct MR_PD_CFG_SEQ) * (MAX_PHYSICAL_DEVICES - 1));
5573
5574         if (reset_devices || !fusion ||
5575                 !instance->ctrl_info_buf->adapterOperations3.useSeqNumJbodFP) {
5576                 dev_info(&instance->pdev->dev,
5577                         "Jbod map is not supported %s %d\n",
5578                         __func__, __LINE__);
5579                 instance->use_seqnum_jbod_fp = false;
5580                 return;
5581         }
5582
5583         if (fusion->pd_seq_sync[0])
5584                 goto skip_alloc;
5585
5586         for (i = 0; i < JBOD_MAPS_COUNT; i++) {
5587                 fusion->pd_seq_sync[i] = dma_alloc_coherent
5588                         (&instance->pdev->dev, pd_seq_map_sz,
5589                         &fusion->pd_seq_phys[i], GFP_KERNEL);
5590                 if (!fusion->pd_seq_sync[i]) {
5591                         dev_err(&instance->pdev->dev,
5592                                 "Failed to allocate memory from %s %d\n",
5593                                 __func__, __LINE__);
5594                         if (i == 1) {
5595                                 dma_free_coherent(&instance->pdev->dev,
5596                                         pd_seq_map_sz, fusion->pd_seq_sync[0],
5597                                         fusion->pd_seq_phys[0]);
5598                                 fusion->pd_seq_sync[0] = NULL;
5599                         }
5600                         instance->use_seqnum_jbod_fp = false;
5601                         return;
5602                 }
5603         }
5604
5605 skip_alloc:
5606         if (!megasas_sync_pd_seq_num(instance, false) &&
5607                 !megasas_sync_pd_seq_num(instance, true))
5608                 instance->use_seqnum_jbod_fp = true;
5609         else
5610                 instance->use_seqnum_jbod_fp = false;
5611 }
5612
5613 static void megasas_setup_reply_map(struct megasas_instance *instance)
5614 {
5615         const struct cpumask *mask;
5616         unsigned int queue, cpu;
5617
5618         for (queue = 0; queue < instance->msix_vectors; queue++) {
5619                 mask = pci_irq_get_affinity(instance->pdev, queue);
5620                 if (!mask)
5621                         goto fallback;
5622
5623                 for_each_cpu(cpu, mask)
5624                         instance->reply_map[cpu] = queue;
5625         }
5626         return;
5627
5628 fallback:
5629         for_each_possible_cpu(cpu)
5630                 instance->reply_map[cpu] = cpu % instance->msix_vectors;
5631 }
5632
5633 /**
5634  * megasas_get_device_list -    Get the PD and LD device list from FW.
5635  * @instance:                   Adapter soft state
5636  * @return:                     Success or failure
5637  *
5638  * Issue DCMDs to Firmware to get the PD and LD list.
5639  * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
5640  * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
5641  */
5642 static
5643 int megasas_get_device_list(struct megasas_instance *instance)
5644 {
5645         memset(instance->pd_list, 0,
5646                (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
5647         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
5648
5649         if (instance->enable_fw_dev_list) {
5650                 if (megasas_host_device_list_query(instance, true))
5651                         return FAILED;
5652         } else {
5653                 if (megasas_get_pd_list(instance) < 0) {
5654                         dev_err(&instance->pdev->dev, "failed to get PD list\n");
5655                         return FAILED;
5656                 }
5657
5658                 if (megasas_ld_list_query(instance,
5659                                           MR_LD_QUERY_TYPE_EXPOSED_TO_HOST)) {
5660                         dev_err(&instance->pdev->dev, "failed to get LD list\n");
5661                         return FAILED;
5662                 }
5663         }
5664
5665         return SUCCESS;
5666 }
5667 /**
5668  * megasas_init_fw -    Initializes the FW
5669  * @instance:           Adapter soft state
5670  *
5671  * This is the main function for initializing firmware
5672  */
5673
5674 static int megasas_init_fw(struct megasas_instance *instance)
5675 {
5676         u32 max_sectors_1;
5677         u32 max_sectors_2, tmp_sectors, msix_enable;
5678         u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg;
5679         resource_size_t base_addr;
5680         void *base_addr_phys;
5681         struct megasas_ctrl_info *ctrl_info = NULL;
5682         unsigned long bar_list;
5683         int i, j, loop;
5684         struct IOV_111 *iovPtr;
5685         struct fusion_context *fusion;
5686
5687         fusion = instance->ctrl_context;
5688
5689         /* Find first memory bar */
5690         bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
5691         instance->bar = find_first_bit(&bar_list, BITS_PER_LONG);
5692         if (pci_request_selected_regions(instance->pdev, 1<<instance->bar,
5693                                          "megasas: LSI")) {
5694                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "IO memory region busy!\n");
5695                 return -EBUSY;
5696         }
5697
5698         base_addr = pci_resource_start(instance->pdev, instance->bar);
5699         instance->reg_set = ioremap_nocache(base_addr, 8192);
5700
5701         if (!instance->reg_set) {
5702                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to map IO mem\n");
5703                 goto fail_ioremap;
5704         }
5705
5706         base_addr_phys = &base_addr;
5707         dev_printk(KERN_DEBUG, &instance->pdev->dev,
5708                    "BAR:0x%lx  BAR's base_addr(phys):%pa  mapped virt_addr:0x%p\n",
5709                    instance->bar, base_addr_phys, instance->reg_set);
5710
5711         if (instance->adapter_type != MFI_SERIES)
5712                 instance->instancet = &megasas_instance_template_fusion;
5713         else {
5714                 switch (instance->pdev->device) {
5715                 case PCI_DEVICE_ID_LSI_SAS1078R:
5716                 case PCI_DEVICE_ID_LSI_SAS1078DE:
5717                         instance->instancet = &megasas_instance_template_ppc;
5718                         break;
5719                 case PCI_DEVICE_ID_LSI_SAS1078GEN2:
5720                 case PCI_DEVICE_ID_LSI_SAS0079GEN2:
5721                         instance->instancet = &megasas_instance_template_gen2;
5722                         break;
5723                 case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
5724                 case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
5725                         instance->instancet = &megasas_instance_template_skinny;
5726                         break;
5727                 case PCI_DEVICE_ID_LSI_SAS1064R:
5728                 case PCI_DEVICE_ID_DELL_PERC5:
5729                 default:
5730                         instance->instancet = &megasas_instance_template_xscale;
5731                         instance->pd_list_not_supported = 1;
5732                         break;
5733                 }
5734         }
5735
5736         if (megasas_transition_to_ready(instance, 0)) {
5737                 dev_info(&instance->pdev->dev,
5738                          "Failed to transition controller to ready from %s!\n",
5739                          __func__);
5740                 if (instance->adapter_type != MFI_SERIES) {
5741                         status_reg = instance->instancet->read_fw_status_reg(
5742                                         instance);
5743                         if (status_reg & MFI_RESET_ADAPTER) {
5744                                 if (megasas_adp_reset_wait_for_ready
5745                                         (instance, true, 0) == FAILED)
5746                                         goto fail_ready_state;
5747                         } else {
5748                                 goto fail_ready_state;
5749                         }
5750                 } else {
5751                         atomic_set(&instance->fw_reset_no_pci_access, 1);
5752                         instance->instancet->adp_reset
5753                                 (instance, instance->reg_set);
5754                         atomic_set(&instance->fw_reset_no_pci_access, 0);
5755
5756                         /*waiting for about 30 second before retry*/
5757                         ssleep(30);
5758
5759                         if (megasas_transition_to_ready(instance, 0))
5760                                 goto fail_ready_state;
5761                 }
5762
5763                 dev_info(&instance->pdev->dev,
5764                          "FW restarted successfully from %s!\n",
5765                          __func__);
5766         }
5767
5768         megasas_init_ctrl_params(instance);
5769
5770         if (megasas_set_dma_mask(instance))
5771                 goto fail_ready_state;
5772
5773         if (megasas_alloc_ctrl_mem(instance))
5774                 goto fail_alloc_dma_buf;
5775
5776         if (megasas_alloc_ctrl_dma_buffers(instance))
5777                 goto fail_alloc_dma_buf;
5778
5779         fusion = instance->ctrl_context;
5780
5781         if (instance->adapter_type >= VENTURA_SERIES) {
5782                 scratch_pad_2 =
5783                         megasas_readl(instance,
5784                                       &instance->reg_set->outbound_scratch_pad_2);
5785                 instance->max_raid_mapsize = ((scratch_pad_2 >>
5786                         MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) &
5787                         MR_MAX_RAID_MAP_SIZE_MASK);
5788         }
5789
5790         /* Check if MSI-X is supported while in ready state */
5791         msix_enable = (instance->instancet->read_fw_status_reg(instance) &
5792                        0x4000000) >> 0x1a;
5793         if (msix_enable && !msix_disable) {
5794                 int irq_flags = PCI_IRQ_MSIX;
5795
5796                 scratch_pad_1 = megasas_readl
5797                         (instance, &instance->reg_set->outbound_scratch_pad_1);
5798                 /* Check max MSI-X vectors */
5799                 if (fusion) {
5800                         if (instance->adapter_type == THUNDERBOLT_SERIES) {
5801                                 /* Thunderbolt Series*/
5802                                 instance->msix_vectors = (scratch_pad_1
5803                                         & MR_MAX_REPLY_QUEUES_OFFSET) + 1;
5804                         } else {
5805                                 instance->msix_vectors = ((scratch_pad_1
5806                                         & MR_MAX_REPLY_QUEUES_EXT_OFFSET)
5807                                         >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1;
5808
5809                                 /*
5810                                  * For Invader series, > 8 MSI-x vectors
5811                                  * supported by FW/HW implies combined
5812                                  * reply queue mode is enabled.
5813                                  * For Ventura series, > 16 MSI-x vectors
5814                                  * supported by FW/HW implies combined
5815                                  * reply queue mode is enabled.
5816                                  */
5817                                 switch (instance->adapter_type) {
5818                                 case INVADER_SERIES:
5819                                         if (instance->msix_vectors > 8)
5820                                                 instance->msix_combined = true;
5821                                         break;
5822                                 case AERO_SERIES:
5823                                 case VENTURA_SERIES:
5824                                         if (instance->msix_vectors > 16)
5825                                                 instance->msix_combined = true;
5826                                         break;
5827                                 }
5828
5829                                 if (rdpq_enable)
5830                                         instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ?
5831                                                                 1 : 0;
5832
5833                                 if (!instance->msix_combined) {
5834                                         instance->msix_load_balance = true;
5835                                         instance->smp_affinity_enable = false;
5836                                 }
5837
5838                                 /* Save 1-15 reply post index address to local memory
5839                                  * Index 0 is already saved from reg offset
5840                                  * MPI2_REPLY_POST_HOST_INDEX_OFFSET
5841                                  */
5842                                 for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) {
5843                                         instance->reply_post_host_index_addr[loop] =
5844                                                 (u32 __iomem *)
5845                                                 ((u8 __iomem *)instance->reg_set +
5846                                                 MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET
5847                                                 + (loop * 0x10));
5848                                 }
5849                         }
5850
5851                         dev_info(&instance->pdev->dev,
5852                                  "firmware supports msix\t: (%d)",
5853                                  instance->msix_vectors);
5854                         if (msix_vectors)
5855                                 instance->msix_vectors = min(msix_vectors,
5856                                         instance->msix_vectors);
5857                 } else /* MFI adapters */
5858                         instance->msix_vectors = 1;
5859
5860                 /* Don't bother allocating more MSI-X vectors than cpus */
5861                 instance->msix_vectors = min(instance->msix_vectors,
5862                                              (unsigned int)num_online_cpus());
5863                 if (instance->smp_affinity_enable)
5864                         irq_flags |= PCI_IRQ_AFFINITY;
5865                 i = pci_alloc_irq_vectors(instance->pdev, 1,
5866                                           instance->msix_vectors, irq_flags);
5867                 if (i > 0) {
5868                         instance->msix_vectors = i;
5869                 } else {
5870                         instance->msix_vectors = 0;
5871                         instance->msix_load_balance = false;
5872                 }
5873         }
5874         /*
5875          * MSI-X host index 0 is common for all adapter.
5876          * It is used for all MPT based Adapters.
5877          */
5878         if (instance->msix_combined) {
5879                 instance->reply_post_host_index_addr[0] =
5880                                 (u32 *)((u8 *)instance->reg_set +
5881                                 MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET);
5882         } else {
5883                 instance->reply_post_host_index_addr[0] =
5884                         (u32 *)((u8 *)instance->reg_set +
5885                         MPI2_REPLY_POST_HOST_INDEX_OFFSET);
5886         }
5887
5888         if (!instance->msix_vectors) {
5889                 i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_LEGACY);
5890                 if (i < 0)
5891                         goto fail_init_adapter;
5892         }
5893
5894         megasas_setup_reply_map(instance);
5895
5896         dev_info(&instance->pdev->dev,
5897                 "current msix/online cpus\t: (%d/%d)\n",
5898                 instance->msix_vectors, (unsigned int)num_online_cpus());
5899         dev_info(&instance->pdev->dev,
5900                 "RDPQ mode\t: (%s)\n", instance->is_rdpq ? "enabled" : "disabled");
5901
5902         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
5903                 (unsigned long)instance);
5904
5905         /*
5906          * Below are default value for legacy Firmware.
5907          * non-fusion based controllers
5908          */
5909         instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES;
5910         instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES;
5911         /* Get operational params, sge flags, send init cmd to controller */
5912         if (instance->instancet->init_adapter(instance))
5913                 goto fail_init_adapter;
5914
5915         if (instance->adapter_type >= VENTURA_SERIES) {
5916                 scratch_pad_3 =
5917                         megasas_readl(instance,
5918                                       &instance->reg_set->outbound_scratch_pad_3);
5919                 if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >=
5920                         MR_DEFAULT_NVME_PAGE_SHIFT)
5921                         instance->nvme_page_size =
5922                                 (1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK));
5923
5924                 dev_info(&instance->pdev->dev,
5925                          "NVME page size\t: (%d)\n", instance->nvme_page_size);
5926         }
5927
5928         if (instance->msix_vectors ?
5929                 megasas_setup_irqs_msix(instance, 1) :
5930                 megasas_setup_irqs_ioapic(instance))
5931                 goto fail_init_adapter;
5932
5933         if (instance->adapter_type != MFI_SERIES)
5934                 megasas_setup_irq_poll(instance);
5935
5936         instance->instancet->enable_intr(instance);
5937
5938         dev_info(&instance->pdev->dev, "INIT adapter done\n");
5939
5940         megasas_setup_jbod_map(instance);
5941
5942         if (megasas_get_device_list(instance) != SUCCESS) {
5943                 dev_err(&instance->pdev->dev,
5944                         "%s: megasas_get_device_list failed\n",
5945                         __func__);
5946                 goto fail_get_ld_pd_list;
5947         }
5948
5949         /* stream detection initialization */
5950         if (instance->adapter_type >= VENTURA_SERIES) {
5951                 fusion->stream_detect_by_ld =
5952                         kcalloc(MAX_LOGICAL_DRIVES_EXT,
5953                                 sizeof(struct LD_STREAM_DETECT *),
5954                                 GFP_KERNEL);
5955                 if (!fusion->stream_detect_by_ld) {
5956                         dev_err(&instance->pdev->dev,
5957                                 "unable to allocate stream detection for pool of LDs\n");
5958                         goto fail_get_ld_pd_list;
5959                 }
5960                 for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) {
5961                         fusion->stream_detect_by_ld[i] =
5962                                 kzalloc(sizeof(struct LD_STREAM_DETECT),
5963                                 GFP_KERNEL);
5964                         if (!fusion->stream_detect_by_ld[i]) {
5965                                 dev_err(&instance->pdev->dev,
5966                                         "unable to allocate stream detect by LD\n ");
5967                                 for (j = 0; j < i; ++j)
5968                                         kfree(fusion->stream_detect_by_ld[j]);
5969                                 kfree(fusion->stream_detect_by_ld);
5970                                 fusion->stream_detect_by_ld = NULL;
5971                                 goto fail_get_ld_pd_list;
5972                         }
5973                         fusion->stream_detect_by_ld[i]->mru_bit_map
5974                                 = MR_STREAM_BITMAP;
5975                 }
5976         }
5977
5978         /*
5979          * Compute the max allowed sectors per IO: The controller info has two
5980          * limits on max sectors. Driver should use the minimum of these two.
5981          *
5982          * 1 << stripe_sz_ops.min = max sectors per strip
5983          *
5984          * Note that older firmwares ( < FW ver 30) didn't report information
5985          * to calculate max_sectors_1. So the number ended up as zero always.
5986          */
5987         tmp_sectors = 0;
5988         ctrl_info = instance->ctrl_info_buf;
5989
5990         max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
5991                 le16_to_cpu(ctrl_info->max_strips_per_io);
5992         max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size);
5993
5994         tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2);
5995
5996         instance->peerIsPresent = ctrl_info->cluster.peerIsPresent;
5997         instance->passive = ctrl_info->cluster.passive;
5998         memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId));
5999         instance->UnevenSpanSupport =
6000                 ctrl_info->adapterOperations2.supportUnevenSpans;
6001         if (instance->UnevenSpanSupport) {
6002                 struct fusion_context *fusion = instance->ctrl_context;
6003                 if (MR_ValidateMapInfo(instance, instance->map_id))
6004                         fusion->fast_path_io = 1;
6005                 else
6006                         fusion->fast_path_io = 0;
6007
6008         }
6009         if (ctrl_info->host_interface.SRIOV) {
6010                 instance->requestorId = ctrl_info->iov.requestorId;
6011                 if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) {
6012                         if (!ctrl_info->adapterOperations2.activePassive)
6013                             instance->PlasmaFW111 = 1;
6014
6015                         dev_info(&instance->pdev->dev, "SR-IOV: firmware type: %s\n",
6016                             instance->PlasmaFW111 ? "1.11" : "new");
6017
6018                         if (instance->PlasmaFW111) {
6019                             iovPtr = (struct IOV_111 *)
6020                                 ((unsigned char *)ctrl_info + IOV_111_OFFSET);
6021                             instance->requestorId = iovPtr->requestorId;
6022                         }
6023                 }
6024                 dev_info(&instance->pdev->dev, "SRIOV: VF requestorId %d\n",
6025                         instance->requestorId);
6026         }
6027
6028         instance->crash_dump_fw_support =
6029                 ctrl_info->adapterOperations3.supportCrashDump;
6030         instance->crash_dump_drv_support =
6031                 (instance->crash_dump_fw_support &&
6032                 instance->crash_dump_buf);
6033         if (instance->crash_dump_drv_support)
6034                 megasas_set_crash_dump_params(instance,
6035                         MR_CRASH_BUF_TURN_OFF);
6036
6037         else {
6038                 if (instance->crash_dump_buf)
6039                         dma_free_coherent(&instance->pdev->dev,
6040                                 CRASH_DMA_BUF_SIZE,
6041                                 instance->crash_dump_buf,
6042                                 instance->crash_dump_h);
6043                 instance->crash_dump_buf = NULL;
6044         }
6045
6046         if (instance->snapdump_wait_time) {
6047                 megasas_get_snapdump_properties(instance);
6048                 dev_info(&instance->pdev->dev, "Snap dump wait time\t: %d\n",
6049                          instance->snapdump_wait_time);
6050         }
6051
6052         dev_info(&instance->pdev->dev,
6053                 "pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n",
6054                 le16_to_cpu(ctrl_info->pci.vendor_id),
6055                 le16_to_cpu(ctrl_info->pci.device_id),
6056                 le16_to_cpu(ctrl_info->pci.sub_vendor_id),
6057                 le16_to_cpu(ctrl_info->pci.sub_device_id));
6058         dev_info(&instance->pdev->dev, "unevenspan support      : %s\n",
6059                 instance->UnevenSpanSupport ? "yes" : "no");
6060         dev_info(&instance->pdev->dev, "firmware crash dump     : %s\n",
6061                 instance->crash_dump_drv_support ? "yes" : "no");
6062         dev_info(&instance->pdev->dev, "jbod sync map           : %s\n",
6063                 instance->use_seqnum_jbod_fp ? "yes" : "no");
6064
6065         instance->max_sectors_per_req = instance->max_num_sge *
6066                                                 SGE_BUFFER_SIZE / 512;
6067         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
6068                 instance->max_sectors_per_req = tmp_sectors;
6069
6070         /* Check for valid throttlequeuedepth module parameter */
6071         if (throttlequeuedepth &&
6072                         throttlequeuedepth <= instance->max_scsi_cmds)
6073                 instance->throttlequeuedepth = throttlequeuedepth;
6074         else
6075                 instance->throttlequeuedepth =
6076                                 MEGASAS_THROTTLE_QUEUE_DEPTH;
6077
6078         if ((resetwaittime < 1) ||
6079             (resetwaittime > MEGASAS_RESET_WAIT_TIME))
6080                 resetwaittime = MEGASAS_RESET_WAIT_TIME;
6081
6082         if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT))
6083                 scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT;
6084
6085         /* Launch SR-IOV heartbeat timer */
6086         if (instance->requestorId) {
6087                 if (!megasas_sriov_start_heartbeat(instance, 1)) {
6088                         megasas_start_timer(instance);
6089                 } else {
6090                         instance->skip_heartbeat_timer_del = 1;
6091                         goto fail_get_ld_pd_list;
6092                 }
6093         }
6094
6095         /*
6096          * Create and start watchdog thread which will monitor
6097          * controller state every 1 sec and trigger OCR when
6098          * it enters fault state
6099          */
6100         if (instance->adapter_type != MFI_SERIES)
6101                 if (megasas_fusion_start_watchdog(instance) != SUCCESS)
6102                         goto fail_start_watchdog;
6103
6104         return 0;
6105
6106 fail_start_watchdog:
6107         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
6108                 del_timer_sync(&instance->sriov_heartbeat_timer);
6109 fail_get_ld_pd_list:
6110         instance->instancet->disable_intr(instance);
6111         megasas_destroy_irqs(instance);
6112 fail_init_adapter:
6113         if (instance->msix_vectors)
6114                 pci_free_irq_vectors(instance->pdev);
6115         instance->msix_vectors = 0;
6116 fail_alloc_dma_buf:
6117         megasas_free_ctrl_dma_buffers(instance);
6118         megasas_free_ctrl_mem(instance);
6119 fail_ready_state:
6120         iounmap(instance->reg_set);
6121
6122 fail_ioremap:
6123         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6124
6125         dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6126                 __func__, __LINE__);
6127         return -EINVAL;
6128 }
6129
6130 /**
6131  * megasas_release_mfi -        Reverses the FW initialization
6132  * @instance:                   Adapter soft state
6133  */
6134 static void megasas_release_mfi(struct megasas_instance *instance)
6135 {
6136         u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
6137
6138         if (instance->reply_queue)
6139                 dma_free_coherent(&instance->pdev->dev, reply_q_sz,
6140                             instance->reply_queue, instance->reply_queue_h);
6141
6142         megasas_free_cmds(instance);
6143
6144         iounmap(instance->reg_set);
6145
6146         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
6147 }
6148
6149 /**
6150  * megasas_get_seq_num -        Gets latest event sequence numbers
6151  * @instance:                   Adapter soft state
6152  * @eli:                        FW event log sequence numbers information
6153  *
6154  * FW maintains a log of all events in a non-volatile area. Upper layers would
6155  * usually find out the latest sequence number of the events, the seq number at
6156  * the boot etc. They would "read" all the events below the latest seq number
6157  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
6158  * number), they would subsribe to AEN (asynchronous event notification) and
6159  * wait for the events to happen.
6160  */
6161 static int
6162 megasas_get_seq_num(struct megasas_instance *instance,
6163                     struct megasas_evt_log_info *eli)
6164 {
6165         struct megasas_cmd *cmd;
6166         struct megasas_dcmd_frame *dcmd;
6167         struct megasas_evt_log_info *el_info;
6168         dma_addr_t el_info_h = 0;
6169         int ret;
6170
6171         cmd = megasas_get_cmd(instance);
6172
6173         if (!cmd) {
6174                 return -ENOMEM;
6175         }
6176
6177         dcmd = &cmd->frame->dcmd;
6178         el_info = dma_alloc_coherent(&instance->pdev->dev,
6179                                      sizeof(struct megasas_evt_log_info),
6180                                      &el_info_h, GFP_KERNEL);
6181         if (!el_info) {
6182                 megasas_return_cmd(instance, cmd);
6183                 return -ENOMEM;
6184         }
6185
6186         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6187
6188         dcmd->cmd = MFI_CMD_DCMD;
6189         dcmd->cmd_status = 0x0;
6190         dcmd->sge_count = 1;
6191         dcmd->flags = MFI_FRAME_DIR_READ;
6192         dcmd->timeout = 0;
6193         dcmd->pad_0 = 0;
6194         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info));
6195         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO);
6196
6197         megasas_set_dma_settings(instance, dcmd, el_info_h,
6198                                  sizeof(struct megasas_evt_log_info));
6199
6200         ret = megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS);
6201         if (ret != DCMD_SUCCESS) {
6202                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
6203                         __func__, __LINE__);
6204                 goto dcmd_failed;
6205         }
6206
6207         /*
6208          * Copy the data back into callers buffer
6209          */
6210         eli->newest_seq_num = el_info->newest_seq_num;
6211         eli->oldest_seq_num = el_info->oldest_seq_num;
6212         eli->clear_seq_num = el_info->clear_seq_num;
6213         eli->shutdown_seq_num = el_info->shutdown_seq_num;
6214         eli->boot_seq_num = el_info->boot_seq_num;
6215
6216 dcmd_failed:
6217         dma_free_coherent(&instance->pdev->dev,
6218                         sizeof(struct megasas_evt_log_info),
6219                         el_info, el_info_h);
6220
6221         megasas_return_cmd(instance, cmd);
6222
6223         return ret;
6224 }
6225
6226 /**
6227  * megasas_register_aen -       Registers for asynchronous event notification
6228  * @instance:                   Adapter soft state
6229  * @seq_num:                    The starting sequence number
6230  * @class_locale:               Class of the event
6231  *
6232  * This function subscribes for AEN for events beyond the @seq_num. It requests
6233  * to be notified if and only if the event is of type @class_locale
6234  */
6235 static int
6236 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
6237                      u32 class_locale_word)
6238 {
6239         int ret_val;
6240         struct megasas_cmd *cmd;
6241         struct megasas_dcmd_frame *dcmd;
6242         union megasas_evt_class_locale curr_aen;
6243         union megasas_evt_class_locale prev_aen;
6244
6245         /*
6246          * If there an AEN pending already (aen_cmd), check if the
6247          * class_locale of that pending AEN is inclusive of the new
6248          * AEN request we currently have. If it is, then we don't have
6249          * to do anything. In other words, whichever events the current
6250          * AEN request is subscribing to, have already been subscribed
6251          * to.
6252          *
6253          * If the old_cmd is _not_ inclusive, then we have to abort
6254          * that command, form a class_locale that is superset of both
6255          * old and current and re-issue to the FW
6256          */
6257
6258         curr_aen.word = class_locale_word;
6259
6260         if (instance->aen_cmd) {
6261
6262                 prev_aen.word =
6263                         le32_to_cpu(instance->aen_cmd->frame->dcmd.mbox.w[1]);
6264
6265                 if ((curr_aen.members.class < MFI_EVT_CLASS_DEBUG) ||
6266                     (curr_aen.members.class > MFI_EVT_CLASS_DEAD)) {
6267                         dev_info(&instance->pdev->dev,
6268                                  "%s %d out of range class %d send by application\n",
6269                                  __func__, __LINE__, curr_aen.members.class);
6270                         return 0;
6271                 }
6272
6273                 /*
6274                  * A class whose enum value is smaller is inclusive of all
6275                  * higher values. If a PROGRESS (= -1) was previously
6276                  * registered, then a new registration requests for higher
6277                  * classes need not be sent to FW. They are automatically
6278                  * included.
6279                  *
6280                  * Locale numbers don't have such hierarchy. They are bitmap
6281                  * values
6282                  */
6283                 if ((prev_aen.members.class <= curr_aen.members.class) &&
6284                     !((prev_aen.members.locale & curr_aen.members.locale) ^
6285                       curr_aen.members.locale)) {
6286                         /*
6287                          * Previously issued event registration includes
6288                          * current request. Nothing to do.
6289                          */
6290                         return 0;
6291                 } else {
6292                         curr_aen.members.locale |= prev_aen.members.locale;
6293
6294                         if (prev_aen.members.class < curr_aen.members.class)
6295                                 curr_aen.members.class = prev_aen.members.class;
6296
6297                         instance->aen_cmd->abort_aen = 1;
6298                         ret_val = megasas_issue_blocked_abort_cmd(instance,
6299                                                                   instance->
6300                                                                   aen_cmd, 30);
6301
6302                         if (ret_val) {
6303                                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to abort "
6304                                        "previous AEN command\n");
6305                                 return ret_val;
6306                         }
6307                 }
6308         }
6309
6310         cmd = megasas_get_cmd(instance);
6311
6312         if (!cmd)
6313                 return -ENOMEM;
6314
6315         dcmd = &cmd->frame->dcmd;
6316
6317         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
6318
6319         /*
6320          * Prepare DCMD for aen registration
6321          */
6322         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6323
6324         dcmd->cmd = MFI_CMD_DCMD;
6325         dcmd->cmd_status = 0x0;
6326         dcmd->sge_count = 1;
6327         dcmd->flags = MFI_FRAME_DIR_READ;
6328         dcmd->timeout = 0;
6329         dcmd->pad_0 = 0;
6330         dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail));
6331         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT);
6332         dcmd->mbox.w[0] = cpu_to_le32(seq_num);
6333         instance->last_seq_num = seq_num;
6334         dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word);
6335
6336         megasas_set_dma_settings(instance, dcmd, instance->evt_detail_h,
6337                                  sizeof(struct megasas_evt_detail));
6338
6339         if (instance->aen_cmd != NULL) {
6340                 megasas_return_cmd(instance, cmd);
6341                 return 0;
6342         }
6343
6344         /*
6345          * Store reference to the cmd used to register for AEN. When an
6346          * application wants us to register for AEN, we have to abort this
6347          * cmd and re-register with a new EVENT LOCALE supplied by that app
6348          */
6349         instance->aen_cmd = cmd;
6350
6351         /*
6352          * Issue the aen registration frame
6353          */
6354         instance->instancet->issue_dcmd(instance, cmd);
6355
6356         return 0;
6357 }
6358
6359 /* megasas_get_target_prop - Send DCMD with below details to firmware.
6360  *
6361  * This DCMD will fetch few properties of LD/system PD defined
6362  * in MR_TARGET_DEV_PROPERTIES. eg. Queue Depth, MDTS value.
6363  *
6364  * DCMD send by drivers whenever new target is added to the OS.
6365  *
6366  * dcmd.opcode         - MR_DCMD_DEV_GET_TARGET_PROP
6367  * dcmd.mbox.b[0]      - DCMD is to be fired for LD or system PD.
6368  *                       0 = system PD, 1 = LD.
6369  * dcmd.mbox.s[1]      - TargetID for LD/system PD.
6370  * dcmd.sge IN         - Pointer to return MR_TARGET_DEV_PROPERTIES.
6371  *
6372  * @instance:           Adapter soft state
6373  * @sdev:               OS provided scsi device
6374  *
6375  * Returns 0 on success non-zero on failure.
6376  */
6377 int
6378 megasas_get_target_prop(struct megasas_instance *instance,
6379                         struct scsi_device *sdev)
6380 {
6381         int ret;
6382         struct megasas_cmd *cmd;
6383         struct megasas_dcmd_frame *dcmd;
6384         u16 targetId = (sdev->channel % 2) + sdev->id;
6385
6386         cmd = megasas_get_cmd(instance);
6387
6388         if (!cmd) {
6389                 dev_err(&instance->pdev->dev,
6390                         "Failed to get cmd %s\n", __func__);
6391                 return -ENOMEM;
6392         }
6393
6394         dcmd = &cmd->frame->dcmd;
6395
6396         memset(instance->tgt_prop, 0, sizeof(*instance->tgt_prop));
6397         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
6398         dcmd->mbox.b[0] = MEGASAS_IS_LOGICAL(sdev);
6399
6400         dcmd->mbox.s[1] = cpu_to_le16(targetId);
6401         dcmd->cmd = MFI_CMD_DCMD;
6402         dcmd->cmd_status = 0xFF;
6403         dcmd->sge_count = 1;
6404         dcmd->flags = MFI_FRAME_DIR_READ;
6405         dcmd->timeout = 0;
6406         dcmd->pad_0 = 0;
6407         dcmd->data_xfer_len =
6408                 cpu_to_le32(sizeof(struct MR_TARGET_PROPERTIES));
6409         dcmd->opcode = cpu_to_le32(MR_DCMD_DRV_GET_TARGET_PROP);
6410
6411         megasas_set_dma_settings(instance, dcmd, instance->tgt_prop_h,
6412                                  sizeof(struct MR_TARGET_PROPERTIES));
6413
6414         if ((instance->adapter_type != MFI_SERIES) &&
6415             !instance->mask_interrupts)
6416                 ret = megasas_issue_blocked_cmd(instance,
6417                                                 cmd, MFI_IO_TIMEOUT_SECS);
6418         else
6419                 ret = megasas_issue_polled(instance, cmd);
6420
6421         switch (ret) {
6422         case DCMD_TIMEOUT:
6423                 switch (dcmd_timeout_ocr_possible(instance)) {
6424                 case INITIATE_OCR:
6425                         cmd->flags |= DRV_DCMD_SKIP_REFIRE;
6426                         megasas_reset_fusion(instance->host,
6427                                              MFI_IO_TIMEOUT_OCR);
6428                         break;
6429                 case KILL_ADAPTER:
6430                         megaraid_sas_kill_hba(instance);
6431                         break;
6432                 case IGNORE_TIMEOUT:
6433                         dev_info(&instance->pdev->dev,
6434                                  "Ignore DCMD timeout: %s %d\n",
6435                                  __func__, __LINE__);
6436                         break;
6437                 }
6438                 break;
6439
6440         default:
6441                 megasas_return_cmd(instance, cmd);
6442         }
6443         if (ret != DCMD_SUCCESS)
6444                 dev_err(&instance->pdev->dev,
6445                         "return from %s %d return value %d\n",
6446                         __func__, __LINE__, ret);
6447
6448         return ret;
6449 }
6450
6451 /**
6452  * megasas_start_aen -  Subscribes to AEN during driver load time
6453  * @instance:           Adapter soft state
6454  */
6455 static int megasas_start_aen(struct megasas_instance *instance)
6456 {
6457         struct megasas_evt_log_info eli;
6458         union megasas_evt_class_locale class_locale;
6459
6460         /*
6461          * Get the latest sequence number from FW
6462          */
6463         memset(&eli, 0, sizeof(eli));
6464
6465         if (megasas_get_seq_num(instance, &eli))
6466                 return -1;
6467
6468         /*
6469          * Register AEN with FW for latest sequence number plus 1
6470          */
6471         class_locale.members.reserved = 0;
6472         class_locale.members.locale = MR_EVT_LOCALE_ALL;
6473         class_locale.members.class = MR_EVT_CLASS_DEBUG;
6474
6475         return megasas_register_aen(instance,
6476                         le32_to_cpu(eli.newest_seq_num) + 1,
6477                         class_locale.word);
6478 }
6479
6480 /**
6481  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
6482  * @instance:           Adapter soft state
6483  */
6484 static int megasas_io_attach(struct megasas_instance *instance)
6485 {
6486         struct Scsi_Host *host = instance->host;
6487
6488         /*
6489          * Export parameters required by SCSI mid-layer
6490          */
6491         host->unique_id = instance->unique_id;
6492         host->can_queue = instance->max_scsi_cmds;
6493         host->this_id = instance->init_id;
6494         host->sg_tablesize = instance->max_num_sge;
6495
6496         if (instance->fw_support_ieee)
6497                 instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
6498
6499         /*
6500          * Check if the module parameter value for max_sectors can be used
6501          */
6502         if (max_sectors && max_sectors < instance->max_sectors_per_req)
6503                 instance->max_sectors_per_req = max_sectors;
6504         else {
6505                 if (max_sectors) {
6506                         if (((instance->pdev->device ==
6507                                 PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
6508                                 (instance->pdev->device ==
6509                                 PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
6510                                 (max_sectors <= MEGASAS_MAX_SECTORS)) {
6511                                 instance->max_sectors_per_req = max_sectors;
6512                         } else {
6513                         dev_info(&instance->pdev->dev, "max_sectors should be > 0"
6514                                 "and <= %d (or < 1MB for GEN2 controller)\n",
6515                                 instance->max_sectors_per_req);
6516                         }
6517                 }
6518         }
6519
6520         host->max_sectors = instance->max_sectors_per_req;
6521         host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
6522         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
6523         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
6524         host->max_lun = MEGASAS_MAX_LUN;
6525         host->max_cmd_len = 16;
6526
6527         /*
6528          * Notify the mid-layer about the new controller
6529          */
6530         if (scsi_add_host(host, &instance->pdev->dev)) {
6531                 dev_err(&instance->pdev->dev,
6532                         "Failed to add host from %s %d\n",
6533                         __func__, __LINE__);
6534                 return -ENODEV;
6535         }
6536
6537         return 0;
6538 }
6539
6540 /**
6541  * megasas_set_dma_mask -       Set DMA mask for supported controllers
6542  *
6543  * @instance:           Adapter soft state
6544  * Description:
6545  *
6546  * For Ventura, driver/FW will operate in 63bit DMA addresses.
6547  *
6548  * For invader-
6549  *      By default, driver/FW will operate in 32bit DMA addresses
6550  *      for consistent DMA mapping but if 32 bit consistent
6551  *      DMA mask fails, driver will try with 63 bit consistent
6552  *      mask provided FW is true 63bit DMA capable
6553  *
6554  * For older controllers(Thunderbolt and MFI based adapters)-
6555  *      driver/FW will operate in 32 bit consistent DMA addresses.
6556  */
6557 static int
6558 megasas_set_dma_mask(struct megasas_instance *instance)
6559 {
6560         u64 consistent_mask;
6561         struct pci_dev *pdev;
6562         u32 scratch_pad_1;
6563
6564         pdev = instance->pdev;
6565         consistent_mask = (instance->adapter_type >= VENTURA_SERIES) ?
6566                                 DMA_BIT_MASK(63) : DMA_BIT_MASK(32);
6567
6568         if (IS_DMA64) {
6569                 if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(63)) &&
6570                     dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
6571                         goto fail_set_dma_mask;
6572
6573                 if ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) &&
6574                     (dma_set_coherent_mask(&pdev->dev, consistent_mask) &&
6575                      dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))) {
6576                         /*
6577                          * If 32 bit DMA mask fails, then try for 64 bit mask
6578                          * for FW capable of handling 64 bit DMA.
6579                          */
6580                         scratch_pad_1 = megasas_readl
6581                                 (instance, &instance->reg_set->outbound_scratch_pad_1);
6582
6583                         if (!(scratch_pad_1 & MR_CAN_HANDLE_64_BIT_DMA_OFFSET))
6584                                 goto fail_set_dma_mask;
6585                         else if (dma_set_mask_and_coherent(&pdev->dev,
6586                                                            DMA_BIT_MASK(63)))
6587                                 goto fail_set_dma_mask;
6588                 }
6589         } else if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
6590                 goto fail_set_dma_mask;
6591
6592         if (pdev->dev.coherent_dma_mask == DMA_BIT_MASK(32))
6593                 instance->consistent_mask_64bit = false;
6594         else
6595                 instance->consistent_mask_64bit = true;
6596
6597         dev_info(&pdev->dev, "%s bit DMA mask and %s bit consistent mask\n",
6598                  ((*pdev->dev.dma_mask == DMA_BIT_MASK(63)) ? "63" : "32"),
6599                  (instance->consistent_mask_64bit ? "63" : "32"));
6600
6601         return 0;
6602
6603 fail_set_dma_mask:
6604         dev_err(&pdev->dev, "Failed to set DMA mask\n");
6605         return -1;
6606
6607 }
6608
6609 /*
6610  * megasas_set_adapter_type -   Set adapter type.
6611  *                              Supported controllers can be divided in
6612  *                              different categories-
6613  *                                      enum MR_ADAPTER_TYPE {
6614  *                                              MFI_SERIES = 1,
6615  *                                              THUNDERBOLT_SERIES = 2,
6616  *                                              INVADER_SERIES = 3,
6617  *                                              VENTURA_SERIES = 4,
6618  *                                              AERO_SERIES = 5,
6619  *                                      };
6620  * @instance:                   Adapter soft state
6621  * return:                      void
6622  */
6623 static inline void megasas_set_adapter_type(struct megasas_instance *instance)
6624 {
6625         if ((instance->pdev->vendor == PCI_VENDOR_ID_DELL) &&
6626             (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5)) {
6627                 instance->adapter_type = MFI_SERIES;
6628         } else {
6629                 switch (instance->pdev->device) {
6630                 case PCI_DEVICE_ID_LSI_AERO_10E1:
6631                 case PCI_DEVICE_ID_LSI_AERO_10E2:
6632                 case PCI_DEVICE_ID_LSI_AERO_10E5:
6633                 case PCI_DEVICE_ID_LSI_AERO_10E6:
6634                         instance->adapter_type = AERO_SERIES;
6635                         break;
6636                 case PCI_DEVICE_ID_LSI_VENTURA:
6637                 case PCI_DEVICE_ID_LSI_CRUSADER:
6638                 case PCI_DEVICE_ID_LSI_HARPOON:
6639                 case PCI_DEVICE_ID_LSI_TOMCAT:
6640                 case PCI_DEVICE_ID_LSI_VENTURA_4PORT:
6641                 case PCI_DEVICE_ID_LSI_CRUSADER_4PORT:
6642                         instance->adapter_type = VENTURA_SERIES;
6643                         break;
6644                 case PCI_DEVICE_ID_LSI_FUSION:
6645                 case PCI_DEVICE_ID_LSI_PLASMA:
6646                         instance->adapter_type = THUNDERBOLT_SERIES;
6647                         break;
6648                 case PCI_DEVICE_ID_LSI_INVADER:
6649                 case PCI_DEVICE_ID_LSI_INTRUDER:
6650                 case PCI_DEVICE_ID_LSI_INTRUDER_24:
6651                 case PCI_DEVICE_ID_LSI_CUTLASS_52:
6652                 case PCI_DEVICE_ID_LSI_CUTLASS_53:
6653                 case PCI_DEVICE_ID_LSI_FURY:
6654                         instance->adapter_type = INVADER_SERIES;
6655                         break;
6656                 default: /* For all other supported controllers */
6657                         instance->adapter_type = MFI_SERIES;
6658                         break;
6659                 }
6660         }
6661 }
6662
6663 static inline int megasas_alloc_mfi_ctrl_mem(struct megasas_instance *instance)
6664 {
6665         instance->producer = dma_alloc_coherent(&instance->pdev->dev,
6666                         sizeof(u32), &instance->producer_h, GFP_KERNEL);
6667         instance->consumer = dma_alloc_coherent(&instance->pdev->dev,
6668                         sizeof(u32), &instance->consumer_h, GFP_KERNEL);
6669
6670         if (!instance->producer || !instance->consumer) {
6671                 dev_err(&instance->pdev->dev,
6672                         "Failed to allocate memory for producer, consumer\n");
6673                 return -1;
6674         }
6675
6676         *instance->producer = 0;
6677         *instance->consumer = 0;
6678         return 0;
6679 }
6680
6681 /**
6682  * megasas_alloc_ctrl_mem -     Allocate per controller memory for core data
6683  *                              structures which are not common across MFI
6684  *                              adapters and fusion adapters.
6685  *                              For MFI based adapters, allocate producer and
6686  *                              consumer buffers. For fusion adapters, allocate
6687  *                              memory for fusion context.
6688  * @instance:                   Adapter soft state
6689  * return:                      0 for SUCCESS
6690  */
6691 static int megasas_alloc_ctrl_mem(struct megasas_instance *instance)
6692 {
6693         instance->reply_map = kcalloc(nr_cpu_ids, sizeof(unsigned int),
6694                                       GFP_KERNEL);
6695         if (!instance->reply_map)
6696                 return -ENOMEM;
6697
6698         switch (instance->adapter_type) {
6699         case MFI_SERIES:
6700                 if (megasas_alloc_mfi_ctrl_mem(instance))
6701                         goto fail;
6702                 break;
6703         case AERO_SERIES:
6704         case VENTURA_SERIES:
6705         case THUNDERBOLT_SERIES:
6706         case INVADER_SERIES:
6707                 if (megasas_alloc_fusion_context(instance))
6708                         goto fail;
6709                 break;
6710         }
6711
6712         return 0;
6713  fail:
6714         kfree(instance->reply_map);
6715         instance->reply_map = NULL;
6716         return -ENOMEM;
6717 }
6718
6719 /*
6720  * megasas_free_ctrl_mem -      Free fusion context for fusion adapters and
6721  *                              producer, consumer buffers for MFI adapters
6722  *
6723  * @instance -                  Adapter soft instance
6724  *
6725  */
6726 static inline void megasas_free_ctrl_mem(struct megasas_instance *instance)
6727 {
6728         kfree(instance->reply_map);
6729         if (instance->adapter_type == MFI_SERIES) {
6730                 if (instance->producer)
6731                         dma_free_coherent(&instance->pdev->dev, sizeof(u32),
6732                                             instance->producer,
6733                                             instance->producer_h);
6734                 if (instance->consumer)
6735                         dma_free_coherent(&instance->pdev->dev, sizeof(u32),
6736                                             instance->consumer,
6737                                             instance->consumer_h);
6738         } else {
6739                 megasas_free_fusion_context(instance);
6740         }
6741 }
6742
6743 /**
6744  * megasas_alloc_ctrl_dma_buffers -     Allocate consistent DMA buffers during
6745  *                                      driver load time
6746  *
6747  * @instance-                           Adapter soft instance
6748  * @return-                             O for SUCCESS
6749  */
6750 static inline
6751 int megasas_alloc_ctrl_dma_buffers(struct megasas_instance *instance)
6752 {
6753         struct pci_dev *pdev = instance->pdev;
6754         struct fusion_context *fusion = instance->ctrl_context;
6755
6756         instance->evt_detail = dma_alloc_coherent(&pdev->dev,
6757                         sizeof(struct megasas_evt_detail),
6758                         &instance->evt_detail_h, GFP_KERNEL);
6759
6760         if (!instance->evt_detail) {
6761                 dev_err(&instance->pdev->dev,
6762                         "Failed to allocate event detail buffer\n");
6763                 return -ENOMEM;
6764         }
6765
6766         if (fusion) {
6767                 fusion->ioc_init_request =
6768                         dma_alloc_coherent(&pdev->dev,
6769                                            sizeof(struct MPI2_IOC_INIT_REQUEST),
6770                                            &fusion->ioc_init_request_phys,
6771                                            GFP_KERNEL);
6772
6773                 if (!fusion->ioc_init_request) {
6774                         dev_err(&pdev->dev,
6775                                 "Failed to allocate PD list buffer\n");
6776                         return -ENOMEM;
6777                 }
6778
6779                 instance->snapdump_prop = dma_alloc_coherent(&pdev->dev,
6780                                 sizeof(struct MR_SNAPDUMP_PROPERTIES),
6781                                 &instance->snapdump_prop_h, GFP_KERNEL);
6782
6783                 if (!instance->snapdump_prop)
6784                         dev_err(&pdev->dev,
6785                                 "Failed to allocate snapdump properties buffer\n");
6786
6787                 instance->host_device_list_buf = dma_alloc_coherent(&pdev->dev,
6788                                                         HOST_DEVICE_LIST_SZ,
6789                                                         &instance->host_device_list_buf_h,
6790                                                         GFP_KERNEL);
6791
6792                 if (!instance->host_device_list_buf) {
6793                         dev_err(&pdev->dev,
6794                                 "Failed to allocate targetid list buffer\n");
6795                         return -ENOMEM;
6796                 }
6797
6798         }
6799
6800         instance->pd_list_buf =
6801                 dma_alloc_coherent(&pdev->dev,
6802                                      MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
6803                                      &instance->pd_list_buf_h, GFP_KERNEL);
6804
6805         if (!instance->pd_list_buf) {
6806                 dev_err(&pdev->dev, "Failed to allocate PD list buffer\n");
6807                 return -ENOMEM;
6808         }
6809
6810         instance->ctrl_info_buf =
6811                 dma_alloc_coherent(&pdev->dev,
6812                                      sizeof(struct megasas_ctrl_info),
6813                                      &instance->ctrl_info_buf_h, GFP_KERNEL);
6814
6815         if (!instance->ctrl_info_buf) {
6816                 dev_err(&pdev->dev,
6817                         "Failed to allocate controller info buffer\n");
6818                 return -ENOMEM;
6819         }
6820
6821         instance->ld_list_buf =
6822                 dma_alloc_coherent(&pdev->dev,
6823                                      sizeof(struct MR_LD_LIST),
6824                                      &instance->ld_list_buf_h, GFP_KERNEL);
6825
6826         if (!instance->ld_list_buf) {
6827                 dev_err(&pdev->dev, "Failed to allocate LD list buffer\n");
6828                 return -ENOMEM;
6829         }
6830
6831         instance->ld_targetid_list_buf =
6832                 dma_alloc_coherent(&pdev->dev,
6833                                 sizeof(struct MR_LD_TARGETID_LIST),
6834                                 &instance->ld_targetid_list_buf_h, GFP_KERNEL);
6835
6836         if (!instance->ld_targetid_list_buf) {
6837                 dev_err(&pdev->dev,
6838                         "Failed to allocate LD targetid list buffer\n");
6839                 return -ENOMEM;
6840         }
6841
6842         if (!reset_devices) {
6843                 instance->system_info_buf =
6844                         dma_alloc_coherent(&pdev->dev,
6845                                         sizeof(struct MR_DRV_SYSTEM_INFO),
6846                                         &instance->system_info_h, GFP_KERNEL);
6847                 instance->pd_info =
6848                         dma_alloc_coherent(&pdev->dev,
6849                                         sizeof(struct MR_PD_INFO),
6850                                         &instance->pd_info_h, GFP_KERNEL);
6851                 instance->tgt_prop =
6852                         dma_alloc_coherent(&pdev->dev,
6853                                         sizeof(struct MR_TARGET_PROPERTIES),
6854                                         &instance->tgt_prop_h, GFP_KERNEL);
6855                 instance->crash_dump_buf =
6856                         dma_alloc_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
6857                                         &instance->crash_dump_h, GFP_KERNEL);
6858
6859                 if (!instance->system_info_buf)
6860                         dev_err(&instance->pdev->dev,
6861                                 "Failed to allocate system info buffer\n");
6862
6863                 if (!instance->pd_info)
6864                         dev_err(&instance->pdev->dev,
6865                                 "Failed to allocate pd_info buffer\n");
6866
6867                 if (!instance->tgt_prop)
6868                         dev_err(&instance->pdev->dev,
6869                                 "Failed to allocate tgt_prop buffer\n");
6870
6871                 if (!instance->crash_dump_buf)
6872                         dev_err(&instance->pdev->dev,
6873                                 "Failed to allocate crash dump buffer\n");
6874         }
6875
6876         return 0;
6877 }
6878
6879 /*
6880  * megasas_free_ctrl_dma_buffers -      Free consistent DMA buffers allocated
6881  *                                      during driver load time
6882  *
6883  * @instance-                           Adapter soft instance
6884  *
6885  */
6886 static inline
6887 void megasas_free_ctrl_dma_buffers(struct megasas_instance *instance)
6888 {
6889         struct pci_dev *pdev = instance->pdev;
6890         struct fusion_context *fusion = instance->ctrl_context;
6891
6892         if (instance->evt_detail)
6893                 dma_free_coherent(&pdev->dev, sizeof(struct megasas_evt_detail),
6894                                     instance->evt_detail,
6895                                     instance->evt_detail_h);
6896
6897         if (fusion && fusion->ioc_init_request)
6898                 dma_free_coherent(&pdev->dev,
6899                                   sizeof(struct MPI2_IOC_INIT_REQUEST),
6900                                   fusion->ioc_init_request,
6901                                   fusion->ioc_init_request_phys);
6902
6903         if (instance->pd_list_buf)
6904                 dma_free_coherent(&pdev->dev,
6905                                     MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
6906                                     instance->pd_list_buf,
6907                                     instance->pd_list_buf_h);
6908
6909         if (instance->ld_list_buf)
6910                 dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_LIST),
6911                                     instance->ld_list_buf,
6912                                     instance->ld_list_buf_h);
6913
6914         if (instance->ld_targetid_list_buf)
6915                 dma_free_coherent(&pdev->dev, sizeof(struct MR_LD_TARGETID_LIST),
6916                                     instance->ld_targetid_list_buf,
6917                                     instance->ld_targetid_list_buf_h);
6918
6919         if (instance->ctrl_info_buf)
6920                 dma_free_coherent(&pdev->dev, sizeof(struct megasas_ctrl_info),
6921                                     instance->ctrl_info_buf,
6922                                     instance->ctrl_info_buf_h);
6923
6924         if (instance->system_info_buf)
6925                 dma_free_coherent(&pdev->dev, sizeof(struct MR_DRV_SYSTEM_INFO),
6926                                     instance->system_info_buf,
6927                                     instance->system_info_h);
6928
6929         if (instance->pd_info)
6930                 dma_free_coherent(&pdev->dev, sizeof(struct MR_PD_INFO),
6931                                     instance->pd_info, instance->pd_info_h);
6932
6933         if (instance->tgt_prop)
6934                 dma_free_coherent(&pdev->dev, sizeof(struct MR_TARGET_PROPERTIES),
6935                                     instance->tgt_prop, instance->tgt_prop_h);
6936
6937         if (instance->crash_dump_buf)
6938                 dma_free_coherent(&pdev->dev, CRASH_DMA_BUF_SIZE,
6939                                     instance->crash_dump_buf,
6940                                     instance->crash_dump_h);
6941
6942         if (instance->snapdump_prop)
6943                 dma_free_coherent(&pdev->dev,
6944                                   sizeof(struct MR_SNAPDUMP_PROPERTIES),
6945                                   instance->snapdump_prop,
6946                                   instance->snapdump_prop_h);
6947
6948         if (instance->host_device_list_buf)
6949                 dma_free_coherent(&pdev->dev,
6950                                   HOST_DEVICE_LIST_SZ,
6951                                   instance->host_device_list_buf,
6952                                   instance->host_device_list_buf_h);
6953
6954 }
6955
6956 /*
6957  * megasas_init_ctrl_params -           Initialize controller's instance
6958  *                                      parameters before FW init
6959  * @instance -                          Adapter soft instance
6960  * @return -                            void
6961  */
6962 static inline void megasas_init_ctrl_params(struct megasas_instance *instance)
6963 {
6964         instance->fw_crash_state = UNAVAILABLE;
6965
6966         megasas_poll_wait_aen = 0;
6967         instance->issuepend_done = 1;
6968         atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
6969
6970         /*
6971          * Initialize locks and queues
6972          */
6973         INIT_LIST_HEAD(&instance->cmd_pool);
6974         INIT_LIST_HEAD(&instance->internal_reset_pending_q);
6975
6976         atomic_set(&instance->fw_outstanding, 0);
6977         atomic64_set(&instance->total_io_count, 0);
6978
6979         init_waitqueue_head(&instance->int_cmd_wait_q);
6980         init_waitqueue_head(&instance->abort_cmd_wait_q);
6981
6982         spin_lock_init(&instance->crashdump_lock);
6983         spin_lock_init(&instance->mfi_pool_lock);
6984         spin_lock_init(&instance->hba_lock);
6985         spin_lock_init(&instance->stream_lock);
6986         spin_lock_init(&instance->completion_lock);
6987
6988         mutex_init(&instance->reset_mutex);
6989
6990         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
6991             (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY))
6992                 instance->flag_ieee = 1;
6993
6994         megasas_dbg_lvl = 0;
6995         instance->flag = 0;
6996         instance->unload = 1;
6997         instance->last_time = 0;
6998         instance->disableOnlineCtrlReset = 1;
6999         instance->UnevenSpanSupport = 0;
7000         instance->smp_affinity_enable = smp_affinity_enable ? true : false;
7001         instance->msix_load_balance = false;
7002
7003         if (instance->adapter_type != MFI_SERIES)
7004                 INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
7005         else
7006                 INIT_WORK(&instance->work_init, process_fw_state_change_wq);
7007 }
7008
7009 /**
7010  * megasas_probe_one -  PCI hotplug entry point
7011  * @pdev:               PCI device structure
7012  * @id:                 PCI ids of supported hotplugged adapter
7013  */
7014 static int megasas_probe_one(struct pci_dev *pdev,
7015                              const struct pci_device_id *id)
7016 {
7017         int rval, pos;
7018         struct Scsi_Host *host;
7019         struct megasas_instance *instance;
7020         u16 control = 0;
7021
7022         switch (pdev->device) {
7023         case PCI_DEVICE_ID_LSI_AERO_10E1:
7024         case PCI_DEVICE_ID_LSI_AERO_10E5:
7025                 dev_info(&pdev->dev, "Adapter is in configurable secure mode\n");
7026                 break;
7027         }
7028
7029         /* Reset MSI-X in the kdump kernel */
7030         if (reset_devices) {
7031                 pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
7032                 if (pos) {
7033                         pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS,
7034                                              &control);
7035                         if (control & PCI_MSIX_FLAGS_ENABLE) {
7036                                 dev_info(&pdev->dev, "resetting MSI-X\n");
7037                                 pci_write_config_word(pdev,
7038                                                       pos + PCI_MSIX_FLAGS,
7039                                                       control &
7040                                                       ~PCI_MSIX_FLAGS_ENABLE);
7041                         }
7042                 }
7043         }
7044
7045         /*
7046          * PCI prepping: enable device set bus mastering and dma mask
7047          */
7048         rval = pci_enable_device_mem(pdev);
7049
7050         if (rval) {
7051                 return rval;
7052         }
7053
7054         pci_set_master(pdev);
7055
7056         host = scsi_host_alloc(&megasas_template,
7057                                sizeof(struct megasas_instance));
7058
7059         if (!host) {
7060                 dev_printk(KERN_DEBUG, &pdev->dev, "scsi_host_alloc failed\n");
7061                 goto fail_alloc_instance;
7062         }
7063
7064         instance = (struct megasas_instance *)host->hostdata;
7065         memset(instance, 0, sizeof(*instance));
7066         atomic_set(&instance->fw_reset_no_pci_access, 0);
7067
7068         /*
7069          * Initialize PCI related and misc parameters
7070          */
7071         instance->pdev = pdev;
7072         instance->host = host;
7073         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
7074         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
7075
7076         megasas_set_adapter_type(instance);
7077
7078         /*
7079          * Initialize MFI Firmware
7080          */
7081         if (megasas_init_fw(instance))
7082                 goto fail_init_mfi;
7083
7084         if (instance->requestorId) {
7085                 if (instance->PlasmaFW111) {
7086                         instance->vf_affiliation_111 =
7087                                 dma_alloc_coherent(&pdev->dev,
7088                                         sizeof(struct MR_LD_VF_AFFILIATION_111),
7089                                         &instance->vf_affiliation_111_h,
7090                                         GFP_KERNEL);
7091                         if (!instance->vf_affiliation_111)
7092                                 dev_warn(&pdev->dev, "Can't allocate "
7093                                        "memory for VF affiliation buffer\n");
7094                 } else {
7095                         instance->vf_affiliation =
7096                                 dma_alloc_coherent(&pdev->dev,
7097                                         (MAX_LOGICAL_DRIVES + 1) *
7098                                         sizeof(struct MR_LD_VF_AFFILIATION),
7099                                         &instance->vf_affiliation_h,
7100                                         GFP_KERNEL);
7101                         if (!instance->vf_affiliation)
7102                                 dev_warn(&pdev->dev, "Can't allocate "
7103                                        "memory for VF affiliation buffer\n");
7104                 }
7105         }
7106
7107         /*
7108          * Store instance in PCI softstate
7109          */
7110         pci_set_drvdata(pdev, instance);
7111
7112         /*
7113          * Add this controller to megasas_mgmt_info structure so that it
7114          * can be exported to management applications
7115          */
7116         megasas_mgmt_info.count++;
7117         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
7118         megasas_mgmt_info.max_index++;
7119
7120         /*
7121          * Register with SCSI mid-layer
7122          */
7123         if (megasas_io_attach(instance))
7124                 goto fail_io_attach;
7125
7126         instance->unload = 0;
7127         /*
7128          * Trigger SCSI to scan our drives
7129          */
7130         if (!instance->enable_fw_dev_list ||
7131             (instance->host_device_list_buf->count > 0))
7132                 scsi_scan_host(host);
7133
7134         /*
7135          * Initiate AEN (Asynchronous Event Notification)
7136          */
7137         if (megasas_start_aen(instance)) {
7138                 dev_printk(KERN_DEBUG, &pdev->dev, "start aen failed\n");
7139                 goto fail_start_aen;
7140         }
7141
7142         /* Get current SR-IOV LD/VF affiliation */
7143         if (instance->requestorId)
7144                 megasas_get_ld_vf_affiliation(instance, 1);
7145
7146         return 0;
7147
7148 fail_start_aen:
7149 fail_io_attach:
7150         megasas_mgmt_info.count--;
7151         megasas_mgmt_info.max_index--;
7152         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
7153
7154         instance->instancet->disable_intr(instance);
7155         megasas_destroy_irqs(instance);
7156
7157         if (instance->adapter_type != MFI_SERIES)
7158                 megasas_release_fusion(instance);
7159         else
7160                 megasas_release_mfi(instance);
7161         if (instance->msix_vectors)
7162                 pci_free_irq_vectors(instance->pdev);
7163 fail_init_mfi:
7164         scsi_host_put(host);
7165 fail_alloc_instance:
7166         pci_disable_device(pdev);
7167
7168         return -ENODEV;
7169 }
7170
7171 /**
7172  * megasas_flush_cache -        Requests FW to flush all its caches
7173  * @instance:                   Adapter soft state
7174  */
7175 static void megasas_flush_cache(struct megasas_instance *instance)
7176 {
7177         struct megasas_cmd *cmd;
7178         struct megasas_dcmd_frame *dcmd;
7179
7180         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7181                 return;
7182
7183         cmd = megasas_get_cmd(instance);
7184
7185         if (!cmd)
7186                 return;
7187
7188         dcmd = &cmd->frame->dcmd;
7189
7190         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7191
7192         dcmd->cmd = MFI_CMD_DCMD;
7193         dcmd->cmd_status = 0x0;
7194         dcmd->sge_count = 0;
7195         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7196         dcmd->timeout = 0;
7197         dcmd->pad_0 = 0;
7198         dcmd->data_xfer_len = 0;
7199         dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH);
7200         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
7201
7202         if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7203                         != DCMD_SUCCESS) {
7204                 dev_err(&instance->pdev->dev,
7205                         "return from %s %d\n", __func__, __LINE__);
7206                 return;
7207         }
7208
7209         megasas_return_cmd(instance, cmd);
7210 }
7211
7212 /**
7213  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
7214  * @instance:                           Adapter soft state
7215  * @opcode:                             Shutdown/Hibernate
7216  */
7217 static void megasas_shutdown_controller(struct megasas_instance *instance,
7218                                         u32 opcode)
7219 {
7220         struct megasas_cmd *cmd;
7221         struct megasas_dcmd_frame *dcmd;
7222
7223         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
7224                 return;
7225
7226         cmd = megasas_get_cmd(instance);
7227
7228         if (!cmd)
7229                 return;
7230
7231         if (instance->aen_cmd)
7232                 megasas_issue_blocked_abort_cmd(instance,
7233                         instance->aen_cmd, MFI_IO_TIMEOUT_SECS);
7234         if (instance->map_update_cmd)
7235                 megasas_issue_blocked_abort_cmd(instance,
7236                         instance->map_update_cmd, MFI_IO_TIMEOUT_SECS);
7237         if (instance->jbod_seq_cmd)
7238                 megasas_issue_blocked_abort_cmd(instance,
7239                         instance->jbod_seq_cmd, MFI_IO_TIMEOUT_SECS);
7240
7241         dcmd = &cmd->frame->dcmd;
7242
7243         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
7244
7245         dcmd->cmd = MFI_CMD_DCMD;
7246         dcmd->cmd_status = 0x0;
7247         dcmd->sge_count = 0;
7248         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
7249         dcmd->timeout = 0;
7250         dcmd->pad_0 = 0;
7251         dcmd->data_xfer_len = 0;
7252         dcmd->opcode = cpu_to_le32(opcode);
7253
7254         if (megasas_issue_blocked_cmd(instance, cmd, MFI_IO_TIMEOUT_SECS)
7255                         != DCMD_SUCCESS) {
7256                 dev_err(&instance->pdev->dev,
7257                         "return from %s %d\n", __func__, __LINE__);
7258                 return;
7259         }
7260
7261         megasas_return_cmd(instance, cmd);
7262 }
7263
7264 #ifdef CONFIG_PM
7265 /**
7266  * megasas_suspend -    driver suspend entry point
7267  * @pdev:               PCI device structure
7268  * @state:              PCI power state to suspend routine
7269  */
7270 static int
7271 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
7272 {
7273         struct Scsi_Host *host;
7274         struct megasas_instance *instance;
7275
7276         instance = pci_get_drvdata(pdev);
7277         host = instance->host;
7278         instance->unload = 1;
7279
7280         dev_info(&pdev->dev, "%s is called\n", __func__);
7281
7282         /* Shutdown SR-IOV heartbeat timer */
7283         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7284                 del_timer_sync(&instance->sriov_heartbeat_timer);
7285
7286         /* Stop the FW fault detection watchdog */
7287         if (instance->adapter_type != MFI_SERIES)
7288                 megasas_fusion_stop_watchdog(instance);
7289
7290         megasas_flush_cache(instance);
7291         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
7292
7293         /* cancel the delayed work if this work still in queue */
7294         if (instance->ev != NULL) {
7295                 struct megasas_aen_event *ev = instance->ev;
7296                 cancel_delayed_work_sync(&ev->hotplug_work);
7297                 instance->ev = NULL;
7298         }
7299
7300         tasklet_kill(&instance->isr_tasklet);
7301
7302         pci_set_drvdata(instance->pdev, instance);
7303         instance->instancet->disable_intr(instance);
7304
7305         megasas_destroy_irqs(instance);
7306
7307         if (instance->msix_vectors)
7308                 pci_free_irq_vectors(instance->pdev);
7309
7310         pci_save_state(pdev);
7311         pci_disable_device(pdev);
7312
7313         pci_set_power_state(pdev, pci_choose_state(pdev, state));
7314
7315         return 0;
7316 }
7317
7318 /**
7319  * megasas_resume-      driver resume entry point
7320  * @pdev:               PCI device structure
7321  */
7322 static int
7323 megasas_resume(struct pci_dev *pdev)
7324 {
7325         int rval;
7326         struct Scsi_Host *host;
7327         struct megasas_instance *instance;
7328         int irq_flags = PCI_IRQ_LEGACY;
7329
7330         instance = pci_get_drvdata(pdev);
7331         host = instance->host;
7332         pci_set_power_state(pdev, PCI_D0);
7333         pci_enable_wake(pdev, PCI_D0, 0);
7334         pci_restore_state(pdev);
7335
7336         dev_info(&pdev->dev, "%s is called\n", __func__);
7337         /*
7338          * PCI prepping: enable device set bus mastering and dma mask
7339          */
7340         rval = pci_enable_device_mem(pdev);
7341
7342         if (rval) {
7343                 dev_err(&pdev->dev, "Enable device failed\n");
7344                 return rval;
7345         }
7346
7347         pci_set_master(pdev);
7348
7349         /*
7350          * We expect the FW state to be READY
7351          */
7352         if (megasas_transition_to_ready(instance, 0))
7353                 goto fail_ready_state;
7354
7355         if (megasas_set_dma_mask(instance))
7356                 goto fail_set_dma_mask;
7357
7358         /*
7359          * Initialize MFI Firmware
7360          */
7361
7362         atomic_set(&instance->fw_outstanding, 0);
7363         atomic_set(&instance->ldio_outstanding, 0);
7364
7365         /* Now re-enable MSI-X */
7366         if (instance->msix_vectors) {
7367                 irq_flags = PCI_IRQ_MSIX;
7368                 if (instance->smp_affinity_enable)
7369                         irq_flags |= PCI_IRQ_AFFINITY;
7370         }
7371         rval = pci_alloc_irq_vectors(instance->pdev, 1,
7372                                      instance->msix_vectors ?
7373                                      instance->msix_vectors : 1, irq_flags);
7374         if (rval < 0)
7375                 goto fail_reenable_msix;
7376
7377         megasas_setup_reply_map(instance);
7378
7379         if (instance->adapter_type != MFI_SERIES) {
7380                 megasas_reset_reply_desc(instance);
7381                 if (megasas_ioc_init_fusion(instance)) {
7382                         megasas_free_cmds(instance);
7383                         megasas_free_cmds_fusion(instance);
7384                         goto fail_init_mfi;
7385                 }
7386                 if (!megasas_get_map_info(instance))
7387                         megasas_sync_map_info(instance);
7388         } else {
7389                 *instance->producer = 0;
7390                 *instance->consumer = 0;
7391                 if (megasas_issue_init_mfi(instance))
7392                         goto fail_init_mfi;
7393         }
7394
7395         if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS)
7396                 goto fail_init_mfi;
7397
7398         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
7399                      (unsigned long)instance);
7400
7401         if (instance->msix_vectors ?
7402                         megasas_setup_irqs_msix(instance, 0) :
7403                         megasas_setup_irqs_ioapic(instance))
7404                 goto fail_init_mfi;
7405
7406         if (instance->adapter_type != MFI_SERIES)
7407                 megasas_setup_irq_poll(instance);
7408
7409         /* Re-launch SR-IOV heartbeat timer */
7410         if (instance->requestorId) {
7411                 if (!megasas_sriov_start_heartbeat(instance, 0))
7412                         megasas_start_timer(instance);
7413                 else {
7414                         instance->skip_heartbeat_timer_del = 1;
7415                         goto fail_init_mfi;
7416                 }
7417         }
7418
7419         instance->instancet->enable_intr(instance);
7420         megasas_setup_jbod_map(instance);
7421         instance->unload = 0;
7422
7423         /*
7424          * Initiate AEN (Asynchronous Event Notification)
7425          */
7426         if (megasas_start_aen(instance))
7427                 dev_err(&instance->pdev->dev, "Start AEN failed\n");
7428
7429         /* Re-launch FW fault watchdog */
7430         if (instance->adapter_type != MFI_SERIES)
7431                 if (megasas_fusion_start_watchdog(instance) != SUCCESS)
7432                         goto fail_start_watchdog;
7433
7434         return 0;
7435
7436 fail_start_watchdog:
7437         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7438                 del_timer_sync(&instance->sriov_heartbeat_timer);
7439 fail_init_mfi:
7440         megasas_free_ctrl_dma_buffers(instance);
7441         megasas_free_ctrl_mem(instance);
7442         scsi_host_put(host);
7443
7444 fail_reenable_msix:
7445 fail_set_dma_mask:
7446 fail_ready_state:
7447
7448         pci_disable_device(pdev);
7449
7450         return -ENODEV;
7451 }
7452 #else
7453 #define megasas_suspend NULL
7454 #define megasas_resume  NULL
7455 #endif
7456
7457 static inline int
7458 megasas_wait_for_adapter_operational(struct megasas_instance *instance)
7459 {
7460         int wait_time = MEGASAS_RESET_WAIT_TIME * 2;
7461         int i;
7462         u8 adp_state;
7463
7464         for (i = 0; i < wait_time; i++) {
7465                 adp_state = atomic_read(&instance->adprecovery);
7466                 if ((adp_state == MEGASAS_HBA_OPERATIONAL) ||
7467                     (adp_state == MEGASAS_HW_CRITICAL_ERROR))
7468                         break;
7469
7470                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL))
7471                         dev_notice(&instance->pdev->dev, "waiting for controller reset to finish\n");
7472
7473                 msleep(1000);
7474         }
7475
7476         if (adp_state != MEGASAS_HBA_OPERATIONAL) {
7477                 dev_info(&instance->pdev->dev,
7478                          "%s HBA failed to become operational, adp_state %d\n",
7479                          __func__, adp_state);
7480                 return 1;
7481         }
7482
7483         return 0;
7484 }
7485
7486 /**
7487  * megasas_detach_one - PCI hot"un"plug entry point
7488  * @pdev:               PCI device structure
7489  */
7490 static void megasas_detach_one(struct pci_dev *pdev)
7491 {
7492         int i;
7493         struct Scsi_Host *host;
7494         struct megasas_instance *instance;
7495         struct fusion_context *fusion;
7496         u32 pd_seq_map_sz;
7497
7498         instance = pci_get_drvdata(pdev);
7499         host = instance->host;
7500         fusion = instance->ctrl_context;
7501
7502         /* Shutdown SR-IOV heartbeat timer */
7503         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
7504                 del_timer_sync(&instance->sriov_heartbeat_timer);
7505
7506         /* Stop the FW fault detection watchdog */
7507         if (instance->adapter_type != MFI_SERIES)
7508                 megasas_fusion_stop_watchdog(instance);
7509
7510         if (instance->fw_crash_state != UNAVAILABLE)
7511                 megasas_free_host_crash_buffer(instance);
7512         scsi_remove_host(instance->host);
7513         instance->unload = 1;
7514
7515         if (megasas_wait_for_adapter_operational(instance))
7516                 goto skip_firing_dcmds;
7517
7518         megasas_flush_cache(instance);
7519         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
7520
7521 skip_firing_dcmds:
7522         /* cancel the delayed work if this work still in queue*/
7523         if (instance->ev != NULL) {
7524                 struct megasas_aen_event *ev = instance->ev;
7525                 cancel_delayed_work_sync(&ev->hotplug_work);
7526                 instance->ev = NULL;
7527         }
7528
7529         /* cancel all wait events */
7530         wake_up_all(&instance->int_cmd_wait_q);
7531
7532         tasklet_kill(&instance->isr_tasklet);
7533
7534         /*
7535          * Take the instance off the instance array. Note that we will not
7536          * decrement the max_index. We let this array be sparse array
7537          */
7538         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
7539                 if (megasas_mgmt_info.instance[i] == instance) {
7540                         megasas_mgmt_info.count--;
7541                         megasas_mgmt_info.instance[i] = NULL;
7542
7543                         break;
7544                 }
7545         }
7546
7547         instance->instancet->disable_intr(instance);
7548
7549         megasas_destroy_irqs(instance);
7550
7551         if (instance->msix_vectors)
7552                 pci_free_irq_vectors(instance->pdev);
7553
7554         if (instance->adapter_type >= VENTURA_SERIES) {
7555                 for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i)
7556                         kfree(fusion->stream_detect_by_ld[i]);
7557                 kfree(fusion->stream_detect_by_ld);
7558                 fusion->stream_detect_by_ld = NULL;
7559         }
7560
7561
7562         if (instance->adapter_type != MFI_SERIES) {
7563                 megasas_release_fusion(instance);
7564                         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
7565                                 (sizeof(struct MR_PD_CFG_SEQ) *
7566                                         (MAX_PHYSICAL_DEVICES - 1));
7567                 for (i = 0; i < 2 ; i++) {
7568                         if (fusion->ld_map[i])
7569                                 dma_free_coherent(&instance->pdev->dev,
7570                                                   fusion->max_map_sz,
7571                                                   fusion->ld_map[i],
7572                                                   fusion->ld_map_phys[i]);
7573                         if (fusion->ld_drv_map[i]) {
7574                                 if (is_vmalloc_addr(fusion->ld_drv_map[i]))
7575                                         vfree(fusion->ld_drv_map[i]);
7576                                 else
7577                                         free_pages((ulong)fusion->ld_drv_map[i],
7578                                                    fusion->drv_map_pages);
7579                         }
7580
7581                         if (fusion->pd_seq_sync[i])
7582                                 dma_free_coherent(&instance->pdev->dev,
7583                                         pd_seq_map_sz,
7584                                         fusion->pd_seq_sync[i],
7585                                         fusion->pd_seq_phys[i]);
7586                 }
7587         } else {
7588                 megasas_release_mfi(instance);
7589         }
7590
7591         if (instance->vf_affiliation)
7592                 dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) *
7593                                     sizeof(struct MR_LD_VF_AFFILIATION),
7594                                     instance->vf_affiliation,
7595                                     instance->vf_affiliation_h);
7596
7597         if (instance->vf_affiliation_111)
7598                 dma_free_coherent(&pdev->dev,
7599                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
7600                                     instance->vf_affiliation_111,
7601                                     instance->vf_affiliation_111_h);
7602
7603         if (instance->hb_host_mem)
7604                 dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM),
7605                                     instance->hb_host_mem,
7606                                     instance->hb_host_mem_h);
7607
7608         megasas_free_ctrl_dma_buffers(instance);
7609
7610         megasas_free_ctrl_mem(instance);
7611
7612         scsi_host_put(host);
7613
7614         pci_disable_device(pdev);
7615 }
7616
7617 /**
7618  * megasas_shutdown -   Shutdown entry point
7619  * @device:             Generic device structure
7620  */
7621 static void megasas_shutdown(struct pci_dev *pdev)
7622 {
7623         struct megasas_instance *instance = pci_get_drvdata(pdev);
7624
7625         instance->unload = 1;
7626
7627         if (megasas_wait_for_adapter_operational(instance))
7628                 goto skip_firing_dcmds;
7629
7630         megasas_flush_cache(instance);
7631         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
7632
7633 skip_firing_dcmds:
7634         instance->instancet->disable_intr(instance);
7635         megasas_destroy_irqs(instance);
7636
7637         if (instance->msix_vectors)
7638                 pci_free_irq_vectors(instance->pdev);
7639 }
7640
7641 /**
7642  * megasas_mgmt_open -  char node "open" entry point
7643  */
7644 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
7645 {
7646         /*
7647          * Allow only those users with admin rights
7648          */
7649         if (!capable(CAP_SYS_ADMIN))
7650                 return -EACCES;
7651
7652         return 0;
7653 }
7654
7655 /**
7656  * megasas_mgmt_fasync -        Async notifier registration from applications
7657  *
7658  * This function adds the calling process to a driver global queue. When an
7659  * event occurs, SIGIO will be sent to all processes in this queue.
7660  */
7661 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
7662 {
7663         int rc;
7664
7665         mutex_lock(&megasas_async_queue_mutex);
7666
7667         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
7668
7669         mutex_unlock(&megasas_async_queue_mutex);
7670
7671         if (rc >= 0) {
7672                 /* For sanity check when we get ioctl */
7673                 filep->private_data = filep;
7674                 return 0;
7675         }
7676
7677         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
7678
7679         return rc;
7680 }
7681
7682 /**
7683  * megasas_mgmt_poll -  char node "poll" entry point
7684  * */
7685 static __poll_t megasas_mgmt_poll(struct file *file, poll_table *wait)
7686 {
7687         __poll_t mask;
7688         unsigned long flags;
7689
7690         poll_wait(file, &megasas_poll_wait, wait);
7691         spin_lock_irqsave(&poll_aen_lock, flags);
7692         if (megasas_poll_wait_aen)
7693                 mask = (EPOLLIN | EPOLLRDNORM);
7694         else
7695                 mask = 0;
7696         megasas_poll_wait_aen = 0;
7697         spin_unlock_irqrestore(&poll_aen_lock, flags);
7698         return mask;
7699 }
7700
7701 /*
7702  * megasas_set_crash_dump_params_ioctl:
7703  *              Send CRASH_DUMP_MODE DCMD to all controllers
7704  * @cmd:        MFI command frame
7705  */
7706
7707 static int megasas_set_crash_dump_params_ioctl(struct megasas_cmd *cmd)
7708 {
7709         struct megasas_instance *local_instance;
7710         int i, error = 0;
7711         int crash_support;
7712
7713         crash_support = cmd->frame->dcmd.mbox.w[0];
7714
7715         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
7716                 local_instance = megasas_mgmt_info.instance[i];
7717                 if (local_instance && local_instance->crash_dump_drv_support) {
7718                         if ((atomic_read(&local_instance->adprecovery) ==
7719                                 MEGASAS_HBA_OPERATIONAL) &&
7720                                 !megasas_set_crash_dump_params(local_instance,
7721                                         crash_support)) {
7722                                 local_instance->crash_dump_app_support =
7723                                         crash_support;
7724                                 dev_info(&local_instance->pdev->dev,
7725                                         "Application firmware crash "
7726                                         "dump mode set success\n");
7727                                 error = 0;
7728                         } else {
7729                                 dev_info(&local_instance->pdev->dev,
7730                                         "Application firmware crash "
7731                                         "dump mode set failed\n");
7732                                 error = -1;
7733                         }
7734                 }
7735         }
7736         return error;
7737 }
7738
7739 /**
7740  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
7741  * @instance:                   Adapter soft state
7742  * @argp:                       User's ioctl packet
7743  */
7744 static int
7745 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
7746                       struct megasas_iocpacket __user * user_ioc,
7747                       struct megasas_iocpacket *ioc)
7748 {
7749         struct megasas_sge64 *kern_sge64 = NULL;
7750         struct megasas_sge32 *kern_sge32 = NULL;
7751         struct megasas_cmd *cmd;
7752         void *kbuff_arr[MAX_IOCTL_SGE];
7753         dma_addr_t buf_handle = 0;
7754         int error = 0, i;
7755         void *sense = NULL;
7756         dma_addr_t sense_handle;
7757         unsigned long *sense_ptr;
7758         u32 opcode = 0;
7759
7760         memset(kbuff_arr, 0, sizeof(kbuff_arr));
7761
7762         if (ioc->sge_count > MAX_IOCTL_SGE) {
7763                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "SGE count [%d] >  max limit [%d]\n",
7764                        ioc->sge_count, MAX_IOCTL_SGE);
7765                 return -EINVAL;
7766         }
7767
7768         if ((ioc->frame.hdr.cmd >= MFI_CMD_OP_COUNT) ||
7769             ((ioc->frame.hdr.cmd == MFI_CMD_NVME) &&
7770             !instance->support_nvme_passthru)) {
7771                 dev_err(&instance->pdev->dev,
7772                         "Received invalid ioctl command 0x%x\n",
7773                         ioc->frame.hdr.cmd);
7774                 return -ENOTSUPP;
7775         }
7776
7777         cmd = megasas_get_cmd(instance);
7778         if (!cmd) {
7779                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get a cmd packet\n");
7780                 return -ENOMEM;
7781         }
7782
7783         /*
7784          * User's IOCTL packet has 2 frames (maximum). Copy those two
7785          * frames into our cmd's frames. cmd->frame's context will get
7786          * overwritten when we copy from user's frames. So set that value
7787          * alone separately
7788          */
7789         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
7790         cmd->frame->hdr.context = cpu_to_le32(cmd->index);
7791         cmd->frame->hdr.pad_0 = 0;
7792
7793         cmd->frame->hdr.flags &= (~MFI_FRAME_IEEE);
7794
7795         if (instance->consistent_mask_64bit)
7796                 cmd->frame->hdr.flags |= cpu_to_le16((MFI_FRAME_SGL64 |
7797                                        MFI_FRAME_SENSE64));
7798         else
7799                 cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_SGL64 |
7800                                                MFI_FRAME_SENSE64));
7801
7802         if (cmd->frame->hdr.cmd == MFI_CMD_DCMD)
7803                 opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
7804
7805         if (opcode == MR_DCMD_CTRL_SHUTDOWN) {
7806                 if (megasas_get_ctrl_info(instance) != DCMD_SUCCESS) {
7807                         megasas_return_cmd(instance, cmd);
7808                         return -1;
7809                 }
7810         }
7811
7812         if (opcode == MR_DRIVER_SET_APP_CRASHDUMP_MODE) {
7813                 error = megasas_set_crash_dump_params_ioctl(cmd);
7814                 megasas_return_cmd(instance, cmd);
7815                 return error;
7816         }
7817
7818         /*
7819          * The management interface between applications and the fw uses
7820          * MFI frames. E.g, RAID configuration changes, LD property changes
7821          * etc are accomplishes through different kinds of MFI frames. The
7822          * driver needs to care only about substituting user buffers with
7823          * kernel buffers in SGLs. The location of SGL is embedded in the
7824          * struct iocpacket itself.
7825          */
7826         if (instance->consistent_mask_64bit)
7827                 kern_sge64 = (struct megasas_sge64 *)
7828                         ((unsigned long)cmd->frame + ioc->sgl_off);
7829         else
7830                 kern_sge32 = (struct megasas_sge32 *)
7831                         ((unsigned long)cmd->frame + ioc->sgl_off);
7832
7833         /*
7834          * For each user buffer, create a mirror buffer and copy in
7835          */
7836         for (i = 0; i < ioc->sge_count; i++) {
7837                 if (!ioc->sgl[i].iov_len)
7838                         continue;
7839
7840                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
7841                                                     ioc->sgl[i].iov_len,
7842                                                     &buf_handle, GFP_KERNEL);
7843                 if (!kbuff_arr[i]) {
7844                         dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc "
7845                                "kernel SGL buffer for IOCTL\n");
7846                         error = -ENOMEM;
7847                         goto out;
7848                 }
7849
7850                 /*
7851                  * We don't change the dma_coherent_mask, so
7852                  * dma_alloc_coherent only returns 32bit addresses
7853                  */
7854                 if (instance->consistent_mask_64bit) {
7855                         kern_sge64[i].phys_addr = cpu_to_le64(buf_handle);
7856                         kern_sge64[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
7857                 } else {
7858                         kern_sge32[i].phys_addr = cpu_to_le32(buf_handle);
7859                         kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
7860                 }
7861
7862                 /*
7863                  * We created a kernel buffer corresponding to the
7864                  * user buffer. Now copy in from the user buffer
7865                  */
7866                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
7867                                    (u32) (ioc->sgl[i].iov_len))) {
7868                         error = -EFAULT;
7869                         goto out;
7870                 }
7871         }
7872
7873         if (ioc->sense_len) {
7874                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
7875                                              &sense_handle, GFP_KERNEL);
7876                 if (!sense) {
7877                         error = -ENOMEM;
7878                         goto out;
7879                 }
7880
7881                 sense_ptr =
7882                 (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
7883                 if (instance->consistent_mask_64bit)
7884                         *sense_ptr = cpu_to_le64(sense_handle);
7885                 else
7886                         *sense_ptr = cpu_to_le32(sense_handle);
7887         }
7888
7889         /*
7890          * Set the sync_cmd flag so that the ISR knows not to complete this
7891          * cmd to the SCSI mid-layer
7892          */
7893         cmd->sync_cmd = 1;
7894         if (megasas_issue_blocked_cmd(instance, cmd, 0) == DCMD_NOT_FIRED) {
7895                 cmd->sync_cmd = 0;
7896                 dev_err(&instance->pdev->dev,
7897                         "return -EBUSY from %s %d cmd 0x%x opcode 0x%x cmd->cmd_status_drv 0x%x\n",
7898                         __func__, __LINE__, cmd->frame->hdr.cmd, opcode,
7899                         cmd->cmd_status_drv);
7900                 return -EBUSY;
7901         }
7902
7903         cmd->sync_cmd = 0;
7904
7905         if (instance->unload == 1) {
7906                 dev_info(&instance->pdev->dev, "Driver unload is in progress "
7907                         "don't submit data to application\n");
7908                 goto out;
7909         }
7910         /*
7911          * copy out the kernel buffers to user buffers
7912          */
7913         for (i = 0; i < ioc->sge_count; i++) {
7914                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
7915                                  ioc->sgl[i].iov_len)) {
7916                         error = -EFAULT;
7917                         goto out;
7918                 }
7919         }
7920
7921         /*
7922          * copy out the sense
7923          */
7924         if (ioc->sense_len) {
7925                 /*
7926                  * sense_ptr points to the location that has the user
7927                  * sense buffer address
7928                  */
7929                 sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
7930                                 ioc->sense_off);
7931
7932                 if (copy_to_user((void __user *)((unsigned long)
7933                                  get_unaligned((unsigned long *)sense_ptr)),
7934                                  sense, ioc->sense_len)) {
7935                         dev_err(&instance->pdev->dev, "Failed to copy out to user "
7936                                         "sense data\n");
7937                         error = -EFAULT;
7938                         goto out;
7939                 }
7940         }
7941
7942         /*
7943          * copy the status codes returned by the fw
7944          */
7945         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
7946                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
7947                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error copying out cmd_status\n");
7948                 error = -EFAULT;
7949         }
7950
7951 out:
7952         if (sense) {
7953                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
7954                                     sense, sense_handle);
7955         }
7956
7957         for (i = 0; i < ioc->sge_count; i++) {
7958                 if (kbuff_arr[i]) {
7959                         if (instance->consistent_mask_64bit)
7960                                 dma_free_coherent(&instance->pdev->dev,
7961                                         le32_to_cpu(kern_sge64[i].length),
7962                                         kbuff_arr[i],
7963                                         le64_to_cpu(kern_sge64[i].phys_addr));
7964                         else
7965                                 dma_free_coherent(&instance->pdev->dev,
7966                                         le32_to_cpu(kern_sge32[i].length),
7967                                         kbuff_arr[i],
7968                                         le32_to_cpu(kern_sge32[i].phys_addr));
7969                         kbuff_arr[i] = NULL;
7970                 }
7971         }
7972
7973         megasas_return_cmd(instance, cmd);
7974         return error;
7975 }
7976
7977 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
7978 {
7979         struct megasas_iocpacket __user *user_ioc =
7980             (struct megasas_iocpacket __user *)arg;
7981         struct megasas_iocpacket *ioc;
7982         struct megasas_instance *instance;
7983         int error;
7984
7985         ioc = memdup_user(user_ioc, sizeof(*ioc));
7986         if (IS_ERR(ioc))
7987                 return PTR_ERR(ioc);
7988
7989         instance = megasas_lookup_instance(ioc->host_no);
7990         if (!instance) {
7991                 error = -ENODEV;
7992                 goto out_kfree_ioc;
7993         }
7994
7995         /* Block ioctls in VF mode */
7996         if (instance->requestorId && !allow_vf_ioctls) {
7997                 error = -ENODEV;
7998                 goto out_kfree_ioc;
7999         }
8000
8001         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8002                 dev_err(&instance->pdev->dev, "Controller in crit error\n");
8003                 error = -ENODEV;
8004                 goto out_kfree_ioc;
8005         }
8006
8007         if (instance->unload == 1) {
8008                 error = -ENODEV;
8009                 goto out_kfree_ioc;
8010         }
8011
8012         if (down_interruptible(&instance->ioctl_sem)) {
8013                 error = -ERESTARTSYS;
8014                 goto out_kfree_ioc;
8015         }
8016
8017         if  (megasas_wait_for_adapter_operational(instance)) {
8018                 error = -ENODEV;
8019                 goto out_up;
8020         }
8021
8022         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
8023 out_up:
8024         up(&instance->ioctl_sem);
8025
8026 out_kfree_ioc:
8027         kfree(ioc);
8028         return error;
8029 }
8030
8031 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
8032 {
8033         struct megasas_instance *instance;
8034         struct megasas_aen aen;
8035         int error;
8036
8037         if (file->private_data != file) {
8038                 printk(KERN_DEBUG "megasas: fasync_helper was not "
8039                        "called first\n");
8040                 return -EINVAL;
8041         }
8042
8043         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
8044                 return -EFAULT;
8045
8046         instance = megasas_lookup_instance(aen.host_no);
8047
8048         if (!instance)
8049                 return -ENODEV;
8050
8051         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
8052                 return -ENODEV;
8053         }
8054
8055         if (instance->unload == 1) {
8056                 return -ENODEV;
8057         }
8058
8059         if  (megasas_wait_for_adapter_operational(instance))
8060                 return -ENODEV;
8061
8062         mutex_lock(&instance->reset_mutex);
8063         error = megasas_register_aen(instance, aen.seq_num,
8064                                      aen.class_locale_word);
8065         mutex_unlock(&instance->reset_mutex);
8066         return error;
8067 }
8068
8069 /**
8070  * megasas_mgmt_ioctl - char node ioctl entry point
8071  */
8072 static long
8073 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
8074 {
8075         switch (cmd) {
8076         case MEGASAS_IOC_FIRMWARE:
8077                 return megasas_mgmt_ioctl_fw(file, arg);
8078
8079         case MEGASAS_IOC_GET_AEN:
8080                 return megasas_mgmt_ioctl_aen(file, arg);
8081         }
8082
8083         return -ENOTTY;
8084 }
8085
8086 #ifdef CONFIG_COMPAT
8087 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
8088 {
8089         struct compat_megasas_iocpacket __user *cioc =
8090             (struct compat_megasas_iocpacket __user *)arg;
8091         struct megasas_iocpacket __user *ioc =
8092             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
8093         int i;
8094         int error = 0;
8095         compat_uptr_t ptr;
8096         u32 local_sense_off;
8097         u32 local_sense_len;
8098         u32 user_sense_off;
8099
8100         if (clear_user(ioc, sizeof(*ioc)))
8101                 return -EFAULT;
8102
8103         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
8104             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
8105             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
8106             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
8107             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
8108             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
8109                 return -EFAULT;
8110
8111         /*
8112          * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
8113          * sense_len is not null, so prepare the 64bit value under
8114          * the same condition.
8115          */
8116         if (get_user(local_sense_off, &ioc->sense_off) ||
8117                 get_user(local_sense_len, &ioc->sense_len) ||
8118                 get_user(user_sense_off, &cioc->sense_off))
8119                 return -EFAULT;
8120
8121         if (local_sense_off != user_sense_off)
8122                 return -EINVAL;
8123
8124         if (local_sense_len) {
8125                 void __user **sense_ioc_ptr =
8126                         (void __user **)((u8 *)((unsigned long)&ioc->frame.raw) + local_sense_off);
8127                 compat_uptr_t *sense_cioc_ptr =
8128                         (compat_uptr_t *)(((unsigned long)&cioc->frame.raw) + user_sense_off);
8129                 if (get_user(ptr, sense_cioc_ptr) ||
8130                     put_user(compat_ptr(ptr), sense_ioc_ptr))
8131                         return -EFAULT;
8132         }
8133
8134         for (i = 0; i < MAX_IOCTL_SGE; i++) {
8135                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
8136                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
8137                     copy_in_user(&ioc->sgl[i].iov_len,
8138                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
8139                         return -EFAULT;
8140         }
8141
8142         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
8143
8144         if (copy_in_user(&cioc->frame.hdr.cmd_status,
8145                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
8146                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
8147                 return -EFAULT;
8148         }
8149         return error;
8150 }
8151
8152 static long
8153 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
8154                           unsigned long arg)
8155 {
8156         switch (cmd) {
8157         case MEGASAS_IOC_FIRMWARE32:
8158                 return megasas_mgmt_compat_ioctl_fw(file, arg);
8159         case MEGASAS_IOC_GET_AEN:
8160                 return megasas_mgmt_ioctl_aen(file, arg);
8161         }
8162
8163         return -ENOTTY;
8164 }
8165 #endif
8166
8167 /*
8168  * File operations structure for management interface
8169  */
8170 static const struct file_operations megasas_mgmt_fops = {
8171         .owner = THIS_MODULE,
8172         .open = megasas_mgmt_open,
8173         .fasync = megasas_mgmt_fasync,
8174         .unlocked_ioctl = megasas_mgmt_ioctl,
8175         .poll = megasas_mgmt_poll,
8176 #ifdef CONFIG_COMPAT
8177         .compat_ioctl = megasas_mgmt_compat_ioctl,
8178 #endif
8179         .llseek = noop_llseek,
8180 };
8181
8182 /*
8183  * PCI hotplug support registration structure
8184  */
8185 static struct pci_driver megasas_pci_driver = {
8186
8187         .name = "megaraid_sas",
8188         .id_table = megasas_pci_table,
8189         .probe = megasas_probe_one,
8190         .remove = megasas_detach_one,
8191         .suspend = megasas_suspend,
8192         .resume = megasas_resume,
8193         .shutdown = megasas_shutdown,
8194 };
8195
8196 /*
8197  * Sysfs driver attributes
8198  */
8199 static ssize_t version_show(struct device_driver *dd, char *buf)
8200 {
8201         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
8202                         MEGASAS_VERSION);
8203 }
8204 static DRIVER_ATTR_RO(version);
8205
8206 static ssize_t release_date_show(struct device_driver *dd, char *buf)
8207 {
8208         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
8209                 MEGASAS_RELDATE);
8210 }
8211 static DRIVER_ATTR_RO(release_date);
8212
8213 static ssize_t support_poll_for_event_show(struct device_driver *dd, char *buf)
8214 {
8215         return sprintf(buf, "%u\n", support_poll_for_event);
8216 }
8217 static DRIVER_ATTR_RO(support_poll_for_event);
8218
8219 static ssize_t support_device_change_show(struct device_driver *dd, char *buf)
8220 {
8221         return sprintf(buf, "%u\n", support_device_change);
8222 }
8223 static DRIVER_ATTR_RO(support_device_change);
8224
8225 static ssize_t dbg_lvl_show(struct device_driver *dd, char *buf)
8226 {
8227         return sprintf(buf, "%u\n", megasas_dbg_lvl);
8228 }
8229
8230 static ssize_t dbg_lvl_store(struct device_driver *dd, const char *buf,
8231                              size_t count)
8232 {
8233         int retval = count;
8234
8235         if (sscanf(buf, "%u", &megasas_dbg_lvl) < 1) {
8236                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
8237                 retval = -EINVAL;
8238         }
8239         return retval;
8240 }
8241 static DRIVER_ATTR_RW(dbg_lvl);
8242
8243 static ssize_t
8244 support_nvme_encapsulation_show(struct device_driver *dd, char *buf)
8245 {
8246         return sprintf(buf, "%u\n", support_nvme_encapsulation);
8247 }
8248
8249 static DRIVER_ATTR_RO(support_nvme_encapsulation);
8250
8251 static inline void megasas_remove_scsi_device(struct scsi_device *sdev)
8252 {
8253         sdev_printk(KERN_INFO, sdev, "SCSI device is removed\n");
8254         scsi_remove_device(sdev);
8255         scsi_device_put(sdev);
8256 }
8257
8258 /**
8259  * megasas_update_device_list - Update the PD and LD device list from FW
8260  *                              after an AEN event notification
8261  * @instance:                   Adapter soft state
8262  * @event_type:                 Indicates type of event (PD or LD event)
8263  *
8264  * @return:                     Success or failure
8265  *
8266  * Issue DCMDs to Firmware to update the internal device list in driver.
8267  * Based on the FW support, driver sends the HOST_DEVICE_LIST or combination
8268  * of PD_LIST/LD_LIST_QUERY DCMDs to get the device list.
8269  */
8270 static
8271 int megasas_update_device_list(struct megasas_instance *instance,
8272                                int event_type)
8273 {
8274         int dcmd_ret = DCMD_SUCCESS;
8275
8276         if (instance->enable_fw_dev_list) {
8277                 dcmd_ret = megasas_host_device_list_query(instance, false);
8278                 if (dcmd_ret != DCMD_SUCCESS)
8279                         goto out;
8280         } else {
8281                 if (event_type & SCAN_PD_CHANNEL) {
8282                         dcmd_ret = megasas_get_pd_list(instance);
8283
8284                         if (dcmd_ret != DCMD_SUCCESS)
8285                                 goto out;
8286                 }
8287
8288                 if (event_type & SCAN_VD_CHANNEL) {
8289                         if (!instance->requestorId ||
8290                             (instance->requestorId &&
8291                              megasas_get_ld_vf_affiliation(instance, 0))) {
8292                                 dcmd_ret = megasas_ld_list_query(instance,
8293                                                 MR_LD_QUERY_TYPE_EXPOSED_TO_HOST);
8294                                 if (dcmd_ret != DCMD_SUCCESS)
8295                                         goto out;
8296                         }
8297                 }
8298         }
8299
8300 out:
8301         return dcmd_ret;
8302 }
8303
8304 /**
8305  * megasas_add_remove_devices - Add/remove devices to SCSI mid-layer
8306  *                              after an AEN event notification
8307  * @instance:                   Adapter soft state
8308  * @scan_type:                  Indicates type of devices (PD/LD) to add
8309  * @return                      void
8310  */
8311 static
8312 void megasas_add_remove_devices(struct megasas_instance *instance,
8313                                 int scan_type)
8314 {
8315         int i, j;
8316         u16 pd_index = 0;
8317         u16 ld_index = 0;
8318         u16 channel = 0, id = 0;
8319         struct Scsi_Host *host;
8320         struct scsi_device *sdev1;
8321         struct MR_HOST_DEVICE_LIST *targetid_list = NULL;
8322         struct MR_HOST_DEVICE_LIST_ENTRY *targetid_entry = NULL;
8323
8324         host = instance->host;
8325
8326         if (instance->enable_fw_dev_list) {
8327                 targetid_list = instance->host_device_list_buf;
8328                 for (i = 0; i < targetid_list->count; i++) {
8329                         targetid_entry = &targetid_list->host_device_list[i];
8330                         if (targetid_entry->flags.u.bits.is_sys_pd) {
8331                                 channel = le16_to_cpu(targetid_entry->target_id) /
8332                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8333                                 id = le16_to_cpu(targetid_entry->target_id) %
8334                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8335                         } else {
8336                                 channel = MEGASAS_MAX_PD_CHANNELS +
8337                                           (le16_to_cpu(targetid_entry->target_id) /
8338                                            MEGASAS_MAX_DEV_PER_CHANNEL);
8339                                 id = le16_to_cpu(targetid_entry->target_id) %
8340                                                 MEGASAS_MAX_DEV_PER_CHANNEL;
8341                         }
8342                         sdev1 = scsi_device_lookup(host, channel, id, 0);
8343                         if (!sdev1) {
8344                                 scsi_add_device(host, channel, id, 0);
8345                         } else {
8346                                 scsi_device_put(sdev1);
8347                         }
8348                 }
8349         }
8350
8351         if (scan_type & SCAN_PD_CHANNEL) {
8352                 for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
8353                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8354                                 pd_index = i * MEGASAS_MAX_DEV_PER_CHANNEL + j;
8355                                 sdev1 = scsi_device_lookup(host, i, j, 0);
8356                                 if (instance->pd_list[pd_index].driveState ==
8357                                                         MR_PD_STATE_SYSTEM) {
8358                                         if (!sdev1)
8359                                                 scsi_add_device(host, i, j, 0);
8360                                         else
8361                                                 scsi_device_put(sdev1);
8362                                 } else {
8363                                         if (sdev1)
8364                                                 megasas_remove_scsi_device(sdev1);
8365                                 }
8366                         }
8367                 }
8368         }
8369
8370         if (scan_type & SCAN_VD_CHANNEL) {
8371                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
8372                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
8373                                 ld_index = (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
8374                                 sdev1 = scsi_device_lookup(host,
8375                                                 MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8376                                 if (instance->ld_ids[ld_index] != 0xff) {
8377                                         if (!sdev1)
8378                                                 scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
8379                                         else
8380                                                 scsi_device_put(sdev1);
8381                                 } else {
8382                                         if (sdev1)
8383                                                 megasas_remove_scsi_device(sdev1);
8384                                 }
8385                         }
8386                 }
8387         }
8388
8389 }
8390
8391 static void
8392 megasas_aen_polling(struct work_struct *work)
8393 {
8394         struct megasas_aen_event *ev =
8395                 container_of(work, struct megasas_aen_event, hotplug_work.work);
8396         struct megasas_instance *instance = ev->instance;
8397         union megasas_evt_class_locale class_locale;
8398         int event_type = 0;
8399         u32 seq_num, wait_time = MEGASAS_RESET_WAIT_TIME;
8400         int error;
8401         u8  dcmd_ret = DCMD_SUCCESS;
8402
8403         if (!instance) {
8404                 printk(KERN_ERR "invalid instance!\n");
8405                 kfree(ev);
8406                 return;
8407         }
8408
8409         /* Adjust event workqueue thread wait time for VF mode */
8410         if (instance->requestorId)
8411                 wait_time = MEGASAS_ROUTINE_WAIT_TIME_VF;
8412
8413         /* Don't run the event workqueue thread if OCR is running */
8414         mutex_lock(&instance->reset_mutex);
8415
8416         instance->ev = NULL;
8417         if (instance->evt_detail) {
8418                 megasas_decode_evt(instance);
8419
8420                 switch (le32_to_cpu(instance->evt_detail->code)) {
8421
8422                 case MR_EVT_PD_INSERTED:
8423                 case MR_EVT_PD_REMOVED:
8424                         event_type = SCAN_PD_CHANNEL;
8425                         break;
8426
8427                 case MR_EVT_LD_OFFLINE:
8428                 case MR_EVT_CFG_CLEARED:
8429                 case MR_EVT_LD_DELETED:
8430                 case MR_EVT_LD_CREATED:
8431                         event_type = SCAN_VD_CHANNEL;
8432                         break;
8433
8434                 case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
8435                 case MR_EVT_FOREIGN_CFG_IMPORTED:
8436                 case MR_EVT_LD_STATE_CHANGE:
8437                         event_type = SCAN_PD_CHANNEL | SCAN_VD_CHANNEL;
8438                         dev_info(&instance->pdev->dev, "scanning for scsi%d...\n",
8439                                 instance->host->host_no);
8440                         break;
8441
8442                 case MR_EVT_CTRL_PROP_CHANGED:
8443                         dcmd_ret = megasas_get_ctrl_info(instance);
8444                         if (dcmd_ret == DCMD_SUCCESS &&
8445                             instance->snapdump_wait_time) {
8446                                 megasas_get_snapdump_properties(instance);
8447                                 dev_info(&instance->pdev->dev,
8448                                          "Snap dump wait time\t: %d\n",
8449                                          instance->snapdump_wait_time);
8450                         }
8451                         break;
8452                 default:
8453                         event_type = 0;
8454                         break;
8455                 }
8456         } else {
8457                 dev_err(&instance->pdev->dev, "invalid evt_detail!\n");
8458                 mutex_unlock(&instance->reset_mutex);
8459                 kfree(ev);
8460                 return;
8461         }
8462
8463         if (event_type)
8464                 dcmd_ret = megasas_update_device_list(instance, event_type);
8465
8466         mutex_unlock(&instance->reset_mutex);
8467
8468         if (event_type && dcmd_ret == DCMD_SUCCESS)
8469                 megasas_add_remove_devices(instance, event_type);
8470
8471         if (dcmd_ret == DCMD_SUCCESS)
8472                 seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1;
8473         else
8474                 seq_num = instance->last_seq_num;
8475
8476         /* Register AEN with FW for latest sequence number plus 1 */
8477         class_locale.members.reserved = 0;
8478         class_locale.members.locale = MR_EVT_LOCALE_ALL;
8479         class_locale.members.class = MR_EVT_CLASS_DEBUG;
8480
8481         if (instance->aen_cmd != NULL) {
8482                 kfree(ev);
8483                 return;
8484         }
8485
8486         mutex_lock(&instance->reset_mutex);
8487         error = megasas_register_aen(instance, seq_num,
8488                                         class_locale.word);
8489         if (error)
8490                 dev_err(&instance->pdev->dev,
8491                         "register aen failed error %x\n", error);
8492
8493         mutex_unlock(&instance->reset_mutex);
8494         kfree(ev);
8495 }
8496
8497 /**
8498  * megasas_init - Driver load entry point
8499  */
8500 static int __init megasas_init(void)
8501 {
8502         int rval;
8503
8504         /*
8505          * Booted in kdump kernel, minimize memory footprints by
8506          * disabling few features
8507          */
8508         if (reset_devices) {
8509                 msix_vectors = 1;
8510                 rdpq_enable = 0;
8511                 dual_qdepth_disable = 1;
8512         }
8513
8514         /*
8515          * Announce driver version and other information
8516          */
8517         pr_info("megasas: %s\n", MEGASAS_VERSION);
8518
8519         spin_lock_init(&poll_aen_lock);
8520
8521         support_poll_for_event = 2;
8522         support_device_change = 1;
8523         support_nvme_encapsulation = true;
8524
8525         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
8526
8527         /*
8528          * Register character device node
8529          */
8530         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
8531
8532         if (rval < 0) {
8533                 printk(KERN_DEBUG "megasas: failed to open device node\n");
8534                 return rval;
8535         }
8536
8537         megasas_mgmt_majorno = rval;
8538
8539         /*
8540          * Register ourselves as PCI hotplug module
8541          */
8542         rval = pci_register_driver(&megasas_pci_driver);
8543
8544         if (rval) {
8545                 printk(KERN_DEBUG "megasas: PCI hotplug registration failed \n");
8546                 goto err_pcidrv;
8547         }
8548
8549         rval = driver_create_file(&megasas_pci_driver.driver,
8550                                   &driver_attr_version);
8551         if (rval)
8552                 goto err_dcf_attr_ver;
8553
8554         rval = driver_create_file(&megasas_pci_driver.driver,
8555                                   &driver_attr_release_date);
8556         if (rval)
8557                 goto err_dcf_rel_date;
8558
8559         rval = driver_create_file(&megasas_pci_driver.driver,
8560                                 &driver_attr_support_poll_for_event);
8561         if (rval)
8562                 goto err_dcf_support_poll_for_event;
8563
8564         rval = driver_create_file(&megasas_pci_driver.driver,
8565                                   &driver_attr_dbg_lvl);
8566         if (rval)
8567                 goto err_dcf_dbg_lvl;
8568         rval = driver_create_file(&megasas_pci_driver.driver,
8569                                 &driver_attr_support_device_change);
8570         if (rval)
8571                 goto err_dcf_support_device_change;
8572
8573         rval = driver_create_file(&megasas_pci_driver.driver,
8574                                   &driver_attr_support_nvme_encapsulation);
8575         if (rval)
8576                 goto err_dcf_support_nvme_encapsulation;
8577
8578         return rval;
8579
8580 err_dcf_support_nvme_encapsulation:
8581         driver_remove_file(&megasas_pci_driver.driver,
8582                            &driver_attr_support_device_change);
8583
8584 err_dcf_support_device_change:
8585         driver_remove_file(&megasas_pci_driver.driver,
8586                            &driver_attr_dbg_lvl);
8587 err_dcf_dbg_lvl:
8588         driver_remove_file(&megasas_pci_driver.driver,
8589                         &driver_attr_support_poll_for_event);
8590 err_dcf_support_poll_for_event:
8591         driver_remove_file(&megasas_pci_driver.driver,
8592                            &driver_attr_release_date);
8593 err_dcf_rel_date:
8594         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
8595 err_dcf_attr_ver:
8596         pci_unregister_driver(&megasas_pci_driver);
8597 err_pcidrv:
8598         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
8599         return rval;
8600 }
8601
8602 /**
8603  * megasas_exit - Driver unload entry point
8604  */
8605 static void __exit megasas_exit(void)
8606 {
8607         driver_remove_file(&megasas_pci_driver.driver,
8608                            &driver_attr_dbg_lvl);
8609         driver_remove_file(&megasas_pci_driver.driver,
8610                         &driver_attr_support_poll_for_event);
8611         driver_remove_file(&megasas_pci_driver.driver,
8612                         &driver_attr_support_device_change);
8613         driver_remove_file(&megasas_pci_driver.driver,
8614                            &driver_attr_release_date);
8615         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
8616         driver_remove_file(&megasas_pci_driver.driver,
8617                            &driver_attr_support_nvme_encapsulation);
8618
8619         pci_unregister_driver(&megasas_pci_driver);
8620         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
8621 }
8622
8623 module_init(megasas_init);
8624 module_exit(megasas_exit);