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