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