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