Merge SCSI misc branch into isci-for-3.6 tag
[firefly-linux-kernel-4.4.55.git] / drivers / scsi / megaraid / megaraid_sas_base.c
1 /*
2  *  Linux MegaRAID driver for SAS based RAID controllers
3  *
4  *  Copyright (c) 2009-2011  LSI Corporation.
5  *
6  *  This program is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU General Public License
8  *  as published by the Free Software Foundation; either version 2
9  *  of the License, or (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  *  FILE: megaraid_sas_base.c
21  *  Version : v00.00.06.18-rc1
22  *
23  *  Authors: LSI Corporation
24  *           Sreenivas Bagalkote
25  *           Sumant Patro
26  *           Bo Yang
27  *           Adam Radford <linuxraid@lsi.com>
28  *
29  *  Send feedback to: <megaraidlinux@lsi.com>
30  *
31  *  Mail to: LSI Corporation, 1621 Barber Lane, Milpitas, CA 95035
32  *     ATTN: Linuxraid
33  */
34
35 #include <linux/kernel.h>
36 #include <linux/types.h>
37 #include <linux/pci.h>
38 #include <linux/list.h>
39 #include <linux/moduleparam.h>
40 #include <linux/module.h>
41 #include <linux/spinlock.h>
42 #include <linux/interrupt.h>
43 #include <linux/delay.h>
44 #include <linux/uio.h>
45 #include <linux/slab.h>
46 #include <asm/uaccess.h>
47 #include <linux/fs.h>
48 #include <linux/compat.h>
49 #include <linux/blkdev.h>
50 #include <linux/mutex.h>
51 #include <linux/poll.h>
52
53 #include <scsi/scsi.h>
54 #include <scsi/scsi_cmnd.h>
55 #include <scsi/scsi_device.h>
56 #include <scsi/scsi_host.h>
57 #include <scsi/scsi_tcq.h>
58 #include "megaraid_sas_fusion.h"
59 #include "megaraid_sas.h"
60
61 /*
62  * Number of sectors per IO command
63  * Will be set in megasas_init_mfi if user does not provide
64  */
65 static unsigned int max_sectors;
66 module_param_named(max_sectors, max_sectors, int, 0);
67 MODULE_PARM_DESC(max_sectors,
68         "Maximum number of sectors per IO command");
69
70 static int msix_disable;
71 module_param(msix_disable, int, S_IRUGO);
72 MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
73
74 static int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH;
75 module_param(throttlequeuedepth, int, S_IRUGO);
76 MODULE_PARM_DESC(throttlequeuedepth,
77         "Adapter queue depth when throttled due to I/O timeout. Default: 16");
78
79 int resetwaittime = MEGASAS_RESET_WAIT_TIME;
80 module_param(resetwaittime, int, S_IRUGO);
81 MODULE_PARM_DESC(resetwaittime, "Wait time in seconds after I/O timeout "
82                  "before resetting adapter. Default: 180");
83
84 MODULE_LICENSE("GPL");
85 MODULE_VERSION(MEGASAS_VERSION);
86 MODULE_AUTHOR("megaraidlinux@lsi.com");
87 MODULE_DESCRIPTION("LSI MegaRAID SAS Driver");
88
89 int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
90 static int megasas_get_pd_list(struct megasas_instance *instance);
91 static int megasas_issue_init_mfi(struct megasas_instance *instance);
92 static int megasas_register_aen(struct megasas_instance *instance,
93                                 u32 seq_num, u32 class_locale_word);
94 /*
95  * PCI ID table for all supported controllers
96  */
97 static struct pci_device_id megasas_pci_table[] = {
98
99         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
100         /* xscale IOP */
101         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
102         /* ppc IOP */
103         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
104         /* ppc IOP */
105         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
106         /* gen2*/
107         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
108         /* gen2*/
109         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
110         /* skinny*/
111         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
112         /* skinny*/
113         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
114         /* xscale IOP, vega */
115         {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
116         /* xscale IOP */
117         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
118         /* Fusion */
119         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
120         /* Invader */
121         {}
122 };
123
124 MODULE_DEVICE_TABLE(pci, megasas_pci_table);
125
126 static int megasas_mgmt_majorno;
127 static struct megasas_mgmt_info megasas_mgmt_info;
128 static struct fasync_struct *megasas_async_queue;
129 static DEFINE_MUTEX(megasas_async_queue_mutex);
130
131 static int megasas_poll_wait_aen;
132 static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
133 static u32 support_poll_for_event;
134 u32 megasas_dbg_lvl;
135 static u32 support_device_change;
136
137 /* define lock for aen poll */
138 spinlock_t poll_aen_lock;
139
140 void
141 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
142                      u8 alt_status);
143 static u32
144 megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs);
145 static int
146 megasas_adp_reset_gen2(struct megasas_instance *instance,
147                        struct megasas_register_set __iomem *reg_set);
148 static irqreturn_t megasas_isr(int irq, void *devp);
149 static u32
150 megasas_init_adapter_mfi(struct megasas_instance *instance);
151 u32
152 megasas_build_and_issue_cmd(struct megasas_instance *instance,
153                             struct scsi_cmnd *scmd);
154 static void megasas_complete_cmd_dpc(unsigned long instance_addr);
155 void
156 megasas_release_fusion(struct megasas_instance *instance);
157 int
158 megasas_ioc_init_fusion(struct megasas_instance *instance);
159 void
160 megasas_free_cmds_fusion(struct megasas_instance *instance);
161 u8
162 megasas_get_map_info(struct megasas_instance *instance);
163 int
164 megasas_sync_map_info(struct megasas_instance *instance);
165 int
166 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd);
167 void megasas_reset_reply_desc(struct megasas_instance *instance);
168 u8 MR_ValidateMapInfo(struct MR_FW_RAID_MAP_ALL *map,
169                       struct LD_LOAD_BALANCE_INFO *lbInfo);
170 int megasas_reset_fusion(struct Scsi_Host *shost);
171 void megasas_fusion_ocr_wq(struct work_struct *work);
172
173 void
174 megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
175 {
176         instance->instancet->fire_cmd(instance,
177                 cmd->frame_phys_addr, 0, instance->reg_set);
178 }
179
180 /**
181  * megasas_get_cmd -    Get a command from the free pool
182  * @instance:           Adapter soft state
183  *
184  * Returns a free command from the pool
185  */
186 struct megasas_cmd *megasas_get_cmd(struct megasas_instance
187                                                   *instance)
188 {
189         unsigned long flags;
190         struct megasas_cmd *cmd = NULL;
191
192         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
193
194         if (!list_empty(&instance->cmd_pool)) {
195                 cmd = list_entry((&instance->cmd_pool)->next,
196                                  struct megasas_cmd, list);
197                 list_del_init(&cmd->list);
198         } else {
199                 printk(KERN_ERR "megasas: Command pool empty!\n");
200         }
201
202         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
203         return cmd;
204 }
205
206 /**
207  * megasas_return_cmd - Return a cmd to free command pool
208  * @instance:           Adapter soft state
209  * @cmd:                Command packet to be returned to free command pool
210  */
211 inline void
212 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
213 {
214         unsigned long flags;
215
216         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
217
218         cmd->scmd = NULL;
219         cmd->frame_count = 0;
220         if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
221             (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
222             (reset_devices))
223                 cmd->frame->hdr.cmd = MFI_CMD_INVALID;
224         list_add_tail(&cmd->list, &instance->cmd_pool);
225
226         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
227 }
228
229
230 /**
231 *       The following functions are defined for xscale
232 *       (deviceid : 1064R, PERC5) controllers
233 */
234
235 /**
236  * megasas_enable_intr_xscale - Enables interrupts
237  * @regs:                       MFI register set
238  */
239 static inline void
240 megasas_enable_intr_xscale(struct megasas_register_set __iomem * regs)
241 {
242         writel(0, &(regs)->outbound_intr_mask);
243
244         /* Dummy readl to force pci flush */
245         readl(&regs->outbound_intr_mask);
246 }
247
248 /**
249  * megasas_disable_intr_xscale -Disables interrupt
250  * @regs:                       MFI register set
251  */
252 static inline void
253 megasas_disable_intr_xscale(struct megasas_register_set __iomem * regs)
254 {
255         u32 mask = 0x1f;
256         writel(mask, &regs->outbound_intr_mask);
257         /* Dummy readl to force pci flush */
258         readl(&regs->outbound_intr_mask);
259 }
260
261 /**
262  * megasas_read_fw_status_reg_xscale - returns the current FW status value
263  * @regs:                       MFI register set
264  */
265 static u32
266 megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
267 {
268         return readl(&(regs)->outbound_msg_0);
269 }
270 /**
271  * megasas_clear_interrupt_xscale -     Check & clear interrupt
272  * @regs:                               MFI register set
273  */
274 static int
275 megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
276 {
277         u32 status;
278         u32 mfiStatus = 0;
279         /*
280          * Check if it is our interrupt
281          */
282         status = readl(&regs->outbound_intr_status);
283
284         if (status & MFI_OB_INTR_STATUS_MASK)
285                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
286         if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
287                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
288
289         /*
290          * Clear the interrupt by writing back the same value
291          */
292         if (mfiStatus)
293                 writel(status, &regs->outbound_intr_status);
294
295         /* Dummy readl to force pci flush */
296         readl(&regs->outbound_intr_status);
297
298         return mfiStatus;
299 }
300
301 /**
302  * megasas_fire_cmd_xscale -    Sends command to the FW
303  * @frame_phys_addr :           Physical address of cmd
304  * @frame_count :               Number of frames for the command
305  * @regs :                      MFI register set
306  */
307 static inline void
308 megasas_fire_cmd_xscale(struct megasas_instance *instance,
309                 dma_addr_t frame_phys_addr,
310                 u32 frame_count,
311                 struct megasas_register_set __iomem *regs)
312 {
313         unsigned long flags;
314         spin_lock_irqsave(&instance->hba_lock, flags);
315         writel((frame_phys_addr >> 3)|(frame_count),
316                &(regs)->inbound_queue_port);
317         spin_unlock_irqrestore(&instance->hba_lock, flags);
318 }
319
320 /**
321  * megasas_adp_reset_xscale -  For controller reset
322  * @regs:                              MFI register set
323  */
324 static int
325 megasas_adp_reset_xscale(struct megasas_instance *instance,
326         struct megasas_register_set __iomem *regs)
327 {
328         u32 i;
329         u32 pcidata;
330         writel(MFI_ADP_RESET, &regs->inbound_doorbell);
331
332         for (i = 0; i < 3; i++)
333                 msleep(1000); /* sleep for 3 secs */
334         pcidata  = 0;
335         pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
336         printk(KERN_NOTICE "pcidata = %x\n", pcidata);
337         if (pcidata & 0x2) {
338                 printk(KERN_NOTICE "mfi 1068 offset read=%x\n", pcidata);
339                 pcidata &= ~0x2;
340                 pci_write_config_dword(instance->pdev,
341                                 MFI_1068_PCSR_OFFSET, pcidata);
342
343                 for (i = 0; i < 2; i++)
344                         msleep(1000); /* need to wait 2 secs again */
345
346                 pcidata  = 0;
347                 pci_read_config_dword(instance->pdev,
348                                 MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
349                 printk(KERN_NOTICE "1068 offset handshake read=%x\n", pcidata);
350                 if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
351                         printk(KERN_NOTICE "1068 offset pcidt=%x\n", pcidata);
352                         pcidata = 0;
353                         pci_write_config_dword(instance->pdev,
354                                 MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
355                 }
356         }
357         return 0;
358 }
359
360 /**
361  * megasas_check_reset_xscale - For controller reset check
362  * @regs:                               MFI register set
363  */
364 static int
365 megasas_check_reset_xscale(struct megasas_instance *instance,
366                 struct megasas_register_set __iomem *regs)
367 {
368         u32 consumer;
369         consumer = *instance->consumer;
370
371         if ((instance->adprecovery != MEGASAS_HBA_OPERATIONAL) &&
372                 (*instance->consumer == MEGASAS_ADPRESET_INPROG_SIGN)) {
373                 return 1;
374         }
375         return 0;
376 }
377
378 static struct megasas_instance_template megasas_instance_template_xscale = {
379
380         .fire_cmd = megasas_fire_cmd_xscale,
381         .enable_intr = megasas_enable_intr_xscale,
382         .disable_intr = megasas_disable_intr_xscale,
383         .clear_intr = megasas_clear_intr_xscale,
384         .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
385         .adp_reset = megasas_adp_reset_xscale,
386         .check_reset = megasas_check_reset_xscale,
387         .service_isr = megasas_isr,
388         .tasklet = megasas_complete_cmd_dpc,
389         .init_adapter = megasas_init_adapter_mfi,
390         .build_and_issue_cmd = megasas_build_and_issue_cmd,
391         .issue_dcmd = megasas_issue_dcmd,
392 };
393
394 /**
395 *       This is the end of set of functions & definitions specific
396 *       to xscale (deviceid : 1064R, PERC5) controllers
397 */
398
399 /**
400 *       The following functions are defined for ppc (deviceid : 0x60)
401 *       controllers
402 */
403
404 /**
405  * megasas_enable_intr_ppc -    Enables interrupts
406  * @regs:                       MFI register set
407  */
408 static inline void
409 megasas_enable_intr_ppc(struct megasas_register_set __iomem * regs)
410 {
411         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
412
413         writel(~0x80000000, &(regs)->outbound_intr_mask);
414
415         /* Dummy readl to force pci flush */
416         readl(&regs->outbound_intr_mask);
417 }
418
419 /**
420  * megasas_disable_intr_ppc -   Disable interrupt
421  * @regs:                       MFI register set
422  */
423 static inline void
424 megasas_disable_intr_ppc(struct megasas_register_set __iomem * regs)
425 {
426         u32 mask = 0xFFFFFFFF;
427         writel(mask, &regs->outbound_intr_mask);
428         /* Dummy readl to force pci flush */
429         readl(&regs->outbound_intr_mask);
430 }
431
432 /**
433  * megasas_read_fw_status_reg_ppc - returns the current FW status value
434  * @regs:                       MFI register set
435  */
436 static u32
437 megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
438 {
439         return readl(&(regs)->outbound_scratch_pad);
440 }
441
442 /**
443  * megasas_clear_interrupt_ppc -        Check & clear interrupt
444  * @regs:                               MFI register set
445  */
446 static int
447 megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
448 {
449         u32 status, mfiStatus = 0;
450
451         /*
452          * Check if it is our interrupt
453          */
454         status = readl(&regs->outbound_intr_status);
455
456         if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
457                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
458
459         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
460                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
461
462         /*
463          * Clear the interrupt by writing back the same value
464          */
465         writel(status, &regs->outbound_doorbell_clear);
466
467         /* Dummy readl to force pci flush */
468         readl(&regs->outbound_doorbell_clear);
469
470         return mfiStatus;
471 }
472
473 /**
474  * megasas_fire_cmd_ppc -       Sends command to the FW
475  * @frame_phys_addr :           Physical address of cmd
476  * @frame_count :               Number of frames for the command
477  * @regs :                      MFI register set
478  */
479 static inline void
480 megasas_fire_cmd_ppc(struct megasas_instance *instance,
481                 dma_addr_t frame_phys_addr,
482                 u32 frame_count,
483                 struct megasas_register_set __iomem *regs)
484 {
485         unsigned long flags;
486         spin_lock_irqsave(&instance->hba_lock, flags);
487         writel((frame_phys_addr | (frame_count<<1))|1,
488                         &(regs)->inbound_queue_port);
489         spin_unlock_irqrestore(&instance->hba_lock, flags);
490 }
491
492 /**
493  * megasas_check_reset_ppc -    For controller reset check
494  * @regs:                               MFI register set
495  */
496 static int
497 megasas_check_reset_ppc(struct megasas_instance *instance,
498                         struct megasas_register_set __iomem *regs)
499 {
500         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
501                 return 1;
502
503         return 0;
504 }
505
506 static struct megasas_instance_template megasas_instance_template_ppc = {
507
508         .fire_cmd = megasas_fire_cmd_ppc,
509         .enable_intr = megasas_enable_intr_ppc,
510         .disable_intr = megasas_disable_intr_ppc,
511         .clear_intr = megasas_clear_intr_ppc,
512         .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
513         .adp_reset = megasas_adp_reset_xscale,
514         .check_reset = megasas_check_reset_ppc,
515         .service_isr = megasas_isr,
516         .tasklet = megasas_complete_cmd_dpc,
517         .init_adapter = megasas_init_adapter_mfi,
518         .build_and_issue_cmd = megasas_build_and_issue_cmd,
519         .issue_dcmd = megasas_issue_dcmd,
520 };
521
522 /**
523  * megasas_enable_intr_skinny - Enables interrupts
524  * @regs:                       MFI register set
525  */
526 static inline void
527 megasas_enable_intr_skinny(struct megasas_register_set __iomem *regs)
528 {
529         writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
530
531         writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
532
533         /* Dummy readl to force pci flush */
534         readl(&regs->outbound_intr_mask);
535 }
536
537 /**
538  * megasas_disable_intr_skinny -        Disables interrupt
539  * @regs:                       MFI register set
540  */
541 static inline void
542 megasas_disable_intr_skinny(struct megasas_register_set __iomem *regs)
543 {
544         u32 mask = 0xFFFFFFFF;
545         writel(mask, &regs->outbound_intr_mask);
546         /* Dummy readl to force pci flush */
547         readl(&regs->outbound_intr_mask);
548 }
549
550 /**
551  * megasas_read_fw_status_reg_skinny - returns the current FW status value
552  * @regs:                       MFI register set
553  */
554 static u32
555 megasas_read_fw_status_reg_skinny(struct megasas_register_set __iomem *regs)
556 {
557         return readl(&(regs)->outbound_scratch_pad);
558 }
559
560 /**
561  * megasas_clear_interrupt_skinny -     Check & clear interrupt
562  * @regs:                               MFI register set
563  */
564 static int
565 megasas_clear_intr_skinny(struct megasas_register_set __iomem *regs)
566 {
567         u32 status;
568         u32 mfiStatus = 0;
569
570         /*
571          * Check if it is our interrupt
572          */
573         status = readl(&regs->outbound_intr_status);
574
575         if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
576                 return 0;
577         }
578
579         /*
580          * Check if it is our interrupt
581          */
582         if ((megasas_read_fw_status_reg_gen2(regs) & MFI_STATE_MASK) ==
583             MFI_STATE_FAULT) {
584                 mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
585         } else
586                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
587
588         /*
589          * Clear the interrupt by writing back the same value
590          */
591         writel(status, &regs->outbound_intr_status);
592
593         /*
594         * dummy read to flush PCI
595         */
596         readl(&regs->outbound_intr_status);
597
598         return mfiStatus;
599 }
600
601 /**
602  * megasas_fire_cmd_skinny -    Sends command to the FW
603  * @frame_phys_addr :           Physical address of cmd
604  * @frame_count :               Number of frames for the command
605  * @regs :                      MFI register set
606  */
607 static inline void
608 megasas_fire_cmd_skinny(struct megasas_instance *instance,
609                         dma_addr_t frame_phys_addr,
610                         u32 frame_count,
611                         struct megasas_register_set __iomem *regs)
612 {
613         unsigned long flags;
614         spin_lock_irqsave(&instance->hba_lock, flags);
615         writel(0, &(regs)->inbound_high_queue_port);
616         writel((frame_phys_addr | (frame_count<<1))|1,
617                 &(regs)->inbound_low_queue_port);
618         spin_unlock_irqrestore(&instance->hba_lock, flags);
619 }
620
621 /**
622  * megasas_check_reset_skinny - For controller reset check
623  * @regs:                               MFI register set
624  */
625 static int
626 megasas_check_reset_skinny(struct megasas_instance *instance,
627                                 struct megasas_register_set __iomem *regs)
628 {
629         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
630                 return 1;
631
632         return 0;
633 }
634
635 static struct megasas_instance_template megasas_instance_template_skinny = {
636
637         .fire_cmd = megasas_fire_cmd_skinny,
638         .enable_intr = megasas_enable_intr_skinny,
639         .disable_intr = megasas_disable_intr_skinny,
640         .clear_intr = megasas_clear_intr_skinny,
641         .read_fw_status_reg = megasas_read_fw_status_reg_skinny,
642         .adp_reset = megasas_adp_reset_gen2,
643         .check_reset = megasas_check_reset_skinny,
644         .service_isr = megasas_isr,
645         .tasklet = megasas_complete_cmd_dpc,
646         .init_adapter = megasas_init_adapter_mfi,
647         .build_and_issue_cmd = megasas_build_and_issue_cmd,
648         .issue_dcmd = megasas_issue_dcmd,
649 };
650
651
652 /**
653 *       The following functions are defined for gen2 (deviceid : 0x78 0x79)
654 *       controllers
655 */
656
657 /**
658  * megasas_enable_intr_gen2 -  Enables interrupts
659  * @regs:                      MFI register set
660  */
661 static inline void
662 megasas_enable_intr_gen2(struct megasas_register_set __iomem *regs)
663 {
664         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
665
666         /* write ~0x00000005 (4 & 1) to the intr mask*/
667         writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
668
669         /* Dummy readl to force pci flush */
670         readl(&regs->outbound_intr_mask);
671 }
672
673 /**
674  * megasas_disable_intr_gen2 - Disables interrupt
675  * @regs:                      MFI register set
676  */
677 static inline void
678 megasas_disable_intr_gen2(struct megasas_register_set __iomem *regs)
679 {
680         u32 mask = 0xFFFFFFFF;
681         writel(mask, &regs->outbound_intr_mask);
682         /* Dummy readl to force pci flush */
683         readl(&regs->outbound_intr_mask);
684 }
685
686 /**
687  * megasas_read_fw_status_reg_gen2 - returns the current FW status value
688  * @regs:                      MFI register set
689  */
690 static u32
691 megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs)
692 {
693         return readl(&(regs)->outbound_scratch_pad);
694 }
695
696 /**
697  * megasas_clear_interrupt_gen2 -      Check & clear interrupt
698  * @regs:                              MFI register set
699  */
700 static int
701 megasas_clear_intr_gen2(struct megasas_register_set __iomem *regs)
702 {
703         u32 status;
704         u32 mfiStatus = 0;
705         /*
706          * Check if it is our interrupt
707          */
708         status = readl(&regs->outbound_intr_status);
709
710         if (status & MFI_GEN2_ENABLE_INTERRUPT_MASK) {
711                 mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
712         }
713         if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
714                 mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
715         }
716
717         /*
718          * Clear the interrupt by writing back the same value
719          */
720         if (mfiStatus)
721                 writel(status, &regs->outbound_doorbell_clear);
722
723         /* Dummy readl to force pci flush */
724         readl(&regs->outbound_intr_status);
725
726         return mfiStatus;
727 }
728 /**
729  * megasas_fire_cmd_gen2 -     Sends command to the FW
730  * @frame_phys_addr :          Physical address of cmd
731  * @frame_count :              Number of frames for the command
732  * @regs :                     MFI register set
733  */
734 static inline void
735 megasas_fire_cmd_gen2(struct megasas_instance *instance,
736                         dma_addr_t frame_phys_addr,
737                         u32 frame_count,
738                         struct megasas_register_set __iomem *regs)
739 {
740         unsigned long flags;
741         spin_lock_irqsave(&instance->hba_lock, flags);
742         writel((frame_phys_addr | (frame_count<<1))|1,
743                         &(regs)->inbound_queue_port);
744         spin_unlock_irqrestore(&instance->hba_lock, flags);
745 }
746
747 /**
748  * megasas_adp_reset_gen2 -     For controller reset
749  * @regs:                               MFI register set
750  */
751 static int
752 megasas_adp_reset_gen2(struct megasas_instance *instance,
753                         struct megasas_register_set __iomem *reg_set)
754 {
755         u32                     retry = 0 ;
756         u32                     HostDiag;
757         u32                     *seq_offset = &reg_set->seq_offset;
758         u32                     *hostdiag_offset = &reg_set->host_diag;
759
760         if (instance->instancet == &megasas_instance_template_skinny) {
761                 seq_offset = &reg_set->fusion_seq_offset;
762                 hostdiag_offset = &reg_set->fusion_host_diag;
763         }
764
765         writel(0, seq_offset);
766         writel(4, seq_offset);
767         writel(0xb, seq_offset);
768         writel(2, seq_offset);
769         writel(7, seq_offset);
770         writel(0xd, seq_offset);
771
772         msleep(1000);
773
774         HostDiag = (u32)readl(hostdiag_offset);
775
776         while ( !( HostDiag & DIAG_WRITE_ENABLE) ) {
777                 msleep(100);
778                 HostDiag = (u32)readl(hostdiag_offset);
779                 printk(KERN_NOTICE "RESETGEN2: retry=%x, hostdiag=%x\n",
780                                         retry, HostDiag);
781
782                 if (retry++ >= 100)
783                         return 1;
784
785         }
786
787         printk(KERN_NOTICE "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
788
789         writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
790
791         ssleep(10);
792
793         HostDiag = (u32)readl(hostdiag_offset);
794         while ( ( HostDiag & DIAG_RESET_ADAPTER) ) {
795                 msleep(100);
796                 HostDiag = (u32)readl(hostdiag_offset);
797                 printk(KERN_NOTICE "RESET_GEN2: retry=%x, hostdiag=%x\n",
798                                 retry, HostDiag);
799
800                 if (retry++ >= 1000)
801                         return 1;
802
803         }
804         return 0;
805 }
806
807 /**
808  * megasas_check_reset_gen2 -   For controller reset check
809  * @regs:                               MFI register set
810  */
811 static int
812 megasas_check_reset_gen2(struct megasas_instance *instance,
813                 struct megasas_register_set __iomem *regs)
814 {
815         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
816                 return 1;
817         }
818
819         return 0;
820 }
821
822 static struct megasas_instance_template megasas_instance_template_gen2 = {
823
824         .fire_cmd = megasas_fire_cmd_gen2,
825         .enable_intr = megasas_enable_intr_gen2,
826         .disable_intr = megasas_disable_intr_gen2,
827         .clear_intr = megasas_clear_intr_gen2,
828         .read_fw_status_reg = megasas_read_fw_status_reg_gen2,
829         .adp_reset = megasas_adp_reset_gen2,
830         .check_reset = megasas_check_reset_gen2,
831         .service_isr = megasas_isr,
832         .tasklet = megasas_complete_cmd_dpc,
833         .init_adapter = megasas_init_adapter_mfi,
834         .build_and_issue_cmd = megasas_build_and_issue_cmd,
835         .issue_dcmd = megasas_issue_dcmd,
836 };
837
838 /**
839 *       This is the end of set of functions & definitions
840 *       specific to gen2 (deviceid : 0x78, 0x79) controllers
841 */
842
843 /*
844  * Template added for TB (Fusion)
845  */
846 extern struct megasas_instance_template megasas_instance_template_fusion;
847
848 /**
849  * megasas_issue_polled -       Issues a polling command
850  * @instance:                   Adapter soft state
851  * @cmd:                        Command packet to be issued
852  *
853  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
854  */
855 int
856 megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
857 {
858
859         struct megasas_header *frame_hdr = &cmd->frame->hdr;
860
861         frame_hdr->cmd_status = 0xFF;
862         frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
863
864         /*
865          * Issue the frame using inbound queue port
866          */
867         instance->instancet->issue_dcmd(instance, cmd);
868
869         /*
870          * Wait for cmd_status to change
871          */
872         return wait_and_poll(instance, cmd);
873 }
874
875 /**
876  * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
877  * @instance:                   Adapter soft state
878  * @cmd:                        Command to be issued
879  *
880  * This function waits on an event for the command to be returned from ISR.
881  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
882  * Used to issue ioctl commands.
883  */
884 static int
885 megasas_issue_blocked_cmd(struct megasas_instance *instance,
886                           struct megasas_cmd *cmd)
887 {
888         cmd->cmd_status = ENODATA;
889
890         instance->instancet->issue_dcmd(instance, cmd);
891
892         wait_event(instance->int_cmd_wait_q, cmd->cmd_status != ENODATA);
893
894         return 0;
895 }
896
897 /**
898  * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
899  * @instance:                           Adapter soft state
900  * @cmd_to_abort:                       Previously issued cmd to be aborted
901  *
902  * MFI firmware can abort previously issued AEN command (automatic event
903  * notification). The megasas_issue_blocked_abort_cmd() issues such abort
904  * cmd and waits for return status.
905  * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
906  */
907 static int
908 megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
909                                 struct megasas_cmd *cmd_to_abort)
910 {
911         struct megasas_cmd *cmd;
912         struct megasas_abort_frame *abort_fr;
913
914         cmd = megasas_get_cmd(instance);
915
916         if (!cmd)
917                 return -1;
918
919         abort_fr = &cmd->frame->abort;
920
921         /*
922          * Prepare and issue the abort frame
923          */
924         abort_fr->cmd = MFI_CMD_ABORT;
925         abort_fr->cmd_status = 0xFF;
926         abort_fr->flags = 0;
927         abort_fr->abort_context = cmd_to_abort->index;
928         abort_fr->abort_mfi_phys_addr_lo = cmd_to_abort->frame_phys_addr;
929         abort_fr->abort_mfi_phys_addr_hi = 0;
930
931         cmd->sync_cmd = 1;
932         cmd->cmd_status = 0xFF;
933
934         instance->instancet->issue_dcmd(instance, cmd);
935
936         /*
937          * Wait for this cmd to complete
938          */
939         wait_event(instance->abort_cmd_wait_q, cmd->cmd_status != 0xFF);
940         cmd->sync_cmd = 0;
941
942         megasas_return_cmd(instance, cmd);
943         return 0;
944 }
945
946 /**
947  * megasas_make_sgl32 - Prepares 32-bit SGL
948  * @instance:           Adapter soft state
949  * @scp:                SCSI command from the mid-layer
950  * @mfi_sgl:            SGL to be filled in
951  *
952  * If successful, this function returns the number of SG elements. Otherwise,
953  * it returnes -1.
954  */
955 static int
956 megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
957                    union megasas_sgl *mfi_sgl)
958 {
959         int i;
960         int sge_count;
961         struct scatterlist *os_sgl;
962
963         sge_count = scsi_dma_map(scp);
964         BUG_ON(sge_count < 0);
965
966         if (sge_count) {
967                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
968                         mfi_sgl->sge32[i].length = sg_dma_len(os_sgl);
969                         mfi_sgl->sge32[i].phys_addr = sg_dma_address(os_sgl);
970                 }
971         }
972         return sge_count;
973 }
974
975 /**
976  * megasas_make_sgl64 - Prepares 64-bit SGL
977  * @instance:           Adapter soft state
978  * @scp:                SCSI command from the mid-layer
979  * @mfi_sgl:            SGL to be filled in
980  *
981  * If successful, this function returns the number of SG elements. Otherwise,
982  * it returnes -1.
983  */
984 static int
985 megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
986                    union megasas_sgl *mfi_sgl)
987 {
988         int i;
989         int sge_count;
990         struct scatterlist *os_sgl;
991
992         sge_count = scsi_dma_map(scp);
993         BUG_ON(sge_count < 0);
994
995         if (sge_count) {
996                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
997                         mfi_sgl->sge64[i].length = sg_dma_len(os_sgl);
998                         mfi_sgl->sge64[i].phys_addr = sg_dma_address(os_sgl);
999                 }
1000         }
1001         return sge_count;
1002 }
1003
1004 /**
1005  * megasas_make_sgl_skinny - Prepares IEEE SGL
1006  * @instance:           Adapter soft state
1007  * @scp:                SCSI command from the mid-layer
1008  * @mfi_sgl:            SGL to be filled in
1009  *
1010  * If successful, this function returns the number of SG elements. Otherwise,
1011  * it returnes -1.
1012  */
1013 static int
1014 megasas_make_sgl_skinny(struct megasas_instance *instance,
1015                 struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
1016 {
1017         int i;
1018         int sge_count;
1019         struct scatterlist *os_sgl;
1020
1021         sge_count = scsi_dma_map(scp);
1022
1023         if (sge_count) {
1024                 scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1025                         mfi_sgl->sge_skinny[i].length = sg_dma_len(os_sgl);
1026                         mfi_sgl->sge_skinny[i].phys_addr =
1027                                                 sg_dma_address(os_sgl);
1028                         mfi_sgl->sge_skinny[i].flag = 0;
1029                 }
1030         }
1031         return sge_count;
1032 }
1033
1034  /**
1035  * megasas_get_frame_count - Computes the number of frames
1036  * @frame_type          : type of frame- io or pthru frame
1037  * @sge_count           : number of sg elements
1038  *
1039  * Returns the number of frames required for numnber of sge's (sge_count)
1040  */
1041
1042 static u32 megasas_get_frame_count(struct megasas_instance *instance,
1043                         u8 sge_count, u8 frame_type)
1044 {
1045         int num_cnt;
1046         int sge_bytes;
1047         u32 sge_sz;
1048         u32 frame_count=0;
1049
1050         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1051             sizeof(struct megasas_sge32);
1052
1053         if (instance->flag_ieee) {
1054                 sge_sz = sizeof(struct megasas_sge_skinny);
1055         }
1056
1057         /*
1058          * Main frame can contain 2 SGEs for 64-bit SGLs and
1059          * 3 SGEs for 32-bit SGLs for ldio &
1060          * 1 SGEs for 64-bit SGLs and
1061          * 2 SGEs for 32-bit SGLs for pthru frame
1062          */
1063         if (unlikely(frame_type == PTHRU_FRAME)) {
1064                 if (instance->flag_ieee == 1) {
1065                         num_cnt = sge_count - 1;
1066                 } else if (IS_DMA64)
1067                         num_cnt = sge_count - 1;
1068                 else
1069                         num_cnt = sge_count - 2;
1070         } else {
1071                 if (instance->flag_ieee == 1) {
1072                         num_cnt = sge_count - 1;
1073                 } else if (IS_DMA64)
1074                         num_cnt = sge_count - 2;
1075                 else
1076                         num_cnt = sge_count - 3;
1077         }
1078
1079         if(num_cnt>0){
1080                 sge_bytes = sge_sz * num_cnt;
1081
1082                 frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
1083                     ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
1084         }
1085         /* Main frame */
1086         frame_count +=1;
1087
1088         if (frame_count > 7)
1089                 frame_count = 8;
1090         return frame_count;
1091 }
1092
1093 /**
1094  * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
1095  * @instance:           Adapter soft state
1096  * @scp:                SCSI command
1097  * @cmd:                Command to be prepared in
1098  *
1099  * This function prepares CDB commands. These are typcially pass-through
1100  * commands to the devices.
1101  */
1102 static int
1103 megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
1104                    struct megasas_cmd *cmd)
1105 {
1106         u32 is_logical;
1107         u32 device_id;
1108         u16 flags = 0;
1109         struct megasas_pthru_frame *pthru;
1110
1111         is_logical = MEGASAS_IS_LOGICAL(scp);
1112         device_id = MEGASAS_DEV_INDEX(instance, scp);
1113         pthru = (struct megasas_pthru_frame *)cmd->frame;
1114
1115         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1116                 flags = MFI_FRAME_DIR_WRITE;
1117         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1118                 flags = MFI_FRAME_DIR_READ;
1119         else if (scp->sc_data_direction == PCI_DMA_NONE)
1120                 flags = MFI_FRAME_DIR_NONE;
1121
1122         if (instance->flag_ieee == 1) {
1123                 flags |= MFI_FRAME_IEEE;
1124         }
1125
1126         /*
1127          * Prepare the DCDB frame
1128          */
1129         pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
1130         pthru->cmd_status = 0x0;
1131         pthru->scsi_status = 0x0;
1132         pthru->target_id = device_id;
1133         pthru->lun = scp->device->lun;
1134         pthru->cdb_len = scp->cmd_len;
1135         pthru->timeout = 0;
1136         pthru->pad_0 = 0;
1137         pthru->flags = flags;
1138         pthru->data_xfer_len = scsi_bufflen(scp);
1139
1140         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1141
1142         /*
1143         * If the command is for the tape device, set the
1144         * pthru timeout to the os layer timeout value.
1145         */
1146         if (scp->device->type == TYPE_TAPE) {
1147                 if ((scp->request->timeout / HZ) > 0xFFFF)
1148                         pthru->timeout = 0xFFFF;
1149                 else
1150                         pthru->timeout = scp->request->timeout / HZ;
1151         }
1152
1153         /*
1154          * Construct SGL
1155          */
1156         if (instance->flag_ieee == 1) {
1157                 pthru->flags |= MFI_FRAME_SGL64;
1158                 pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
1159                                                       &pthru->sgl);
1160         } else if (IS_DMA64) {
1161                 pthru->flags |= MFI_FRAME_SGL64;
1162                 pthru->sge_count = megasas_make_sgl64(instance, scp,
1163                                                       &pthru->sgl);
1164         } else
1165                 pthru->sge_count = megasas_make_sgl32(instance, scp,
1166                                                       &pthru->sgl);
1167
1168         if (pthru->sge_count > instance->max_num_sge) {
1169                 printk(KERN_ERR "megasas: DCDB two many SGE NUM=%x\n",
1170                         pthru->sge_count);
1171                 return 0;
1172         }
1173
1174         /*
1175          * Sense info specific
1176          */
1177         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
1178         pthru->sense_buf_phys_addr_hi = 0;
1179         pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
1180
1181         /*
1182          * Compute the total number of frames this command consumes. FW uses
1183          * this number to pull sufficient number of frames from host memory.
1184          */
1185         cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
1186                                                         PTHRU_FRAME);
1187
1188         return cmd->frame_count;
1189 }
1190
1191 /**
1192  * megasas_build_ldio - Prepares IOs to logical devices
1193  * @instance:           Adapter soft state
1194  * @scp:                SCSI command
1195  * @cmd:                Command to be prepared
1196  *
1197  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
1198  */
1199 static int
1200 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
1201                    struct megasas_cmd *cmd)
1202 {
1203         u32 device_id;
1204         u8 sc = scp->cmnd[0];
1205         u16 flags = 0;
1206         struct megasas_io_frame *ldio;
1207
1208         device_id = MEGASAS_DEV_INDEX(instance, scp);
1209         ldio = (struct megasas_io_frame *)cmd->frame;
1210
1211         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1212                 flags = MFI_FRAME_DIR_WRITE;
1213         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1214                 flags = MFI_FRAME_DIR_READ;
1215
1216         if (instance->flag_ieee == 1) {
1217                 flags |= MFI_FRAME_IEEE;
1218         }
1219
1220         /*
1221          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
1222          */
1223         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
1224         ldio->cmd_status = 0x0;
1225         ldio->scsi_status = 0x0;
1226         ldio->target_id = device_id;
1227         ldio->timeout = 0;
1228         ldio->reserved_0 = 0;
1229         ldio->pad_0 = 0;
1230         ldio->flags = flags;
1231         ldio->start_lba_hi = 0;
1232         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
1233
1234         /*
1235          * 6-byte READ(0x08) or WRITE(0x0A) cdb
1236          */
1237         if (scp->cmd_len == 6) {
1238                 ldio->lba_count = (u32) scp->cmnd[4];
1239                 ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) |
1240                     ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
1241
1242                 ldio->start_lba_lo &= 0x1FFFFF;
1243         }
1244
1245         /*
1246          * 10-byte READ(0x28) or WRITE(0x2A) cdb
1247          */
1248         else if (scp->cmd_len == 10) {
1249                 ldio->lba_count = (u32) scp->cmnd[8] |
1250                     ((u32) scp->cmnd[7] << 8);
1251                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
1252                     ((u32) scp->cmnd[3] << 16) |
1253                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
1254         }
1255
1256         /*
1257          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1258          */
1259         else if (scp->cmd_len == 12) {
1260                 ldio->lba_count = ((u32) scp->cmnd[6] << 24) |
1261                     ((u32) scp->cmnd[7] << 16) |
1262                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
1263
1264                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
1265                     ((u32) scp->cmnd[3] << 16) |
1266                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
1267         }
1268
1269         /*
1270          * 16-byte READ(0x88) or WRITE(0x8A) cdb
1271          */
1272         else if (scp->cmd_len == 16) {
1273                 ldio->lba_count = ((u32) scp->cmnd[10] << 24) |
1274                     ((u32) scp->cmnd[11] << 16) |
1275                     ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
1276
1277                 ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) |
1278                     ((u32) scp->cmnd[7] << 16) |
1279                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
1280
1281                 ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) |
1282                     ((u32) scp->cmnd[3] << 16) |
1283                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
1284
1285         }
1286
1287         /*
1288          * Construct SGL
1289          */
1290         if (instance->flag_ieee) {
1291                 ldio->flags |= MFI_FRAME_SGL64;
1292                 ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1293                                               &ldio->sgl);
1294         } else if (IS_DMA64) {
1295                 ldio->flags |= MFI_FRAME_SGL64;
1296                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1297         } else
1298                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1299
1300         if (ldio->sge_count > instance->max_num_sge) {
1301                 printk(KERN_ERR "megasas: build_ld_io: sge_count = %x\n",
1302                         ldio->sge_count);
1303                 return 0;
1304         }
1305
1306         /*
1307          * Sense info specific
1308          */
1309         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1310         ldio->sense_buf_phys_addr_hi = 0;
1311         ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
1312
1313         /*
1314          * Compute the total number of frames this command consumes. FW uses
1315          * this number to pull sufficient number of frames from host memory.
1316          */
1317         cmd->frame_count = megasas_get_frame_count(instance,
1318                         ldio->sge_count, IO_FRAME);
1319
1320         return cmd->frame_count;
1321 }
1322
1323 /**
1324  * megasas_is_ldio -            Checks if the cmd is for logical drive
1325  * @scmd:                       SCSI command
1326  *
1327  * Called by megasas_queue_command to find out if the command to be queued
1328  * is a logical drive command
1329  */
1330 inline int megasas_is_ldio(struct scsi_cmnd *cmd)
1331 {
1332         if (!MEGASAS_IS_LOGICAL(cmd))
1333                 return 0;
1334         switch (cmd->cmnd[0]) {
1335         case READ_10:
1336         case WRITE_10:
1337         case READ_12:
1338         case WRITE_12:
1339         case READ_6:
1340         case WRITE_6:
1341         case READ_16:
1342         case WRITE_16:
1343                 return 1;
1344         default:
1345                 return 0;
1346         }
1347 }
1348
1349  /**
1350  * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
1351  *                                      in FW
1352  * @instance:                           Adapter soft state
1353  */
1354 static inline void
1355 megasas_dump_pending_frames(struct megasas_instance *instance)
1356 {
1357         struct megasas_cmd *cmd;
1358         int i,n;
1359         union megasas_sgl *mfi_sgl;
1360         struct megasas_io_frame *ldio;
1361         struct megasas_pthru_frame *pthru;
1362         u32 sgcount;
1363         u32 max_cmd = instance->max_fw_cmds;
1364
1365         printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1366         printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1367         if (IS_DMA64)
1368                 printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1369         else
1370                 printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1371
1372         printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1373         for (i = 0; i < max_cmd; i++) {
1374                 cmd = instance->cmd_list[i];
1375                 if(!cmd->scmd)
1376                         continue;
1377                 printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1378                 if (megasas_is_ldio(cmd->scmd)){
1379                         ldio = (struct megasas_io_frame *)cmd->frame;
1380                         mfi_sgl = &ldio->sgl;
1381                         sgcount = ldio->sge_count;
1382                         printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no, cmd->frame_count,ldio->cmd,ldio->target_id, ldio->start_lba_lo,ldio->start_lba_hi,ldio->sense_buf_phys_addr_lo,sgcount);
1383                 }
1384                 else {
1385                         pthru = (struct megasas_pthru_frame *) cmd->frame;
1386                         mfi_sgl = &pthru->sgl;
1387                         sgcount = pthru->sge_count;
1388                         printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",instance->host->host_no,cmd->frame_count,pthru->cmd,pthru->target_id,pthru->lun,pthru->cdb_len , pthru->data_xfer_len,pthru->sense_buf_phys_addr_lo,sgcount);
1389                 }
1390         if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
1391                 for (n = 0; n < sgcount; n++){
1392                         if (IS_DMA64)
1393                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%08lx ",mfi_sgl->sge64[n].length , (unsigned long)mfi_sgl->sge64[n].phys_addr) ;
1394                         else
1395                                 printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",mfi_sgl->sge32[n].length , mfi_sgl->sge32[n].phys_addr) ;
1396                         }
1397                 }
1398                 printk(KERN_ERR "\n");
1399         } /*for max_cmd*/
1400         printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1401         for (i = 0; i < max_cmd; i++) {
1402
1403                 cmd = instance->cmd_list[i];
1404
1405                 if(cmd->sync_cmd == 1){
1406                         printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1407                 }
1408         }
1409         printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
1410 }
1411
1412 u32
1413 megasas_build_and_issue_cmd(struct megasas_instance *instance,
1414                             struct scsi_cmnd *scmd)
1415 {
1416         struct megasas_cmd *cmd;
1417         u32 frame_count;
1418
1419         cmd = megasas_get_cmd(instance);
1420         if (!cmd)
1421                 return SCSI_MLQUEUE_HOST_BUSY;
1422
1423         /*
1424          * Logical drive command
1425          */
1426         if (megasas_is_ldio(scmd))
1427                 frame_count = megasas_build_ldio(instance, scmd, cmd);
1428         else
1429                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
1430
1431         if (!frame_count)
1432                 goto out_return_cmd;
1433
1434         cmd->scmd = scmd;
1435         scmd->SCp.ptr = (char *)cmd;
1436
1437         /*
1438          * Issue the command to the FW
1439          */
1440         atomic_inc(&instance->fw_outstanding);
1441
1442         instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1443                                 cmd->frame_count-1, instance->reg_set);
1444
1445         return 0;
1446 out_return_cmd:
1447         megasas_return_cmd(instance, cmd);
1448         return 1;
1449 }
1450
1451
1452 /**
1453  * megasas_queue_command -      Queue entry point
1454  * @scmd:                       SCSI command to be queued
1455  * @done:                       Callback entry point
1456  */
1457 static int
1458 megasas_queue_command_lck(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
1459 {
1460         struct megasas_instance *instance;
1461         unsigned long flags;
1462
1463         instance = (struct megasas_instance *)
1464             scmd->device->host->hostdata;
1465
1466         if (instance->issuepend_done == 0)
1467                 return SCSI_MLQUEUE_HOST_BUSY;
1468
1469         spin_lock_irqsave(&instance->hba_lock, flags);
1470         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
1471                 spin_unlock_irqrestore(&instance->hba_lock, flags);
1472                 return SCSI_MLQUEUE_HOST_BUSY;
1473         }
1474
1475         spin_unlock_irqrestore(&instance->hba_lock, flags);
1476
1477         scmd->scsi_done = done;
1478         scmd->result = 0;
1479
1480         if (MEGASAS_IS_LOGICAL(scmd) &&
1481             (scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
1482                 scmd->result = DID_BAD_TARGET << 16;
1483                 goto out_done;
1484         }
1485
1486         switch (scmd->cmnd[0]) {
1487         case SYNCHRONIZE_CACHE:
1488                 /*
1489                  * FW takes care of flush cache on its own
1490                  * No need to send it down
1491                  */
1492                 scmd->result = DID_OK << 16;
1493                 goto out_done;
1494         default:
1495                 break;
1496         }
1497
1498         if (instance->instancet->build_and_issue_cmd(instance, scmd)) {
1499                 printk(KERN_ERR "megasas: Err returned from build_and_issue_cmd\n");
1500                 return SCSI_MLQUEUE_HOST_BUSY;
1501         }
1502
1503         return 0;
1504
1505  out_done:
1506         done(scmd);
1507         return 0;
1508 }
1509
1510 static DEF_SCSI_QCMD(megasas_queue_command)
1511
1512 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1513 {
1514         int i;
1515
1516         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1517
1518                 if ((megasas_mgmt_info.instance[i]) &&
1519                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1520                         return megasas_mgmt_info.instance[i];
1521         }
1522
1523         return NULL;
1524 }
1525
1526 static int megasas_slave_configure(struct scsi_device *sdev)
1527 {
1528         u16             pd_index = 0;
1529         struct  megasas_instance *instance ;
1530
1531         instance = megasas_lookup_instance(sdev->host->host_no);
1532
1533         /*
1534         * Don't export physical disk devices to the disk driver.
1535         *
1536         * FIXME: Currently we don't export them to the midlayer at all.
1537         *        That will be fixed once LSI engineers have audited the
1538         *        firmware for possible issues.
1539         */
1540         if (sdev->channel < MEGASAS_MAX_PD_CHANNELS &&
1541                                 sdev->type == TYPE_DISK) {
1542                 pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1543                                                                 sdev->id;
1544                 if (instance->pd_list[pd_index].driveState ==
1545                                                 MR_PD_STATE_SYSTEM) {
1546                         blk_queue_rq_timeout(sdev->request_queue,
1547                                 MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1548                         return 0;
1549                 }
1550                 return -ENXIO;
1551         }
1552
1553         /*
1554         * The RAID firmware may require extended timeouts.
1555         */
1556         blk_queue_rq_timeout(sdev->request_queue,
1557                 MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1558         return 0;
1559 }
1560
1561 static int megasas_slave_alloc(struct scsi_device *sdev)
1562 {
1563         u16             pd_index = 0;
1564         struct megasas_instance *instance ;
1565         instance = megasas_lookup_instance(sdev->host->host_no);
1566         if ((sdev->channel < MEGASAS_MAX_PD_CHANNELS) &&
1567                                 (sdev->type == TYPE_DISK)) {
1568                 /*
1569                  * Open the OS scan to the SYSTEM PD
1570                  */
1571                 pd_index =
1572                         (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1573                         sdev->id;
1574                 if ((instance->pd_list[pd_index].driveState ==
1575                                         MR_PD_STATE_SYSTEM) &&
1576                         (instance->pd_list[pd_index].driveType ==
1577                                                 TYPE_DISK)) {
1578                         return 0;
1579                 }
1580                 return -ENXIO;
1581         }
1582         return 0;
1583 }
1584
1585 void megaraid_sas_kill_hba(struct megasas_instance *instance)
1586 {
1587         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1588             (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
1589             (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
1590             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) {
1591                 writel(MFI_STOP_ADP, &instance->reg_set->doorbell);
1592         } else {
1593                 writel(MFI_STOP_ADP, &instance->reg_set->inbound_doorbell);
1594         }
1595 }
1596
1597  /**
1598   * megasas_check_and_restore_queue_depth - Check if queue depth needs to be
1599   *                                     restored to max value
1600   * @instance:                  Adapter soft state
1601   *
1602   */
1603 void
1604 megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
1605 {
1606         unsigned long flags;
1607         if (instance->flag & MEGASAS_FW_BUSY
1608             && time_after(jiffies, instance->last_time + 5 * HZ)
1609             && atomic_read(&instance->fw_outstanding) <
1610             instance->throttlequeuedepth + 1) {
1611
1612                 spin_lock_irqsave(instance->host->host_lock, flags);
1613                 instance->flag &= ~MEGASAS_FW_BUSY;
1614                 if ((instance->pdev->device ==
1615                         PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1616                         (instance->pdev->device ==
1617                         PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1618                         instance->host->can_queue =
1619                                 instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
1620                 } else
1621                         instance->host->can_queue =
1622                                 instance->max_fw_cmds - MEGASAS_INT_CMDS;
1623
1624                 spin_unlock_irqrestore(instance->host->host_lock, flags);
1625         }
1626 }
1627
1628 /**
1629  * megasas_complete_cmd_dpc      -      Returns FW's controller structure
1630  * @instance_addr:                      Address of adapter soft state
1631  *
1632  * Tasklet to complete cmds
1633  */
1634 static void megasas_complete_cmd_dpc(unsigned long instance_addr)
1635 {
1636         u32 producer;
1637         u32 consumer;
1638         u32 context;
1639         struct megasas_cmd *cmd;
1640         struct megasas_instance *instance =
1641                                 (struct megasas_instance *)instance_addr;
1642         unsigned long flags;
1643
1644         /* If we have already declared adapter dead, donot complete cmds */
1645         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR )
1646                 return;
1647
1648         spin_lock_irqsave(&instance->completion_lock, flags);
1649
1650         producer = *instance->producer;
1651         consumer = *instance->consumer;
1652
1653         while (consumer != producer) {
1654                 context = instance->reply_queue[consumer];
1655                 if (context >= instance->max_fw_cmds) {
1656                         printk(KERN_ERR "Unexpected context value %x\n",
1657                                 context);
1658                         BUG();
1659                 }
1660
1661                 cmd = instance->cmd_list[context];
1662
1663                 megasas_complete_cmd(instance, cmd, DID_OK);
1664
1665                 consumer++;
1666                 if (consumer == (instance->max_fw_cmds + 1)) {
1667                         consumer = 0;
1668                 }
1669         }
1670
1671         *instance->consumer = producer;
1672
1673         spin_unlock_irqrestore(&instance->completion_lock, flags);
1674
1675         /*
1676          * Check if we can restore can_queue
1677          */
1678         megasas_check_and_restore_queue_depth(instance);
1679 }
1680
1681 static void
1682 megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
1683
1684 static void
1685 process_fw_state_change_wq(struct work_struct *work);
1686
1687 void megasas_do_ocr(struct megasas_instance *instance)
1688 {
1689         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
1690         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
1691         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
1692                 *instance->consumer     = MEGASAS_ADPRESET_INPROG_SIGN;
1693         }
1694         instance->instancet->disable_intr(instance->reg_set);
1695         instance->adprecovery   = MEGASAS_ADPRESET_SM_INFAULT;
1696         instance->issuepend_done = 0;
1697
1698         atomic_set(&instance->fw_outstanding, 0);
1699         megasas_internal_reset_defer_cmds(instance);
1700         process_fw_state_change_wq(&instance->work_init);
1701 }
1702
1703 /**
1704  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
1705  * @instance:                           Adapter soft state
1706  *
1707  * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
1708  * complete all its outstanding commands. Returns error if one or more IOs
1709  * are pending after this time period. It also marks the controller dead.
1710  */
1711 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
1712 {
1713         int i;
1714         u32 reset_index;
1715         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
1716         u8 adprecovery;
1717         unsigned long flags;
1718         struct list_head clist_local;
1719         struct megasas_cmd *reset_cmd;
1720         u32 fw_state;
1721         u8 kill_adapter_flag;
1722
1723         spin_lock_irqsave(&instance->hba_lock, flags);
1724         adprecovery = instance->adprecovery;
1725         spin_unlock_irqrestore(&instance->hba_lock, flags);
1726
1727         if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
1728
1729                 INIT_LIST_HEAD(&clist_local);
1730                 spin_lock_irqsave(&instance->hba_lock, flags);
1731                 list_splice_init(&instance->internal_reset_pending_q,
1732                                 &clist_local);
1733                 spin_unlock_irqrestore(&instance->hba_lock, flags);
1734
1735                 printk(KERN_NOTICE "megasas: HBA reset wait ...\n");
1736                 for (i = 0; i < wait_time; i++) {
1737                         msleep(1000);
1738                         spin_lock_irqsave(&instance->hba_lock, flags);
1739                         adprecovery = instance->adprecovery;
1740                         spin_unlock_irqrestore(&instance->hba_lock, flags);
1741                         if (adprecovery == MEGASAS_HBA_OPERATIONAL)
1742                                 break;
1743                 }
1744
1745                 if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
1746                         printk(KERN_NOTICE "megasas: reset: Stopping HBA.\n");
1747                         spin_lock_irqsave(&instance->hba_lock, flags);
1748                         instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
1749                         spin_unlock_irqrestore(&instance->hba_lock, flags);
1750                         return FAILED;
1751                 }
1752
1753                 reset_index     = 0;
1754                 while (!list_empty(&clist_local)) {
1755                         reset_cmd       = list_entry((&clist_local)->next,
1756                                                 struct megasas_cmd, list);
1757                         list_del_init(&reset_cmd->list);
1758                         if (reset_cmd->scmd) {
1759                                 reset_cmd->scmd->result = DID_RESET << 16;
1760                                 printk(KERN_NOTICE "%d:%p reset [%02x]\n",
1761                                         reset_index, reset_cmd,
1762                                         reset_cmd->scmd->cmnd[0]);
1763
1764                                 reset_cmd->scmd->scsi_done(reset_cmd->scmd);
1765                                 megasas_return_cmd(instance, reset_cmd);
1766                         } else if (reset_cmd->sync_cmd) {
1767                                 printk(KERN_NOTICE "megasas:%p synch cmds"
1768                                                 "reset queue\n",
1769                                                 reset_cmd);
1770
1771                                 reset_cmd->cmd_status = ENODATA;
1772                                 instance->instancet->fire_cmd(instance,
1773                                                 reset_cmd->frame_phys_addr,
1774                                                 0, instance->reg_set);
1775                         } else {
1776                                 printk(KERN_NOTICE "megasas: %p unexpected"
1777                                         "cmds lst\n",
1778                                         reset_cmd);
1779                         }
1780                         reset_index++;
1781                 }
1782
1783                 return SUCCESS;
1784         }
1785
1786         for (i = 0; i < resetwaittime; i++) {
1787
1788                 int outstanding = atomic_read(&instance->fw_outstanding);
1789
1790                 if (!outstanding)
1791                         break;
1792
1793                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
1794                         printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
1795                                "commands to complete\n",i,outstanding);
1796                         /*
1797                          * Call cmd completion routine. Cmd to be
1798                          * be completed directly without depending on isr.
1799                          */
1800                         megasas_complete_cmd_dpc((unsigned long)instance);
1801                 }
1802
1803                 msleep(1000);
1804         }
1805
1806         i = 0;
1807         kill_adapter_flag = 0;
1808         do {
1809                 fw_state = instance->instancet->read_fw_status_reg(
1810                                         instance->reg_set) & MFI_STATE_MASK;
1811                 if ((fw_state == MFI_STATE_FAULT) &&
1812                         (instance->disableOnlineCtrlReset == 0)) {
1813                         if (i == 3) {
1814                                 kill_adapter_flag = 2;
1815                                 break;
1816                         }
1817                         megasas_do_ocr(instance);
1818                         kill_adapter_flag = 1;
1819
1820                         /* wait for 1 secs to let FW finish the pending cmds */
1821                         msleep(1000);
1822                 }
1823                 i++;
1824         } while (i <= 3);
1825
1826         if (atomic_read(&instance->fw_outstanding) &&
1827                                         !kill_adapter_flag) {
1828                 if (instance->disableOnlineCtrlReset == 0) {
1829
1830                         megasas_do_ocr(instance);
1831
1832                         /* wait for 5 secs to let FW finish the pending cmds */
1833                         for (i = 0; i < wait_time; i++) {
1834                                 int outstanding =
1835                                         atomic_read(&instance->fw_outstanding);
1836                                 if (!outstanding)
1837                                         return SUCCESS;
1838                                 msleep(1000);
1839                         }
1840                 }
1841         }
1842
1843         if (atomic_read(&instance->fw_outstanding) ||
1844                                         (kill_adapter_flag == 2)) {
1845                 printk(KERN_NOTICE "megaraid_sas: pending cmds after reset\n");
1846                 /*
1847                 * Send signal to FW to stop processing any pending cmds.
1848                 * The controller will be taken offline by the OS now.
1849                 */
1850                 if ((instance->pdev->device ==
1851                         PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1852                         (instance->pdev->device ==
1853                         PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
1854                         writel(MFI_STOP_ADP,
1855                                 &instance->reg_set->doorbell);
1856                 } else {
1857                         writel(MFI_STOP_ADP,
1858                                 &instance->reg_set->inbound_doorbell);
1859                 }
1860                 megasas_dump_pending_frames(instance);
1861                 spin_lock_irqsave(&instance->hba_lock, flags);
1862                 instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
1863                 spin_unlock_irqrestore(&instance->hba_lock, flags);
1864                 return FAILED;
1865         }
1866
1867         printk(KERN_NOTICE "megaraid_sas: no pending cmds after reset\n");
1868
1869         return SUCCESS;
1870 }
1871
1872 /**
1873  * megasas_generic_reset -      Generic reset routine
1874  * @scmd:                       Mid-layer SCSI command
1875  *
1876  * This routine implements a generic reset handler for device, bus and host
1877  * reset requests. Device, bus and host specific reset handlers can use this
1878  * function after they do their specific tasks.
1879  */
1880 static int megasas_generic_reset(struct scsi_cmnd *scmd)
1881 {
1882         int ret_val;
1883         struct megasas_instance *instance;
1884
1885         instance = (struct megasas_instance *)scmd->device->host->hostdata;
1886
1887         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
1888                  scmd->cmnd[0], scmd->retries);
1889
1890         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
1891                 printk(KERN_ERR "megasas: cannot recover from previous reset "
1892                        "failures\n");
1893                 return FAILED;
1894         }
1895
1896         ret_val = megasas_wait_for_outstanding(instance);
1897         if (ret_val == SUCCESS)
1898                 printk(KERN_NOTICE "megasas: reset successful \n");
1899         else
1900                 printk(KERN_ERR "megasas: failed to do reset\n");
1901
1902         return ret_val;
1903 }
1904
1905 /**
1906  * megasas_reset_timer - quiesce the adapter if required
1907  * @scmd:               scsi cmnd
1908  *
1909  * Sets the FW busy flag and reduces the host->can_queue if the
1910  * cmd has not been completed within the timeout period.
1911  */
1912 static enum
1913 blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
1914 {
1915         struct megasas_instance *instance;
1916         unsigned long flags;
1917
1918         if (time_after(jiffies, scmd->jiffies_at_alloc +
1919                                 (MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) {
1920                 return BLK_EH_NOT_HANDLED;
1921         }
1922
1923         instance = (struct megasas_instance *)scmd->device->host->hostdata;
1924         if (!(instance->flag & MEGASAS_FW_BUSY)) {
1925                 /* FW is busy, throttle IO */
1926                 spin_lock_irqsave(instance->host->host_lock, flags);
1927
1928                 instance->host->can_queue = instance->throttlequeuedepth;
1929                 instance->last_time = jiffies;
1930                 instance->flag |= MEGASAS_FW_BUSY;
1931
1932                 spin_unlock_irqrestore(instance->host->host_lock, flags);
1933         }
1934         return BLK_EH_RESET_TIMER;
1935 }
1936
1937 /**
1938  * megasas_reset_device -       Device reset handler entry point
1939  */
1940 static int megasas_reset_device(struct scsi_cmnd *scmd)
1941 {
1942         int ret;
1943
1944         /*
1945          * First wait for all commands to complete
1946          */
1947         ret = megasas_generic_reset(scmd);
1948
1949         return ret;
1950 }
1951
1952 /**
1953  * megasas_reset_bus_host -     Bus & host reset handler entry point
1954  */
1955 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
1956 {
1957         int ret;
1958         struct megasas_instance *instance;
1959         instance = (struct megasas_instance *)scmd->device->host->hostdata;
1960
1961         /*
1962          * First wait for all commands to complete
1963          */
1964         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
1965             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER))
1966                 ret = megasas_reset_fusion(scmd->device->host);
1967         else
1968                 ret = megasas_generic_reset(scmd);
1969
1970         return ret;
1971 }
1972
1973 /**
1974  * megasas_bios_param - Returns disk geometry for a disk
1975  * @sdev:               device handle
1976  * @bdev:               block device
1977  * @capacity:           drive capacity
1978  * @geom:               geometry parameters
1979  */
1980 static int
1981 megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
1982                  sector_t capacity, int geom[])
1983 {
1984         int heads;
1985         int sectors;
1986         sector_t cylinders;
1987         unsigned long tmp;
1988         /* Default heads (64) & sectors (32) */
1989         heads = 64;
1990         sectors = 32;
1991
1992         tmp = heads * sectors;
1993         cylinders = capacity;
1994
1995         sector_div(cylinders, tmp);
1996
1997         /*
1998          * Handle extended translation size for logical drives > 1Gb
1999          */
2000
2001         if (capacity >= 0x200000) {
2002                 heads = 255;
2003                 sectors = 63;
2004                 tmp = heads*sectors;
2005                 cylinders = capacity;
2006                 sector_div(cylinders, tmp);
2007         }
2008
2009         geom[0] = heads;
2010         geom[1] = sectors;
2011         geom[2] = cylinders;
2012
2013         return 0;
2014 }
2015
2016 static void megasas_aen_polling(struct work_struct *work);
2017
2018 /**
2019  * megasas_service_aen -        Processes an event notification
2020  * @instance:                   Adapter soft state
2021  * @cmd:                        AEN command completed by the ISR
2022  *
2023  * For AEN, driver sends a command down to FW that is held by the FW till an
2024  * event occurs. When an event of interest occurs, FW completes the command
2025  * that it was previously holding.
2026  *
2027  * This routines sends SIGIO signal to processes that have registered with the
2028  * driver for AEN.
2029  */
2030 static void
2031 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
2032 {
2033         unsigned long flags;
2034         /*
2035          * Don't signal app if it is just an aborted previously registered aen
2036          */
2037         if ((!cmd->abort_aen) && (instance->unload == 0)) {
2038                 spin_lock_irqsave(&poll_aen_lock, flags);
2039                 megasas_poll_wait_aen = 1;
2040                 spin_unlock_irqrestore(&poll_aen_lock, flags);
2041                 wake_up(&megasas_poll_wait);
2042                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
2043         }
2044         else
2045                 cmd->abort_aen = 0;
2046
2047         instance->aen_cmd = NULL;
2048         megasas_return_cmd(instance, cmd);
2049
2050         if ((instance->unload == 0) &&
2051                 ((instance->issuepend_done == 1))) {
2052                 struct megasas_aen_event *ev;
2053                 ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
2054                 if (!ev) {
2055                         printk(KERN_ERR "megasas_service_aen: out of memory\n");
2056                 } else {
2057                         ev->instance = instance;
2058                         instance->ev = ev;
2059                         INIT_WORK(&ev->hotplug_work, megasas_aen_polling);
2060                         schedule_delayed_work(
2061                                 (struct delayed_work *)&ev->hotplug_work, 0);
2062                 }
2063         }
2064 }
2065
2066 static int megasas_change_queue_depth(struct scsi_device *sdev,
2067                                       int queue_depth, int reason)
2068 {
2069         if (reason != SCSI_QDEPTH_DEFAULT)
2070                 return -EOPNOTSUPP;
2071
2072         if (queue_depth > sdev->host->can_queue)
2073                 queue_depth = sdev->host->can_queue;
2074         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev),
2075                                 queue_depth);
2076
2077         return queue_depth;
2078 }
2079
2080 /*
2081  * Scsi host template for megaraid_sas driver
2082  */
2083 static struct scsi_host_template megasas_template = {
2084
2085         .module = THIS_MODULE,
2086         .name = "LSI SAS based MegaRAID driver",
2087         .proc_name = "megaraid_sas",
2088         .slave_configure = megasas_slave_configure,
2089         .slave_alloc = megasas_slave_alloc,
2090         .queuecommand = megasas_queue_command,
2091         .eh_device_reset_handler = megasas_reset_device,
2092         .eh_bus_reset_handler = megasas_reset_bus_host,
2093         .eh_host_reset_handler = megasas_reset_bus_host,
2094         .eh_timed_out = megasas_reset_timer,
2095         .bios_param = megasas_bios_param,
2096         .use_clustering = ENABLE_CLUSTERING,
2097         .change_queue_depth = megasas_change_queue_depth,
2098 };
2099
2100 /**
2101  * megasas_complete_int_cmd -   Completes an internal command
2102  * @instance:                   Adapter soft state
2103  * @cmd:                        Command to be completed
2104  *
2105  * The megasas_issue_blocked_cmd() function waits for a command to complete
2106  * after it issues a command. This function wakes up that waiting routine by
2107  * calling wake_up() on the wait queue.
2108  */
2109 static void
2110 megasas_complete_int_cmd(struct megasas_instance *instance,
2111                          struct megasas_cmd *cmd)
2112 {
2113         cmd->cmd_status = cmd->frame->io.cmd_status;
2114
2115         if (cmd->cmd_status == ENODATA) {
2116                 cmd->cmd_status = 0;
2117         }
2118         wake_up(&instance->int_cmd_wait_q);
2119 }
2120
2121 /**
2122  * megasas_complete_abort -     Completes aborting a command
2123  * @instance:                   Adapter soft state
2124  * @cmd:                        Cmd that was issued to abort another cmd
2125  *
2126  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
2127  * after it issues an abort on a previously issued command. This function
2128  * wakes up all functions waiting on the same wait queue.
2129  */
2130 static void
2131 megasas_complete_abort(struct megasas_instance *instance,
2132                        struct megasas_cmd *cmd)
2133 {
2134         if (cmd->sync_cmd) {
2135                 cmd->sync_cmd = 0;
2136                 cmd->cmd_status = 0;
2137                 wake_up(&instance->abort_cmd_wait_q);
2138         }
2139
2140         return;
2141 }
2142
2143 /**
2144  * megasas_complete_cmd -       Completes a command
2145  * @instance:                   Adapter soft state
2146  * @cmd:                        Command to be completed
2147  * @alt_status:                 If non-zero, use this value as status to
2148  *                              SCSI mid-layer instead of the value returned
2149  *                              by the FW. This should be used if caller wants
2150  *                              an alternate status (as in the case of aborted
2151  *                              commands)
2152  */
2153 void
2154 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
2155                      u8 alt_status)
2156 {
2157         int exception = 0;
2158         struct megasas_header *hdr = &cmd->frame->hdr;
2159         unsigned long flags;
2160         struct fusion_context *fusion = instance->ctrl_context;
2161
2162         /* flag for the retry reset */
2163         cmd->retry_for_fw_reset = 0;
2164
2165         if (cmd->scmd)
2166                 cmd->scmd->SCp.ptr = NULL;
2167
2168         switch (hdr->cmd) {
2169         case MFI_CMD_INVALID:
2170                 /* Some older 1068 controller FW may keep a pended
2171                    MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
2172                    when booting the kdump kernel.  Ignore this command to
2173                    prevent a kernel panic on shutdown of the kdump kernel. */
2174                 printk(KERN_WARNING "megaraid_sas: MFI_CMD_INVALID command "
2175                        "completed.\n");
2176                 printk(KERN_WARNING "megaraid_sas: If you have a controller "
2177                        "other than PERC5, please upgrade your firmware.\n");
2178                 break;
2179         case MFI_CMD_PD_SCSI_IO:
2180         case MFI_CMD_LD_SCSI_IO:
2181
2182                 /*
2183                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
2184                  * issued either through an IO path or an IOCTL path. If it
2185                  * was via IOCTL, we will send it to internal completion.
2186                  */
2187                 if (cmd->sync_cmd) {
2188                         cmd->sync_cmd = 0;
2189                         megasas_complete_int_cmd(instance, cmd);
2190                         break;
2191                 }
2192
2193         case MFI_CMD_LD_READ:
2194         case MFI_CMD_LD_WRITE:
2195
2196                 if (alt_status) {
2197                         cmd->scmd->result = alt_status << 16;
2198                         exception = 1;
2199                 }
2200
2201                 if (exception) {
2202
2203                         atomic_dec(&instance->fw_outstanding);
2204
2205                         scsi_dma_unmap(cmd->scmd);
2206                         cmd->scmd->scsi_done(cmd->scmd);
2207                         megasas_return_cmd(instance, cmd);
2208
2209                         break;
2210                 }
2211
2212                 switch (hdr->cmd_status) {
2213
2214                 case MFI_STAT_OK:
2215                         cmd->scmd->result = DID_OK << 16;
2216                         break;
2217
2218                 case MFI_STAT_SCSI_IO_FAILED:
2219                 case MFI_STAT_LD_INIT_IN_PROGRESS:
2220                         cmd->scmd->result =
2221                             (DID_ERROR << 16) | hdr->scsi_status;
2222                         break;
2223
2224                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
2225
2226                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
2227
2228                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
2229                                 memset(cmd->scmd->sense_buffer, 0,
2230                                        SCSI_SENSE_BUFFERSIZE);
2231                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
2232                                        hdr->sense_len);
2233
2234                                 cmd->scmd->result |= DRIVER_SENSE << 24;
2235                         }
2236
2237                         break;
2238
2239                 case MFI_STAT_LD_OFFLINE:
2240                 case MFI_STAT_DEVICE_NOT_FOUND:
2241                         cmd->scmd->result = DID_BAD_TARGET << 16;
2242                         break;
2243
2244                 default:
2245                         printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
2246                                hdr->cmd_status);
2247                         cmd->scmd->result = DID_ERROR << 16;
2248                         break;
2249                 }
2250
2251                 atomic_dec(&instance->fw_outstanding);
2252
2253                 scsi_dma_unmap(cmd->scmd);
2254                 cmd->scmd->scsi_done(cmd->scmd);
2255                 megasas_return_cmd(instance, cmd);
2256
2257                 break;
2258
2259         case MFI_CMD_SMP:
2260         case MFI_CMD_STP:
2261         case MFI_CMD_DCMD:
2262                 /* Check for LD map update */
2263                 if ((cmd->frame->dcmd.opcode == MR_DCMD_LD_MAP_GET_INFO) &&
2264                     (cmd->frame->dcmd.mbox.b[1] == 1)) {
2265                         spin_lock_irqsave(instance->host->host_lock, flags);
2266                         if (cmd->frame->hdr.cmd_status != 0) {
2267                                 if (cmd->frame->hdr.cmd_status !=
2268                                     MFI_STAT_NOT_FOUND)
2269                                         printk(KERN_WARNING "megasas: map sync"
2270                                                "failed, status = 0x%x.\n",
2271                                                cmd->frame->hdr.cmd_status);
2272                                 else {
2273                                         megasas_return_cmd(instance, cmd);
2274                                         spin_unlock_irqrestore(
2275                                                 instance->host->host_lock,
2276                                                 flags);
2277                                         break;
2278                                 }
2279                         } else
2280                                 instance->map_id++;
2281                         megasas_return_cmd(instance, cmd);
2282                         if (MR_ValidateMapInfo(
2283                                     fusion->ld_map[(instance->map_id & 1)],
2284                                     fusion->load_balance_info))
2285                                 fusion->fast_path_io = 1;
2286                         else
2287                                 fusion->fast_path_io = 0;
2288                         megasas_sync_map_info(instance);
2289                         spin_unlock_irqrestore(instance->host->host_lock,
2290                                                flags);
2291                         break;
2292                 }
2293                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
2294                         cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_GET) {
2295                         spin_lock_irqsave(&poll_aen_lock, flags);
2296                         megasas_poll_wait_aen = 0;
2297                         spin_unlock_irqrestore(&poll_aen_lock, flags);
2298                 }
2299
2300                 /*
2301                  * See if got an event notification
2302                  */
2303                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
2304                         megasas_service_aen(instance, cmd);
2305                 else
2306                         megasas_complete_int_cmd(instance, cmd);
2307
2308                 break;
2309
2310         case MFI_CMD_ABORT:
2311                 /*
2312                  * Cmd issued to abort another cmd returned
2313                  */
2314                 megasas_complete_abort(instance, cmd);
2315                 break;
2316
2317         default:
2318                 printk("megasas: Unknown command completed! [0x%X]\n",
2319                        hdr->cmd);
2320                 break;
2321         }
2322 }
2323
2324 /**
2325  * megasas_issue_pending_cmds_again -   issue all pending cmds
2326  *                                      in FW again because of the fw reset
2327  * @instance:                           Adapter soft state
2328  */
2329 static inline void
2330 megasas_issue_pending_cmds_again(struct megasas_instance *instance)
2331 {
2332         struct megasas_cmd *cmd;
2333         struct list_head clist_local;
2334         union megasas_evt_class_locale class_locale;
2335         unsigned long flags;
2336         u32 seq_num;
2337
2338         INIT_LIST_HEAD(&clist_local);
2339         spin_lock_irqsave(&instance->hba_lock, flags);
2340         list_splice_init(&instance->internal_reset_pending_q, &clist_local);
2341         spin_unlock_irqrestore(&instance->hba_lock, flags);
2342
2343         while (!list_empty(&clist_local)) {
2344                 cmd     = list_entry((&clist_local)->next,
2345                                         struct megasas_cmd, list);
2346                 list_del_init(&cmd->list);
2347
2348                 if (cmd->sync_cmd || cmd->scmd) {
2349                         printk(KERN_NOTICE "megaraid_sas: command %p, %p:%d"
2350                                 "detected to be pending while HBA reset.\n",
2351                                         cmd, cmd->scmd, cmd->sync_cmd);
2352
2353                         cmd->retry_for_fw_reset++;
2354
2355                         if (cmd->retry_for_fw_reset == 3) {
2356                                 printk(KERN_NOTICE "megaraid_sas: cmd %p, %p:%d"
2357                                         "was tried multiple times during reset."
2358                                         "Shutting down the HBA\n",
2359                                         cmd, cmd->scmd, cmd->sync_cmd);
2360                                 megaraid_sas_kill_hba(instance);
2361
2362                                 instance->adprecovery =
2363                                                 MEGASAS_HW_CRITICAL_ERROR;
2364                                 return;
2365                         }
2366                 }
2367
2368                 if (cmd->sync_cmd == 1) {
2369                         if (cmd->scmd) {
2370                                 printk(KERN_NOTICE "megaraid_sas: unexpected"
2371                                         "cmd attached to internal command!\n");
2372                         }
2373                         printk(KERN_NOTICE "megasas: %p synchronous cmd"
2374                                                 "on the internal reset queue,"
2375                                                 "issue it again.\n", cmd);
2376                         cmd->cmd_status = ENODATA;
2377                         instance->instancet->fire_cmd(instance,
2378                                                         cmd->frame_phys_addr ,
2379                                                         0, instance->reg_set);
2380                 } else if (cmd->scmd) {
2381                         printk(KERN_NOTICE "megasas: %p scsi cmd [%02x]"
2382                         "detected on the internal queue, issue again.\n",
2383                         cmd, cmd->scmd->cmnd[0]);
2384
2385                         atomic_inc(&instance->fw_outstanding);
2386                         instance->instancet->fire_cmd(instance,
2387                                         cmd->frame_phys_addr,
2388                                         cmd->frame_count-1, instance->reg_set);
2389                 } else {
2390                         printk(KERN_NOTICE "megasas: %p unexpected cmd on the"
2391                                 "internal reset defer list while re-issue!!\n",
2392                                 cmd);
2393                 }
2394         }
2395
2396         if (instance->aen_cmd) {
2397                 printk(KERN_NOTICE "megaraid_sas: aen_cmd in def process\n");
2398                 megasas_return_cmd(instance, instance->aen_cmd);
2399
2400                 instance->aen_cmd       = NULL;
2401         }
2402
2403         /*
2404         * Initiate AEN (Asynchronous Event Notification)
2405         */
2406         seq_num = instance->last_seq_num;
2407         class_locale.members.reserved = 0;
2408         class_locale.members.locale = MR_EVT_LOCALE_ALL;
2409         class_locale.members.class = MR_EVT_CLASS_DEBUG;
2410
2411         megasas_register_aen(instance, seq_num, class_locale.word);
2412 }
2413
2414 /**
2415  * Move the internal reset pending commands to a deferred queue.
2416  *
2417  * We move the commands pending at internal reset time to a
2418  * pending queue. This queue would be flushed after successful
2419  * completion of the internal reset sequence. if the internal reset
2420  * did not complete in time, the kernel reset handler would flush
2421  * these commands.
2422  **/
2423 static void
2424 megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
2425 {
2426         struct megasas_cmd *cmd;
2427         int i;
2428         u32 max_cmd = instance->max_fw_cmds;
2429         u32 defer_index;
2430         unsigned long flags;
2431
2432         defer_index     = 0;
2433         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
2434         for (i = 0; i < max_cmd; i++) {
2435                 cmd = instance->cmd_list[i];
2436                 if (cmd->sync_cmd == 1 || cmd->scmd) {
2437                         printk(KERN_NOTICE "megasas: moving cmd[%d]:%p:%d:%p"
2438                                         "on the defer queue as internal\n",
2439                                 defer_index, cmd, cmd->sync_cmd, cmd->scmd);
2440
2441                         if (!list_empty(&cmd->list)) {
2442                                 printk(KERN_NOTICE "megaraid_sas: ERROR while"
2443                                         " moving this cmd:%p, %d %p, it was"
2444                                         "discovered on some list?\n",
2445                                         cmd, cmd->sync_cmd, cmd->scmd);
2446
2447                                 list_del_init(&cmd->list);
2448                         }
2449                         defer_index++;
2450                         list_add_tail(&cmd->list,
2451                                 &instance->internal_reset_pending_q);
2452                 }
2453         }
2454         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
2455 }
2456
2457
2458 static void
2459 process_fw_state_change_wq(struct work_struct *work)
2460 {
2461         struct megasas_instance *instance =
2462                 container_of(work, struct megasas_instance, work_init);
2463         u32 wait;
2464         unsigned long flags;
2465
2466         if (instance->adprecovery != MEGASAS_ADPRESET_SM_INFAULT) {
2467                 printk(KERN_NOTICE "megaraid_sas: error, recovery st %x \n",
2468                                 instance->adprecovery);
2469                 return ;
2470         }
2471
2472         if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) {
2473                 printk(KERN_NOTICE "megaraid_sas: FW detected to be in fault"
2474                                         "state, restarting it...\n");
2475
2476                 instance->instancet->disable_intr(instance->reg_set);
2477                 atomic_set(&instance->fw_outstanding, 0);
2478
2479                 atomic_set(&instance->fw_reset_no_pci_access, 1);
2480                 instance->instancet->adp_reset(instance, instance->reg_set);
2481                 atomic_set(&instance->fw_reset_no_pci_access, 0 );
2482
2483                 printk(KERN_NOTICE "megaraid_sas: FW restarted successfully,"
2484                                         "initiating next stage...\n");
2485
2486                 printk(KERN_NOTICE "megaraid_sas: HBA recovery state machine,"
2487                                         "state 2 starting...\n");
2488
2489                 /*waitting for about 20 second before start the second init*/
2490                 for (wait = 0; wait < 30; wait++) {
2491                         msleep(1000);
2492                 }
2493
2494                 if (megasas_transition_to_ready(instance, 1)) {
2495                         printk(KERN_NOTICE "megaraid_sas:adapter not ready\n");
2496
2497                         megaraid_sas_kill_hba(instance);
2498                         instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
2499                         return ;
2500                 }
2501
2502                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
2503                         (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
2504                         (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
2505                         ) {
2506                         *instance->consumer = *instance->producer;
2507                 } else {
2508                         *instance->consumer = 0;
2509                         *instance->producer = 0;
2510                 }
2511
2512                 megasas_issue_init_mfi(instance);
2513
2514                 spin_lock_irqsave(&instance->hba_lock, flags);
2515                 instance->adprecovery   = MEGASAS_HBA_OPERATIONAL;
2516                 spin_unlock_irqrestore(&instance->hba_lock, flags);
2517                 instance->instancet->enable_intr(instance->reg_set);
2518
2519                 megasas_issue_pending_cmds_again(instance);
2520                 instance->issuepend_done = 1;
2521         }
2522         return ;
2523 }
2524
2525 /**
2526  * megasas_deplete_reply_queue -        Processes all completed commands
2527  * @instance:                           Adapter soft state
2528  * @alt_status:                         Alternate status to be returned to
2529  *                                      SCSI mid-layer instead of the status
2530  *                                      returned by the FW
2531  * Note: this must be called with hba lock held
2532  */
2533 static int
2534 megasas_deplete_reply_queue(struct megasas_instance *instance,
2535                                         u8 alt_status)
2536 {
2537         u32 mfiStatus;
2538         u32 fw_state;
2539
2540         if ((mfiStatus = instance->instancet->check_reset(instance,
2541                                         instance->reg_set)) == 1) {
2542                 return IRQ_HANDLED;
2543         }
2544
2545         if ((mfiStatus = instance->instancet->clear_intr(
2546                                                 instance->reg_set)
2547                                                 ) == 0) {
2548                 /* Hardware may not set outbound_intr_status in MSI-X mode */
2549                 if (!instance->msix_vectors)
2550                         return IRQ_NONE;
2551         }
2552
2553         instance->mfiStatus = mfiStatus;
2554
2555         if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
2556                 fw_state = instance->instancet->read_fw_status_reg(
2557                                 instance->reg_set) & MFI_STATE_MASK;
2558
2559                 if (fw_state != MFI_STATE_FAULT) {
2560                         printk(KERN_NOTICE "megaraid_sas: fw state:%x\n",
2561                                                 fw_state);
2562                 }
2563
2564                 if ((fw_state == MFI_STATE_FAULT) &&
2565                                 (instance->disableOnlineCtrlReset == 0)) {
2566                         printk(KERN_NOTICE "megaraid_sas: wait adp restart\n");
2567
2568                         if ((instance->pdev->device ==
2569                                         PCI_DEVICE_ID_LSI_SAS1064R) ||
2570                                 (instance->pdev->device ==
2571                                         PCI_DEVICE_ID_DELL_PERC5) ||
2572                                 (instance->pdev->device ==
2573                                         PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
2574
2575                                 *instance->consumer =
2576                                         MEGASAS_ADPRESET_INPROG_SIGN;
2577                         }
2578
2579
2580                         instance->instancet->disable_intr(instance->reg_set);
2581                         instance->adprecovery   = MEGASAS_ADPRESET_SM_INFAULT;
2582                         instance->issuepend_done = 0;
2583
2584                         atomic_set(&instance->fw_outstanding, 0);
2585                         megasas_internal_reset_defer_cmds(instance);
2586
2587                         printk(KERN_NOTICE "megasas: fwState=%x, stage:%d\n",
2588                                         fw_state, instance->adprecovery);
2589
2590                         schedule_work(&instance->work_init);
2591                         return IRQ_HANDLED;
2592
2593                 } else {
2594                         printk(KERN_NOTICE "megasas: fwstate:%x, dis_OCR=%x\n",
2595                                 fw_state, instance->disableOnlineCtrlReset);
2596                 }
2597         }
2598
2599         tasklet_schedule(&instance->isr_tasklet);
2600         return IRQ_HANDLED;
2601 }
2602 /**
2603  * megasas_isr - isr entry point
2604  */
2605 static irqreturn_t megasas_isr(int irq, void *devp)
2606 {
2607         struct megasas_irq_context *irq_context = devp;
2608         struct megasas_instance *instance = irq_context->instance;
2609         unsigned long flags;
2610         irqreturn_t     rc;
2611
2612         if (atomic_read(&instance->fw_reset_no_pci_access))
2613                 return IRQ_HANDLED;
2614
2615         spin_lock_irqsave(&instance->hba_lock, flags);
2616         rc =  megasas_deplete_reply_queue(instance, DID_OK);
2617         spin_unlock_irqrestore(&instance->hba_lock, flags);
2618
2619         return rc;
2620 }
2621
2622 /**
2623  * megasas_transition_to_ready -        Move the FW to READY state
2624  * @instance:                           Adapter soft state
2625  *
2626  * During the initialization, FW passes can potentially be in any one of
2627  * several possible states. If the FW in operational, waiting-for-handshake
2628  * states, driver must take steps to bring it to ready state. Otherwise, it
2629  * has to wait for the ready state.
2630  */
2631 int
2632 megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
2633 {
2634         int i;
2635         u8 max_wait;
2636         u32 fw_state;
2637         u32 cur_state;
2638         u32 abs_state, curr_abs_state;
2639
2640         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
2641
2642         if (fw_state != MFI_STATE_READY)
2643                 printk(KERN_INFO "megasas: Waiting for FW to come to ready"
2644                        " state\n");
2645
2646         while (fw_state != MFI_STATE_READY) {
2647
2648                 abs_state =
2649                 instance->instancet->read_fw_status_reg(instance->reg_set);
2650
2651                 switch (fw_state) {
2652
2653                 case MFI_STATE_FAULT:
2654                         printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
2655                         if (ocr) {
2656                                 max_wait = MEGASAS_RESET_WAIT_TIME;
2657                                 cur_state = MFI_STATE_FAULT;
2658                                 break;
2659                         } else
2660                                 return -ENODEV;
2661
2662                 case MFI_STATE_WAIT_HANDSHAKE:
2663                         /*
2664                          * Set the CLR bit in inbound doorbell
2665                          */
2666                         if ((instance->pdev->device ==
2667                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2668                                 (instance->pdev->device ==
2669                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
2670                                 (instance->pdev->device ==
2671                                  PCI_DEVICE_ID_LSI_FUSION) ||
2672                                 (instance->pdev->device ==
2673                                 PCI_DEVICE_ID_LSI_INVADER)) {
2674                                 writel(
2675                                   MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
2676                                   &instance->reg_set->doorbell);
2677                         } else {
2678                                 writel(
2679                                     MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
2680                                         &instance->reg_set->inbound_doorbell);
2681                         }
2682
2683                         max_wait = MEGASAS_RESET_WAIT_TIME;
2684                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
2685                         break;
2686
2687                 case MFI_STATE_BOOT_MESSAGE_PENDING:
2688                         if ((instance->pdev->device ==
2689                              PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2690                                 (instance->pdev->device ==
2691                                  PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
2692                             (instance->pdev->device ==
2693                              PCI_DEVICE_ID_LSI_FUSION) ||
2694                             (instance->pdev->device ==
2695                              PCI_DEVICE_ID_LSI_INVADER)) {
2696                                 writel(MFI_INIT_HOTPLUG,
2697                                        &instance->reg_set->doorbell);
2698                         } else
2699                                 writel(MFI_INIT_HOTPLUG,
2700                                         &instance->reg_set->inbound_doorbell);
2701
2702                         max_wait = MEGASAS_RESET_WAIT_TIME;
2703                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
2704                         break;
2705
2706                 case MFI_STATE_OPERATIONAL:
2707                         /*
2708                          * Bring it to READY state; assuming max wait 10 secs
2709                          */
2710                         instance->instancet->disable_intr(instance->reg_set);
2711                         if ((instance->pdev->device ==
2712                                 PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2713                                 (instance->pdev->device ==
2714                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
2715                                 (instance->pdev->device
2716                                         == PCI_DEVICE_ID_LSI_FUSION) ||
2717                                 (instance->pdev->device
2718                                         == PCI_DEVICE_ID_LSI_INVADER)) {
2719                                 writel(MFI_RESET_FLAGS,
2720                                         &instance->reg_set->doorbell);
2721                                 if ((instance->pdev->device ==
2722                                     PCI_DEVICE_ID_LSI_FUSION) ||
2723                                     (instance->pdev->device ==
2724                                      PCI_DEVICE_ID_LSI_INVADER)) {
2725                                         for (i = 0; i < (10 * 1000); i += 20) {
2726                                                 if (readl(
2727                                                             &instance->
2728                                                             reg_set->
2729                                                             doorbell) & 1)
2730                                                         msleep(20);
2731                                                 else
2732                                                         break;
2733                                         }
2734                                 }
2735                         } else
2736                                 writel(MFI_RESET_FLAGS,
2737                                         &instance->reg_set->inbound_doorbell);
2738
2739                         max_wait = MEGASAS_RESET_WAIT_TIME;
2740                         cur_state = MFI_STATE_OPERATIONAL;
2741                         break;
2742
2743                 case MFI_STATE_UNDEFINED:
2744                         /*
2745                          * This state should not last for more than 2 seconds
2746                          */
2747                         max_wait = MEGASAS_RESET_WAIT_TIME;
2748                         cur_state = MFI_STATE_UNDEFINED;
2749                         break;
2750
2751                 case MFI_STATE_BB_INIT:
2752                         max_wait = MEGASAS_RESET_WAIT_TIME;
2753                         cur_state = MFI_STATE_BB_INIT;
2754                         break;
2755
2756                 case MFI_STATE_FW_INIT:
2757                         max_wait = MEGASAS_RESET_WAIT_TIME;
2758                         cur_state = MFI_STATE_FW_INIT;
2759                         break;
2760
2761                 case MFI_STATE_FW_INIT_2:
2762                         max_wait = MEGASAS_RESET_WAIT_TIME;
2763                         cur_state = MFI_STATE_FW_INIT_2;
2764                         break;
2765
2766                 case MFI_STATE_DEVICE_SCAN:
2767                         max_wait = MEGASAS_RESET_WAIT_TIME;
2768                         cur_state = MFI_STATE_DEVICE_SCAN;
2769                         break;
2770
2771                 case MFI_STATE_FLUSH_CACHE:
2772                         max_wait = MEGASAS_RESET_WAIT_TIME;
2773                         cur_state = MFI_STATE_FLUSH_CACHE;
2774                         break;
2775
2776                 default:
2777                         printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
2778                                fw_state);
2779                         return -ENODEV;
2780                 }
2781
2782                 /*
2783                  * The cur_state should not last for more than max_wait secs
2784                  */
2785                 for (i = 0; i < (max_wait * 1000); i++) {
2786                         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &
2787                                         MFI_STATE_MASK ;
2788                 curr_abs_state =
2789                 instance->instancet->read_fw_status_reg(instance->reg_set);
2790
2791                         if (abs_state == curr_abs_state) {
2792                                 msleep(1);
2793                         } else
2794                                 break;
2795                 }
2796
2797                 /*
2798                  * Return error if fw_state hasn't changed after max_wait
2799                  */
2800                 if (curr_abs_state == abs_state) {
2801                         printk(KERN_DEBUG "FW state [%d] hasn't changed "
2802                                "in %d secs\n", fw_state, max_wait);
2803                         return -ENODEV;
2804                 }
2805         }
2806         printk(KERN_INFO "megasas: FW now in Ready state\n");
2807
2808         return 0;
2809 }
2810
2811 /**
2812  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
2813  * @instance:                           Adapter soft state
2814  */
2815 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
2816 {
2817         int i;
2818         u32 max_cmd = instance->max_mfi_cmds;
2819         struct megasas_cmd *cmd;
2820
2821         if (!instance->frame_dma_pool)
2822                 return;
2823
2824         /*
2825          * Return all frames to pool
2826          */
2827         for (i = 0; i < max_cmd; i++) {
2828
2829                 cmd = instance->cmd_list[i];
2830
2831                 if (cmd->frame)
2832                         pci_pool_free(instance->frame_dma_pool, cmd->frame,
2833                                       cmd->frame_phys_addr);
2834
2835                 if (cmd->sense)
2836                         pci_pool_free(instance->sense_dma_pool, cmd->sense,
2837                                       cmd->sense_phys_addr);
2838         }
2839
2840         /*
2841          * Now destroy the pool itself
2842          */
2843         pci_pool_destroy(instance->frame_dma_pool);
2844         pci_pool_destroy(instance->sense_dma_pool);
2845
2846         instance->frame_dma_pool = NULL;
2847         instance->sense_dma_pool = NULL;
2848 }
2849
2850 /**
2851  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
2852  * @instance:                   Adapter soft state
2853  *
2854  * Each command packet has an embedded DMA memory buffer that is used for
2855  * filling MFI frame and the SG list that immediately follows the frame. This
2856  * function creates those DMA memory buffers for each command packet by using
2857  * PCI pool facility.
2858  */
2859 static int megasas_create_frame_pool(struct megasas_instance *instance)
2860 {
2861         int i;
2862         u32 max_cmd;
2863         u32 sge_sz;
2864         u32 sgl_sz;
2865         u32 total_sz;
2866         u32 frame_count;
2867         struct megasas_cmd *cmd;
2868
2869         max_cmd = instance->max_mfi_cmds;
2870
2871         /*
2872          * Size of our frame is 64 bytes for MFI frame, followed by max SG
2873          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
2874          */
2875         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
2876             sizeof(struct megasas_sge32);
2877
2878         if (instance->flag_ieee) {
2879                 sge_sz = sizeof(struct megasas_sge_skinny);
2880         }
2881
2882         /*
2883          * Calculated the number of 64byte frames required for SGL
2884          */
2885         sgl_sz = sge_sz * instance->max_num_sge;
2886         frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
2887         frame_count = 15;
2888
2889         /*
2890          * We need one extra frame for the MFI command
2891          */
2892         frame_count++;
2893
2894         total_sz = MEGAMFI_FRAME_SIZE * frame_count;
2895         /*
2896          * Use DMA pool facility provided by PCI layer
2897          */
2898         instance->frame_dma_pool = pci_pool_create("megasas frame pool",
2899                                                    instance->pdev, total_sz, 64,
2900                                                    0);
2901
2902         if (!instance->frame_dma_pool) {
2903                 printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
2904                 return -ENOMEM;
2905         }
2906
2907         instance->sense_dma_pool = pci_pool_create("megasas sense pool",
2908                                                    instance->pdev, 128, 4, 0);
2909
2910         if (!instance->sense_dma_pool) {
2911                 printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
2912
2913                 pci_pool_destroy(instance->frame_dma_pool);
2914                 instance->frame_dma_pool = NULL;
2915
2916                 return -ENOMEM;
2917         }
2918
2919         /*
2920          * Allocate and attach a frame to each of the commands in cmd_list.
2921          * By making cmd->index as the context instead of the &cmd, we can
2922          * always use 32bit context regardless of the architecture
2923          */
2924         for (i = 0; i < max_cmd; i++) {
2925
2926                 cmd = instance->cmd_list[i];
2927
2928                 cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
2929                                             GFP_KERNEL, &cmd->frame_phys_addr);
2930
2931                 cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
2932                                             GFP_KERNEL, &cmd->sense_phys_addr);
2933
2934                 /*
2935                  * megasas_teardown_frame_pool() takes care of freeing
2936                  * whatever has been allocated
2937                  */
2938                 if (!cmd->frame || !cmd->sense) {
2939                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
2940                         megasas_teardown_frame_pool(instance);
2941                         return -ENOMEM;
2942                 }
2943
2944                 memset(cmd->frame, 0, total_sz);
2945                 cmd->frame->io.context = cmd->index;
2946                 cmd->frame->io.pad_0 = 0;
2947                 if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
2948                     (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
2949                     (reset_devices))
2950                         cmd->frame->hdr.cmd = MFI_CMD_INVALID;
2951         }
2952
2953         return 0;
2954 }
2955
2956 /**
2957  * megasas_free_cmds -  Free all the cmds in the free cmd pool
2958  * @instance:           Adapter soft state
2959  */
2960 void megasas_free_cmds(struct megasas_instance *instance)
2961 {
2962         int i;
2963         /* First free the MFI frame pool */
2964         megasas_teardown_frame_pool(instance);
2965
2966         /* Free all the commands in the cmd_list */
2967         for (i = 0; i < instance->max_mfi_cmds; i++)
2968
2969                 kfree(instance->cmd_list[i]);
2970
2971         /* Free the cmd_list buffer itself */
2972         kfree(instance->cmd_list);
2973         instance->cmd_list = NULL;
2974
2975         INIT_LIST_HEAD(&instance->cmd_pool);
2976 }
2977
2978 /**
2979  * megasas_alloc_cmds - Allocates the command packets
2980  * @instance:           Adapter soft state
2981  *
2982  * Each command that is issued to the FW, whether IO commands from the OS or
2983  * internal commands like IOCTLs, are wrapped in local data structure called
2984  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
2985  * the FW.
2986  *
2987  * Each frame has a 32-bit field called context (tag). This context is used
2988  * to get back the megasas_cmd from the frame when a frame gets completed in
2989  * the ISR. Typically the address of the megasas_cmd itself would be used as
2990  * the context. But we wanted to keep the differences between 32 and 64 bit
2991  * systems to the mininum. We always use 32 bit integers for the context. In
2992  * this driver, the 32 bit values are the indices into an array cmd_list.
2993  * This array is used only to look up the megasas_cmd given the context. The
2994  * free commands themselves are maintained in a linked list called cmd_pool.
2995  */
2996 int megasas_alloc_cmds(struct megasas_instance *instance)
2997 {
2998         int i;
2999         int j;
3000         u32 max_cmd;
3001         struct megasas_cmd *cmd;
3002
3003         max_cmd = instance->max_mfi_cmds;
3004
3005         /*
3006          * instance->cmd_list is an array of struct megasas_cmd pointers.
3007          * Allocate the dynamic array first and then allocate individual
3008          * commands.
3009          */
3010         instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
3011
3012         if (!instance->cmd_list) {
3013                 printk(KERN_DEBUG "megasas: out of memory\n");
3014                 return -ENOMEM;
3015         }
3016
3017         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
3018
3019         for (i = 0; i < max_cmd; i++) {
3020                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
3021                                                 GFP_KERNEL);
3022
3023                 if (!instance->cmd_list[i]) {
3024
3025                         for (j = 0; j < i; j++)
3026                                 kfree(instance->cmd_list[j]);
3027
3028                         kfree(instance->cmd_list);
3029                         instance->cmd_list = NULL;
3030
3031                         return -ENOMEM;
3032                 }
3033         }
3034
3035         /*
3036          * Add all the commands to command pool (instance->cmd_pool)
3037          */
3038         for (i = 0; i < max_cmd; i++) {
3039                 cmd = instance->cmd_list[i];
3040                 memset(cmd, 0, sizeof(struct megasas_cmd));
3041                 cmd->index = i;
3042                 cmd->scmd = NULL;
3043                 cmd->instance = instance;
3044
3045                 list_add_tail(&cmd->list, &instance->cmd_pool);
3046         }
3047
3048         /*
3049          * Create a frame pool and assign one frame to each cmd
3050          */
3051         if (megasas_create_frame_pool(instance)) {
3052                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
3053                 megasas_free_cmds(instance);
3054         }
3055
3056         return 0;
3057 }
3058
3059 /*
3060  * megasas_get_pd_list_info -   Returns FW's pd_list structure
3061  * @instance:                           Adapter soft state
3062  * @pd_list:                            pd_list structure
3063  *
3064  * Issues an internal command (DCMD) to get the FW's controller PD
3065  * list structure.  This information is mainly used to find out SYSTEM
3066  * supported by the FW.
3067  */
3068 static int
3069 megasas_get_pd_list(struct megasas_instance *instance)
3070 {
3071         int ret = 0, pd_index = 0;
3072         struct megasas_cmd *cmd;
3073         struct megasas_dcmd_frame *dcmd;
3074         struct MR_PD_LIST *ci;
3075         struct MR_PD_ADDRESS *pd_addr;
3076         dma_addr_t ci_h = 0;
3077
3078         cmd = megasas_get_cmd(instance);
3079
3080         if (!cmd) {
3081                 printk(KERN_DEBUG "megasas (get_pd_list): Failed to get cmd\n");
3082                 return -ENOMEM;
3083         }
3084
3085         dcmd = &cmd->frame->dcmd;
3086
3087         ci = pci_alloc_consistent(instance->pdev,
3088                   MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &ci_h);
3089
3090         if (!ci) {
3091                 printk(KERN_DEBUG "Failed to alloc mem for pd_list\n");
3092                 megasas_return_cmd(instance, cmd);
3093                 return -ENOMEM;
3094         }
3095
3096         memset(ci, 0, sizeof(*ci));
3097         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3098
3099         dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
3100         dcmd->mbox.b[1] = 0;
3101         dcmd->cmd = MFI_CMD_DCMD;
3102         dcmd->cmd_status = 0xFF;
3103         dcmd->sge_count = 1;
3104         dcmd->flags = MFI_FRAME_DIR_READ;
3105         dcmd->timeout = 0;
3106         dcmd->pad_0 = 0;
3107         dcmd->data_xfer_len = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST);
3108         dcmd->opcode = MR_DCMD_PD_LIST_QUERY;
3109         dcmd->sgl.sge32[0].phys_addr = ci_h;
3110         dcmd->sgl.sge32[0].length = MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST);
3111
3112         if (!megasas_issue_polled(instance, cmd)) {
3113                 ret = 0;
3114         } else {
3115                 ret = -1;
3116         }
3117
3118         /*
3119         * the following function will get the instance PD LIST.
3120         */
3121
3122         pd_addr = ci->addr;
3123
3124         if ( ret == 0 &&
3125                 (ci->count <
3126                   (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) {
3127
3128                 memset(instance->pd_list, 0,
3129                         MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
3130
3131                 for (pd_index = 0; pd_index < ci->count; pd_index++) {
3132
3133                         instance->pd_list[pd_addr->deviceId].tid        =
3134                                                         pd_addr->deviceId;
3135                         instance->pd_list[pd_addr->deviceId].driveType  =
3136                                                         pd_addr->scsiDevType;
3137                         instance->pd_list[pd_addr->deviceId].driveState =
3138                                                         MR_PD_STATE_SYSTEM;
3139                         pd_addr++;
3140                 }
3141         }
3142
3143         pci_free_consistent(instance->pdev,
3144                                 MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
3145                                 ci, ci_h);
3146         megasas_return_cmd(instance, cmd);
3147
3148         return ret;
3149 }
3150
3151 /*
3152  * megasas_get_ld_list_info -   Returns FW's ld_list structure
3153  * @instance:                           Adapter soft state
3154  * @ld_list:                            ld_list structure
3155  *
3156  * Issues an internal command (DCMD) to get the FW's controller PD
3157  * list structure.  This information is mainly used to find out SYSTEM
3158  * supported by the FW.
3159  */
3160 static int
3161 megasas_get_ld_list(struct megasas_instance *instance)
3162 {
3163         int ret = 0, ld_index = 0, ids = 0;
3164         struct megasas_cmd *cmd;
3165         struct megasas_dcmd_frame *dcmd;
3166         struct MR_LD_LIST *ci;
3167         dma_addr_t ci_h = 0;
3168
3169         cmd = megasas_get_cmd(instance);
3170
3171         if (!cmd) {
3172                 printk(KERN_DEBUG "megasas_get_ld_list: Failed to get cmd\n");
3173                 return -ENOMEM;
3174         }
3175
3176         dcmd = &cmd->frame->dcmd;
3177
3178         ci = pci_alloc_consistent(instance->pdev,
3179                                 sizeof(struct MR_LD_LIST),
3180                                 &ci_h);
3181
3182         if (!ci) {
3183                 printk(KERN_DEBUG "Failed to alloc mem in get_ld_list\n");
3184                 megasas_return_cmd(instance, cmd);
3185                 return -ENOMEM;
3186         }
3187
3188         memset(ci, 0, sizeof(*ci));
3189         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3190
3191         dcmd->cmd = MFI_CMD_DCMD;
3192         dcmd->cmd_status = 0xFF;
3193         dcmd->sge_count = 1;
3194         dcmd->flags = MFI_FRAME_DIR_READ;
3195         dcmd->timeout = 0;
3196         dcmd->data_xfer_len = sizeof(struct MR_LD_LIST);
3197         dcmd->opcode = MR_DCMD_LD_GET_LIST;
3198         dcmd->sgl.sge32[0].phys_addr = ci_h;
3199         dcmd->sgl.sge32[0].length = sizeof(struct MR_LD_LIST);
3200         dcmd->pad_0  = 0;
3201
3202         if (!megasas_issue_polled(instance, cmd)) {
3203                 ret = 0;
3204         } else {
3205                 ret = -1;
3206         }
3207
3208         /* the following function will get the instance PD LIST */
3209
3210         if ((ret == 0) && (ci->ldCount <= MAX_LOGICAL_DRIVES)) {
3211                 memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
3212
3213                 for (ld_index = 0; ld_index < ci->ldCount; ld_index++) {
3214                         if (ci->ldList[ld_index].state != 0) {
3215                                 ids = ci->ldList[ld_index].ref.targetId;
3216                                 instance->ld_ids[ids] =
3217                                         ci->ldList[ld_index].ref.targetId;
3218                         }
3219                 }
3220         }
3221
3222         pci_free_consistent(instance->pdev,
3223                                 sizeof(struct MR_LD_LIST),
3224                                 ci,
3225                                 ci_h);
3226
3227         megasas_return_cmd(instance, cmd);
3228         return ret;
3229 }
3230
3231 /**
3232  * megasas_get_controller_info -        Returns FW's controller structure
3233  * @instance:                           Adapter soft state
3234  * @ctrl_info:                          Controller information structure
3235  *
3236  * Issues an internal command (DCMD) to get the FW's controller structure.
3237  * This information is mainly used to find out the maximum IO transfer per
3238  * command supported by the FW.
3239  */
3240 static int
3241 megasas_get_ctrl_info(struct megasas_instance *instance,
3242                       struct megasas_ctrl_info *ctrl_info)
3243 {
3244         int ret = 0;
3245         struct megasas_cmd *cmd;
3246         struct megasas_dcmd_frame *dcmd;
3247         struct megasas_ctrl_info *ci;
3248         dma_addr_t ci_h = 0;
3249
3250         cmd = megasas_get_cmd(instance);
3251
3252         if (!cmd) {
3253                 printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
3254                 return -ENOMEM;
3255         }
3256
3257         dcmd = &cmd->frame->dcmd;
3258
3259         ci = pci_alloc_consistent(instance->pdev,
3260                                   sizeof(struct megasas_ctrl_info), &ci_h);
3261
3262         if (!ci) {
3263                 printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
3264                 megasas_return_cmd(instance, cmd);
3265                 return -ENOMEM;
3266         }
3267
3268         memset(ci, 0, sizeof(*ci));
3269         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3270
3271         dcmd->cmd = MFI_CMD_DCMD;
3272         dcmd->cmd_status = 0xFF;
3273         dcmd->sge_count = 1;
3274         dcmd->flags = MFI_FRAME_DIR_READ;
3275         dcmd->timeout = 0;
3276         dcmd->pad_0 = 0;
3277         dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
3278         dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
3279         dcmd->sgl.sge32[0].phys_addr = ci_h;
3280         dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
3281
3282         if (!megasas_issue_polled(instance, cmd)) {
3283                 ret = 0;
3284                 memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
3285         } else {
3286                 ret = -1;
3287         }
3288
3289         pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
3290                             ci, ci_h);
3291
3292         megasas_return_cmd(instance, cmd);
3293         return ret;
3294 }
3295
3296 /**
3297  * megasas_issue_init_mfi -     Initializes the FW
3298  * @instance:           Adapter soft state
3299  *
3300  * Issues the INIT MFI cmd
3301  */
3302 static int
3303 megasas_issue_init_mfi(struct megasas_instance *instance)
3304 {
3305         u32 context;
3306
3307         struct megasas_cmd *cmd;
3308
3309         struct megasas_init_frame *init_frame;
3310         struct megasas_init_queue_info *initq_info;
3311         dma_addr_t init_frame_h;
3312         dma_addr_t initq_info_h;
3313
3314         /*
3315          * Prepare a init frame. Note the init frame points to queue info
3316          * structure. Each frame has SGL allocated after first 64 bytes. For
3317          * this frame - since we don't need any SGL - we use SGL's space as
3318          * queue info structure
3319          *
3320          * We will not get a NULL command below. We just created the pool.
3321          */
3322         cmd = megasas_get_cmd(instance);
3323
3324         init_frame = (struct megasas_init_frame *)cmd->frame;
3325         initq_info = (struct megasas_init_queue_info *)
3326                 ((unsigned long)init_frame + 64);
3327
3328         init_frame_h = cmd->frame_phys_addr;
3329         initq_info_h = init_frame_h + 64;
3330
3331         context = init_frame->context;
3332         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
3333         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
3334         init_frame->context = context;
3335
3336         initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
3337         initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
3338
3339         initq_info->producer_index_phys_addr_lo = instance->producer_h;
3340         initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
3341
3342         init_frame->cmd = MFI_CMD_INIT;
3343         init_frame->cmd_status = 0xFF;
3344         init_frame->queue_info_new_phys_addr_lo = initq_info_h;
3345
3346         init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
3347
3348         /*
3349          * disable the intr before firing the init frame to FW
3350          */
3351         instance->instancet->disable_intr(instance->reg_set);
3352
3353         /*
3354          * Issue the init frame in polled mode
3355          */
3356
3357         if (megasas_issue_polled(instance, cmd)) {
3358                 printk(KERN_ERR "megasas: Failed to init firmware\n");
3359                 megasas_return_cmd(instance, cmd);
3360                 goto fail_fw_init;
3361         }
3362
3363         megasas_return_cmd(instance, cmd);
3364
3365         return 0;
3366
3367 fail_fw_init:
3368         return -EINVAL;
3369 }
3370
3371 static u32
3372 megasas_init_adapter_mfi(struct megasas_instance *instance)
3373 {
3374         struct megasas_register_set __iomem *reg_set;
3375         u32 context_sz;
3376         u32 reply_q_sz;
3377
3378         reg_set = instance->reg_set;
3379
3380         /*
3381          * Get various operational parameters from status register
3382          */
3383         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
3384         /*
3385          * Reduce the max supported cmds by 1. This is to ensure that the
3386          * reply_q_sz (1 more than the max cmd that driver may send)
3387          * does not exceed max cmds that the FW can support
3388          */
3389         instance->max_fw_cmds = instance->max_fw_cmds-1;
3390         instance->max_mfi_cmds = instance->max_fw_cmds;
3391         instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >>
3392                                         0x10;
3393         /*
3394          * Create a pool of commands
3395          */
3396         if (megasas_alloc_cmds(instance))
3397                 goto fail_alloc_cmds;
3398
3399         /*
3400          * Allocate memory for reply queue. Length of reply queue should
3401          * be _one_ more than the maximum commands handled by the firmware.
3402          *
3403          * Note: When FW completes commands, it places corresponding contex
3404          * values in this circular reply queue. This circular queue is a fairly
3405          * typical producer-consumer queue. FW is the producer (of completed
3406          * commands) and the driver is the consumer.
3407          */
3408         context_sz = sizeof(u32);
3409         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
3410
3411         instance->reply_queue = pci_alloc_consistent(instance->pdev,
3412                                                      reply_q_sz,
3413                                                      &instance->reply_queue_h);
3414
3415         if (!instance->reply_queue) {
3416                 printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
3417                 goto fail_reply_queue;
3418         }
3419
3420         if (megasas_issue_init_mfi(instance))
3421                 goto fail_fw_init;
3422
3423         instance->fw_support_ieee = 0;
3424         instance->fw_support_ieee =
3425                 (instance->instancet->read_fw_status_reg(reg_set) &
3426                 0x04000000);
3427
3428         printk(KERN_NOTICE "megasas_init_mfi: fw_support_ieee=%d",
3429                         instance->fw_support_ieee);
3430
3431         if (instance->fw_support_ieee)
3432                 instance->flag_ieee = 1;
3433
3434         return 0;
3435
3436 fail_fw_init:
3437
3438         pci_free_consistent(instance->pdev, reply_q_sz,
3439                             instance->reply_queue, instance->reply_queue_h);
3440 fail_reply_queue:
3441         megasas_free_cmds(instance);
3442
3443 fail_alloc_cmds:
3444         return 1;
3445 }
3446
3447 /**
3448  * megasas_init_fw -    Initializes the FW
3449  * @instance:           Adapter soft state
3450  *
3451  * This is the main function for initializing firmware
3452  */
3453
3454 static int megasas_init_fw(struct megasas_instance *instance)
3455 {
3456         u32 max_sectors_1;
3457         u32 max_sectors_2;
3458         u32 tmp_sectors, msix_enable;
3459         struct megasas_register_set __iomem *reg_set;
3460         struct megasas_ctrl_info *ctrl_info;
3461         unsigned long bar_list;
3462         int i;
3463
3464         /* Find first memory bar */
3465         bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
3466         instance->bar = find_first_bit(&bar_list, sizeof(unsigned long));
3467         instance->base_addr = pci_resource_start(instance->pdev, instance->bar);
3468         if (pci_request_selected_regions(instance->pdev, instance->bar,
3469                                          "megasas: LSI")) {
3470                 printk(KERN_DEBUG "megasas: IO memory region busy!\n");
3471                 return -EBUSY;
3472         }
3473
3474         instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
3475
3476         if (!instance->reg_set) {
3477                 printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
3478                 goto fail_ioremap;
3479         }
3480
3481         reg_set = instance->reg_set;
3482
3483         switch (instance->pdev->device) {
3484         case PCI_DEVICE_ID_LSI_FUSION:
3485         case PCI_DEVICE_ID_LSI_INVADER:
3486                 instance->instancet = &megasas_instance_template_fusion;
3487                 break;
3488         case PCI_DEVICE_ID_LSI_SAS1078R:
3489         case PCI_DEVICE_ID_LSI_SAS1078DE:
3490                 instance->instancet = &megasas_instance_template_ppc;
3491                 break;
3492         case PCI_DEVICE_ID_LSI_SAS1078GEN2:
3493         case PCI_DEVICE_ID_LSI_SAS0079GEN2:
3494                 instance->instancet = &megasas_instance_template_gen2;
3495                 break;
3496         case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
3497         case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
3498                 instance->instancet = &megasas_instance_template_skinny;
3499                 break;
3500         case PCI_DEVICE_ID_LSI_SAS1064R:
3501         case PCI_DEVICE_ID_DELL_PERC5:
3502         default:
3503                 instance->instancet = &megasas_instance_template_xscale;
3504                 break;
3505         }
3506
3507         /*
3508          * We expect the FW state to be READY
3509          */
3510         if (megasas_transition_to_ready(instance, 0))
3511                 goto fail_ready_state;
3512
3513         /* Check if MSI-X is supported while in ready state */
3514         msix_enable = (instance->instancet->read_fw_status_reg(reg_set) &
3515                        0x4000000) >> 0x1a;
3516         if (msix_enable && !msix_disable) {
3517                 /* Check max MSI-X vectors */
3518                 if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
3519                     (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) {
3520                         instance->msix_vectors = (readl(&instance->reg_set->
3521                                                         outbound_scratch_pad_2
3522                                                           ) & 0x1F) + 1;
3523                 } else
3524                         instance->msix_vectors = 1;
3525                 /* Don't bother allocating more MSI-X vectors than cpus */
3526                 instance->msix_vectors = min(instance->msix_vectors,
3527                                              (unsigned int)num_online_cpus());
3528                 for (i = 0; i < instance->msix_vectors; i++)
3529                         instance->msixentry[i].entry = i;
3530                 i = pci_enable_msix(instance->pdev, instance->msixentry,
3531                                     instance->msix_vectors);
3532                 if (i >= 0) {
3533                         if (i) {
3534                                 if (!pci_enable_msix(instance->pdev,
3535                                                      instance->msixentry, i))
3536                                         instance->msix_vectors = i;
3537                                 else
3538                                         instance->msix_vectors = 0;
3539                         }
3540                 } else
3541                         instance->msix_vectors = 0;
3542         }
3543
3544         /* Get operational params, sge flags, send init cmd to controller */
3545         if (instance->instancet->init_adapter(instance))
3546                 goto fail_init_adapter;
3547
3548         printk(KERN_ERR "megasas: INIT adapter done\n");
3549
3550         /** for passthrough
3551         * the following function will get the PD LIST.
3552         */
3553
3554         memset(instance->pd_list, 0 ,
3555                 (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
3556         megasas_get_pd_list(instance);
3557
3558         memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
3559         megasas_get_ld_list(instance);
3560
3561         ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
3562
3563         /*
3564          * Compute the max allowed sectors per IO: The controller info has two
3565          * limits on max sectors. Driver should use the minimum of these two.
3566          *
3567          * 1 << stripe_sz_ops.min = max sectors per strip
3568          *
3569          * Note that older firmwares ( < FW ver 30) didn't report information
3570          * to calculate max_sectors_1. So the number ended up as zero always.
3571          */
3572         tmp_sectors = 0;
3573         if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
3574
3575                 max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
3576                     ctrl_info->max_strips_per_io;
3577                 max_sectors_2 = ctrl_info->max_request_size;
3578
3579                 tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
3580                 instance->disableOnlineCtrlReset =
3581                 ctrl_info->properties.OnOffProperties.disableOnlineCtrlReset;
3582         }
3583
3584         instance->max_sectors_per_req = instance->max_num_sge *
3585                                                 PAGE_SIZE / 512;
3586         if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
3587                 instance->max_sectors_per_req = tmp_sectors;
3588
3589         kfree(ctrl_info);
3590
3591         /* Check for valid throttlequeuedepth module parameter */
3592         if (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY ||
3593             instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) {
3594                 if (throttlequeuedepth > (instance->max_fw_cmds -
3595                                           MEGASAS_SKINNY_INT_CMDS))
3596                         instance->throttlequeuedepth =
3597                                 MEGASAS_THROTTLE_QUEUE_DEPTH;
3598                 else
3599                         instance->throttlequeuedepth = throttlequeuedepth;
3600         } else {
3601                 if (throttlequeuedepth > (instance->max_fw_cmds -
3602                                           MEGASAS_INT_CMDS))
3603                         instance->throttlequeuedepth =
3604                                 MEGASAS_THROTTLE_QUEUE_DEPTH;
3605                 else
3606                         instance->throttlequeuedepth = throttlequeuedepth;
3607         }
3608
3609         /*
3610         * Setup tasklet for cmd completion
3611         */
3612
3613         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
3614                 (unsigned long)instance);
3615
3616         return 0;
3617
3618 fail_init_adapter:
3619 fail_ready_state:
3620         iounmap(instance->reg_set);
3621
3622       fail_ioremap:
3623         pci_release_selected_regions(instance->pdev, instance->bar);
3624
3625         return -EINVAL;
3626 }
3627
3628 /**
3629  * megasas_release_mfi -        Reverses the FW initialization
3630  * @intance:                    Adapter soft state
3631  */
3632 static void megasas_release_mfi(struct megasas_instance *instance)
3633 {
3634         u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
3635
3636         if (instance->reply_queue)
3637                 pci_free_consistent(instance->pdev, reply_q_sz,
3638                             instance->reply_queue, instance->reply_queue_h);
3639
3640         megasas_free_cmds(instance);
3641
3642         iounmap(instance->reg_set);
3643
3644         pci_release_selected_regions(instance->pdev, instance->bar);
3645 }
3646
3647 /**
3648  * megasas_get_seq_num -        Gets latest event sequence numbers
3649  * @instance:                   Adapter soft state
3650  * @eli:                        FW event log sequence numbers information
3651  *
3652  * FW maintains a log of all events in a non-volatile area. Upper layers would
3653  * usually find out the latest sequence number of the events, the seq number at
3654  * the boot etc. They would "read" all the events below the latest seq number
3655  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
3656  * number), they would subsribe to AEN (asynchronous event notification) and
3657  * wait for the events to happen.
3658  */
3659 static int
3660 megasas_get_seq_num(struct megasas_instance *instance,
3661                     struct megasas_evt_log_info *eli)
3662 {
3663         struct megasas_cmd *cmd;
3664         struct megasas_dcmd_frame *dcmd;
3665         struct megasas_evt_log_info *el_info;
3666         dma_addr_t el_info_h = 0;
3667
3668         cmd = megasas_get_cmd(instance);
3669
3670         if (!cmd) {
3671                 return -ENOMEM;
3672         }
3673
3674         dcmd = &cmd->frame->dcmd;
3675         el_info = pci_alloc_consistent(instance->pdev,
3676                                        sizeof(struct megasas_evt_log_info),
3677                                        &el_info_h);
3678
3679         if (!el_info) {
3680                 megasas_return_cmd(instance, cmd);
3681                 return -ENOMEM;
3682         }
3683
3684         memset(el_info, 0, sizeof(*el_info));
3685         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3686
3687         dcmd->cmd = MFI_CMD_DCMD;
3688         dcmd->cmd_status = 0x0;
3689         dcmd->sge_count = 1;
3690         dcmd->flags = MFI_FRAME_DIR_READ;
3691         dcmd->timeout = 0;
3692         dcmd->pad_0 = 0;
3693         dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
3694         dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
3695         dcmd->sgl.sge32[0].phys_addr = el_info_h;
3696         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
3697
3698         megasas_issue_blocked_cmd(instance, cmd);
3699
3700         /*
3701          * Copy the data back into callers buffer
3702          */
3703         memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
3704
3705         pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
3706                             el_info, el_info_h);
3707
3708         megasas_return_cmd(instance, cmd);
3709
3710         return 0;
3711 }
3712
3713 /**
3714  * megasas_register_aen -       Registers for asynchronous event notification
3715  * @instance:                   Adapter soft state
3716  * @seq_num:                    The starting sequence number
3717  * @class_locale:               Class of the event
3718  *
3719  * This function subscribes for AEN for events beyond the @seq_num. It requests
3720  * to be notified if and only if the event is of type @class_locale
3721  */
3722 static int
3723 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
3724                      u32 class_locale_word)
3725 {
3726         int ret_val;
3727         struct megasas_cmd *cmd;
3728         struct megasas_dcmd_frame *dcmd;
3729         union megasas_evt_class_locale curr_aen;
3730         union megasas_evt_class_locale prev_aen;
3731
3732         /*
3733          * If there an AEN pending already (aen_cmd), check if the
3734          * class_locale of that pending AEN is inclusive of the new
3735          * AEN request we currently have. If it is, then we don't have
3736          * to do anything. In other words, whichever events the current
3737          * AEN request is subscribing to, have already been subscribed
3738          * to.
3739          *
3740          * If the old_cmd is _not_ inclusive, then we have to abort
3741          * that command, form a class_locale that is superset of both
3742          * old and current and re-issue to the FW
3743          */
3744
3745         curr_aen.word = class_locale_word;
3746
3747         if (instance->aen_cmd) {
3748
3749                 prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
3750
3751                 /*
3752                  * A class whose enum value is smaller is inclusive of all
3753                  * higher values. If a PROGRESS (= -1) was previously
3754                  * registered, then a new registration requests for higher
3755                  * classes need not be sent to FW. They are automatically
3756                  * included.
3757                  *
3758                  * Locale numbers don't have such hierarchy. They are bitmap
3759                  * values
3760                  */
3761                 if ((prev_aen.members.class <= curr_aen.members.class) &&
3762                     !((prev_aen.members.locale & curr_aen.members.locale) ^
3763                       curr_aen.members.locale)) {
3764                         /*
3765                          * Previously issued event registration includes
3766                          * current request. Nothing to do.
3767                          */
3768                         return 0;
3769                 } else {
3770                         curr_aen.members.locale |= prev_aen.members.locale;
3771
3772                         if (prev_aen.members.class < curr_aen.members.class)
3773                                 curr_aen.members.class = prev_aen.members.class;
3774
3775                         instance->aen_cmd->abort_aen = 1;
3776                         ret_val = megasas_issue_blocked_abort_cmd(instance,
3777                                                                   instance->
3778                                                                   aen_cmd);
3779
3780                         if (ret_val) {
3781                                 printk(KERN_DEBUG "megasas: Failed to abort "
3782                                        "previous AEN command\n");
3783                                 return ret_val;
3784                         }
3785                 }
3786         }
3787
3788         cmd = megasas_get_cmd(instance);
3789
3790         if (!cmd)
3791                 return -ENOMEM;
3792
3793         dcmd = &cmd->frame->dcmd;
3794
3795         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
3796
3797         /*
3798          * Prepare DCMD for aen registration
3799          */
3800         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3801
3802         dcmd->cmd = MFI_CMD_DCMD;
3803         dcmd->cmd_status = 0x0;
3804         dcmd->sge_count = 1;
3805         dcmd->flags = MFI_FRAME_DIR_READ;
3806         dcmd->timeout = 0;
3807         dcmd->pad_0 = 0;
3808         instance->last_seq_num = seq_num;
3809         dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
3810         dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
3811         dcmd->mbox.w[0] = seq_num;
3812         dcmd->mbox.w[1] = curr_aen.word;
3813         dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
3814         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
3815
3816         if (instance->aen_cmd != NULL) {
3817                 megasas_return_cmd(instance, cmd);
3818                 return 0;
3819         }
3820
3821         /*
3822          * Store reference to the cmd used to register for AEN. When an
3823          * application wants us to register for AEN, we have to abort this
3824          * cmd and re-register with a new EVENT LOCALE supplied by that app
3825          */
3826         instance->aen_cmd = cmd;
3827
3828         /*
3829          * Issue the aen registration frame
3830          */
3831         instance->instancet->issue_dcmd(instance, cmd);
3832
3833         return 0;
3834 }
3835
3836 /**
3837  * megasas_start_aen -  Subscribes to AEN during driver load time
3838  * @instance:           Adapter soft state
3839  */
3840 static int megasas_start_aen(struct megasas_instance *instance)
3841 {
3842         struct megasas_evt_log_info eli;
3843         union megasas_evt_class_locale class_locale;
3844
3845         /*
3846          * Get the latest sequence number from FW
3847          */
3848         memset(&eli, 0, sizeof(eli));
3849
3850         if (megasas_get_seq_num(instance, &eli))
3851                 return -1;
3852
3853         /*
3854          * Register AEN with FW for latest sequence number plus 1
3855          */
3856         class_locale.members.reserved = 0;
3857         class_locale.members.locale = MR_EVT_LOCALE_ALL;
3858         class_locale.members.class = MR_EVT_CLASS_DEBUG;
3859
3860         return megasas_register_aen(instance, eli.newest_seq_num + 1,
3861                                     class_locale.word);
3862 }
3863
3864 /**
3865  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
3866  * @instance:           Adapter soft state
3867  */
3868 static int megasas_io_attach(struct megasas_instance *instance)
3869 {
3870         struct Scsi_Host *host = instance->host;
3871
3872         /*
3873          * Export parameters required by SCSI mid-layer
3874          */
3875         host->irq = instance->pdev->irq;
3876         host->unique_id = instance->unique_id;
3877         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3878                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
3879                 host->can_queue =
3880                         instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
3881         } else
3882                 host->can_queue =
3883                         instance->max_fw_cmds - MEGASAS_INT_CMDS;
3884         host->this_id = instance->init_id;
3885         host->sg_tablesize = instance->max_num_sge;
3886
3887         if (instance->fw_support_ieee)
3888                 instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
3889
3890         /*
3891          * Check if the module parameter value for max_sectors can be used
3892          */
3893         if (max_sectors && max_sectors < instance->max_sectors_per_req)
3894                 instance->max_sectors_per_req = max_sectors;
3895         else {
3896                 if (max_sectors) {
3897                         if (((instance->pdev->device ==
3898                                 PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
3899                                 (instance->pdev->device ==
3900                                 PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
3901                                 (max_sectors <= MEGASAS_MAX_SECTORS)) {
3902                                 instance->max_sectors_per_req = max_sectors;
3903                         } else {
3904                         printk(KERN_INFO "megasas: max_sectors should be > 0"
3905                                 "and <= %d (or < 1MB for GEN2 controller)\n",
3906                                 instance->max_sectors_per_req);
3907                         }
3908                 }
3909         }
3910
3911         host->max_sectors = instance->max_sectors_per_req;
3912         host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
3913         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
3914         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
3915         host->max_lun = MEGASAS_MAX_LUN;
3916         host->max_cmd_len = 16;
3917
3918         /* Fusion only supports host reset */
3919         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
3920             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)) {
3921                 host->hostt->eh_device_reset_handler = NULL;
3922                 host->hostt->eh_bus_reset_handler = NULL;
3923         }
3924
3925         /*
3926          * Notify the mid-layer about the new controller
3927          */
3928         if (scsi_add_host(host, &instance->pdev->dev)) {
3929                 printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
3930                 return -ENODEV;
3931         }
3932
3933         /*
3934          * Trigger SCSI to scan our drives
3935          */
3936         scsi_scan_host(host);
3937         return 0;
3938 }
3939
3940 static int
3941 megasas_set_dma_mask(struct pci_dev *pdev)
3942 {
3943         /*
3944          * All our contollers are capable of performing 64-bit DMA
3945          */
3946         if (IS_DMA64) {
3947                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) {
3948
3949                         if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
3950                                 goto fail_set_dma_mask;
3951                 }
3952         } else {
3953                 if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
3954                         goto fail_set_dma_mask;
3955         }
3956         return 0;
3957
3958 fail_set_dma_mask:
3959         return 1;
3960 }
3961
3962 /**
3963  * megasas_probe_one -  PCI hotplug entry point
3964  * @pdev:               PCI device structure
3965  * @id:                 PCI ids of supported hotplugged adapter
3966  */
3967 static int __devinit
3968 megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
3969 {
3970         int rval, pos, i, j;
3971         struct Scsi_Host *host;
3972         struct megasas_instance *instance;
3973         u16 control = 0;
3974
3975         /* Reset MSI-X in the kdump kernel */
3976         if (reset_devices) {
3977                 pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
3978                 if (pos) {
3979                         pci_read_config_word(pdev, msi_control_reg(pos),
3980                                              &control);
3981                         if (control & PCI_MSIX_FLAGS_ENABLE) {
3982                                 dev_info(&pdev->dev, "resetting MSI-X\n");
3983                                 pci_write_config_word(pdev,
3984                                                       msi_control_reg(pos),
3985                                                       control &
3986                                                       ~PCI_MSIX_FLAGS_ENABLE);
3987                         }
3988                 }
3989         }
3990
3991         /*
3992          * Announce PCI information
3993          */
3994         printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
3995                pdev->vendor, pdev->device, pdev->subsystem_vendor,
3996                pdev->subsystem_device);
3997
3998         printk("bus %d:slot %d:func %d\n",
3999                pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
4000
4001         /*
4002          * PCI prepping: enable device set bus mastering and dma mask
4003          */
4004         rval = pci_enable_device_mem(pdev);
4005
4006         if (rval) {
4007                 return rval;
4008         }
4009
4010         pci_set_master(pdev);
4011
4012         if (megasas_set_dma_mask(pdev))
4013                 goto fail_set_dma_mask;
4014
4015         host = scsi_host_alloc(&megasas_template,
4016                                sizeof(struct megasas_instance));
4017
4018         if (!host) {
4019                 printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
4020                 goto fail_alloc_instance;
4021         }
4022
4023         instance = (struct megasas_instance *)host->hostdata;
4024         memset(instance, 0, sizeof(*instance));
4025         atomic_set( &instance->fw_reset_no_pci_access, 0 );
4026         instance->pdev = pdev;
4027
4028         switch (instance->pdev->device) {
4029         case PCI_DEVICE_ID_LSI_FUSION:
4030         case PCI_DEVICE_ID_LSI_INVADER:
4031         {
4032                 struct fusion_context *fusion;
4033
4034                 instance->ctrl_context =
4035                         kzalloc(sizeof(struct fusion_context), GFP_KERNEL);
4036                 if (!instance->ctrl_context) {
4037                         printk(KERN_DEBUG "megasas: Failed to allocate "
4038                                "memory for Fusion context info\n");
4039                         goto fail_alloc_dma_buf;
4040                 }
4041                 fusion = instance->ctrl_context;
4042                 INIT_LIST_HEAD(&fusion->cmd_pool);
4043                 spin_lock_init(&fusion->cmd_pool_lock);
4044         }
4045         break;
4046         default: /* For all other supported controllers */
4047
4048                 instance->producer =
4049                         pci_alloc_consistent(pdev, sizeof(u32),
4050                                              &instance->producer_h);
4051                 instance->consumer =
4052                         pci_alloc_consistent(pdev, sizeof(u32),
4053                                              &instance->consumer_h);
4054
4055                 if (!instance->producer || !instance->consumer) {
4056                         printk(KERN_DEBUG "megasas: Failed to allocate"
4057                                "memory for producer, consumer\n");
4058                         goto fail_alloc_dma_buf;
4059                 }
4060
4061                 *instance->producer = 0;
4062                 *instance->consumer = 0;
4063                 break;
4064         }
4065
4066         megasas_poll_wait_aen = 0;
4067         instance->flag_ieee = 0;
4068         instance->ev = NULL;
4069         instance->issuepend_done = 1;
4070         instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
4071         megasas_poll_wait_aen = 0;
4072
4073         instance->evt_detail = pci_alloc_consistent(pdev,
4074                                                     sizeof(struct
4075                                                            megasas_evt_detail),
4076                                                     &instance->evt_detail_h);
4077
4078         if (!instance->evt_detail) {
4079                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
4080                        "event detail structure\n");
4081                 goto fail_alloc_dma_buf;
4082         }
4083
4084         /*
4085          * Initialize locks and queues
4086          */
4087         INIT_LIST_HEAD(&instance->cmd_pool);
4088         INIT_LIST_HEAD(&instance->internal_reset_pending_q);
4089
4090         atomic_set(&instance->fw_outstanding,0);
4091
4092         init_waitqueue_head(&instance->int_cmd_wait_q);
4093         init_waitqueue_head(&instance->abort_cmd_wait_q);
4094
4095         spin_lock_init(&instance->cmd_pool_lock);
4096         spin_lock_init(&instance->hba_lock);
4097         spin_lock_init(&instance->completion_lock);
4098
4099         mutex_init(&instance->aen_mutex);
4100         mutex_init(&instance->reset_mutex);
4101
4102         /*
4103          * Initialize PCI related and misc parameters
4104          */
4105         instance->host = host;
4106         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
4107         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
4108
4109         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4110                 (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
4111                 instance->flag_ieee = 1;
4112                 sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
4113         } else
4114                 sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
4115
4116         megasas_dbg_lvl = 0;
4117         instance->flag = 0;
4118         instance->unload = 1;
4119         instance->last_time = 0;
4120         instance->disableOnlineCtrlReset = 1;
4121
4122         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4123             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER))
4124                 INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
4125         else
4126                 INIT_WORK(&instance->work_init, process_fw_state_change_wq);
4127
4128         /*
4129          * Initialize MFI Firmware
4130          */
4131         if (megasas_init_fw(instance))
4132                 goto fail_init_mfi;
4133
4134         /*
4135          * Register IRQ
4136          */
4137         if (instance->msix_vectors) {
4138                 for (i = 0 ; i < instance->msix_vectors; i++) {
4139                         instance->irq_context[i].instance = instance;
4140                         instance->irq_context[i].MSIxIndex = i;
4141                         if (request_irq(instance->msixentry[i].vector,
4142                                         instance->instancet->service_isr, 0,
4143                                         "megasas",
4144                                         &instance->irq_context[i])) {
4145                                 printk(KERN_DEBUG "megasas: Failed to "
4146                                        "register IRQ for vector %d.\n", i);
4147                                 for (j = 0 ; j < i ; j++)
4148                                         free_irq(
4149                                                 instance->msixentry[j].vector,
4150                                                 &instance->irq_context[j]);
4151                                 goto fail_irq;
4152                         }
4153                 }
4154         } else {
4155                 instance->irq_context[0].instance = instance;
4156                 instance->irq_context[0].MSIxIndex = 0;
4157                 if (request_irq(pdev->irq, instance->instancet->service_isr,
4158                                 IRQF_SHARED, "megasas",
4159                                 &instance->irq_context[0])) {
4160                         printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
4161                         goto fail_irq;
4162                 }
4163         }
4164
4165         instance->instancet->enable_intr(instance->reg_set);
4166
4167         /*
4168          * Store instance in PCI softstate
4169          */
4170         pci_set_drvdata(pdev, instance);
4171
4172         /*
4173          * Add this controller to megasas_mgmt_info structure so that it
4174          * can be exported to management applications
4175          */
4176         megasas_mgmt_info.count++;
4177         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
4178         megasas_mgmt_info.max_index++;
4179
4180         /*
4181          * Register with SCSI mid-layer
4182          */
4183         if (megasas_io_attach(instance))
4184                 goto fail_io_attach;
4185
4186         instance->unload = 0;
4187
4188         /*
4189          * Initiate AEN (Asynchronous Event Notification)
4190          */
4191         if (megasas_start_aen(instance)) {
4192                 printk(KERN_DEBUG "megasas: start aen failed\n");
4193                 goto fail_start_aen;
4194         }
4195
4196         return 0;
4197
4198       fail_start_aen:
4199       fail_io_attach:
4200         megasas_mgmt_info.count--;
4201         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
4202         megasas_mgmt_info.max_index--;
4203
4204         pci_set_drvdata(pdev, NULL);
4205         instance->instancet->disable_intr(instance->reg_set);
4206         if (instance->msix_vectors)
4207                 for (i = 0 ; i < instance->msix_vectors; i++)
4208                         free_irq(instance->msixentry[i].vector,
4209                                  &instance->irq_context[i]);
4210         else
4211                 free_irq(instance->pdev->irq, &instance->irq_context[0]);
4212 fail_irq:
4213         if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4214             (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER))
4215                 megasas_release_fusion(instance);
4216         else
4217                 megasas_release_mfi(instance);
4218       fail_init_mfi:
4219         if (instance->msix_vectors)
4220                 pci_disable_msix(instance->pdev);
4221       fail_alloc_dma_buf:
4222         if (instance->evt_detail)
4223                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
4224                                     instance->evt_detail,
4225                                     instance->evt_detail_h);
4226
4227         if (instance->producer)
4228                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
4229                                     instance->producer_h);
4230         if (instance->consumer)
4231                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
4232                                     instance->consumer_h);
4233         scsi_host_put(host);
4234
4235       fail_alloc_instance:
4236       fail_set_dma_mask:
4237         pci_disable_device(pdev);
4238
4239         return -ENODEV;
4240 }
4241
4242 /**
4243  * megasas_flush_cache -        Requests FW to flush all its caches
4244  * @instance:                   Adapter soft state
4245  */
4246 static void megasas_flush_cache(struct megasas_instance *instance)
4247 {
4248         struct megasas_cmd *cmd;
4249         struct megasas_dcmd_frame *dcmd;
4250
4251         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
4252                 return;
4253
4254         cmd = megasas_get_cmd(instance);
4255
4256         if (!cmd)
4257                 return;
4258
4259         dcmd = &cmd->frame->dcmd;
4260
4261         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4262
4263         dcmd->cmd = MFI_CMD_DCMD;
4264         dcmd->cmd_status = 0x0;
4265         dcmd->sge_count = 0;
4266         dcmd->flags = MFI_FRAME_DIR_NONE;
4267         dcmd->timeout = 0;
4268         dcmd->pad_0 = 0;
4269         dcmd->data_xfer_len = 0;
4270         dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
4271         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
4272
4273         megasas_issue_blocked_cmd(instance, cmd);
4274
4275         megasas_return_cmd(instance, cmd);
4276
4277         return;
4278 }
4279
4280 /**
4281  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
4282  * @instance:                           Adapter soft state
4283  * @opcode:                             Shutdown/Hibernate
4284  */
4285 static void megasas_shutdown_controller(struct megasas_instance *instance,
4286                                         u32 opcode)
4287 {
4288         struct megasas_cmd *cmd;
4289         struct megasas_dcmd_frame *dcmd;
4290
4291         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
4292                 return;
4293
4294         cmd = megasas_get_cmd(instance);
4295
4296         if (!cmd)
4297                 return;
4298
4299         if (instance->aen_cmd)
4300                 megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
4301         if (instance->map_update_cmd)
4302                 megasas_issue_blocked_abort_cmd(instance,
4303                                                 instance->map_update_cmd);
4304         dcmd = &cmd->frame->dcmd;
4305
4306         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4307
4308         dcmd->cmd = MFI_CMD_DCMD;
4309         dcmd->cmd_status = 0x0;
4310         dcmd->sge_count = 0;
4311         dcmd->flags = MFI_FRAME_DIR_NONE;
4312         dcmd->timeout = 0;
4313         dcmd->pad_0 = 0;
4314         dcmd->data_xfer_len = 0;
4315         dcmd->opcode = opcode;
4316
4317         megasas_issue_blocked_cmd(instance, cmd);
4318
4319         megasas_return_cmd(instance, cmd);
4320
4321         return;
4322 }
4323
4324 #ifdef CONFIG_PM
4325 /**
4326  * megasas_suspend -    driver suspend entry point
4327  * @pdev:               PCI device structure
4328  * @state:              PCI power state to suspend routine
4329  */
4330 static int
4331 megasas_suspend(struct pci_dev *pdev, pm_message_t state)
4332 {
4333         struct Scsi_Host *host;
4334         struct megasas_instance *instance;
4335         int i;
4336
4337         instance = pci_get_drvdata(pdev);
4338         host = instance->host;
4339         instance->unload = 1;
4340
4341         megasas_flush_cache(instance);
4342         megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
4343
4344         /* cancel the delayed work if this work still in queue */
4345         if (instance->ev != NULL) {
4346                 struct megasas_aen_event *ev = instance->ev;
4347                 cancel_delayed_work_sync(
4348                         (struct delayed_work *)&ev->hotplug_work);
4349                 instance->ev = NULL;
4350         }
4351
4352         tasklet_kill(&instance->isr_tasklet);
4353
4354         pci_set_drvdata(instance->pdev, instance);
4355         instance->instancet->disable_intr(instance->reg_set);
4356
4357         if (instance->msix_vectors)
4358                 for (i = 0 ; i < instance->msix_vectors; i++)
4359                         free_irq(instance->msixentry[i].vector,
4360                                  &instance->irq_context[i]);
4361         else
4362                 free_irq(instance->pdev->irq, &instance->irq_context[0]);
4363         if (instance->msix_vectors)
4364                 pci_disable_msix(instance->pdev);
4365
4366         pci_save_state(pdev);
4367         pci_disable_device(pdev);
4368
4369         pci_set_power_state(pdev, pci_choose_state(pdev, state));
4370
4371         return 0;
4372 }
4373
4374 /**
4375  * megasas_resume-      driver resume entry point
4376  * @pdev:               PCI device structure
4377  */
4378 static int
4379 megasas_resume(struct pci_dev *pdev)
4380 {
4381         int rval, i, j;
4382         struct Scsi_Host *host;
4383         struct megasas_instance *instance;
4384
4385         instance = pci_get_drvdata(pdev);
4386         host = instance->host;
4387         pci_set_power_state(pdev, PCI_D0);
4388         pci_enable_wake(pdev, PCI_D0, 0);
4389         pci_restore_state(pdev);
4390
4391         /*
4392          * PCI prepping: enable device set bus mastering and dma mask
4393          */
4394         rval = pci_enable_device_mem(pdev);
4395
4396         if (rval) {
4397                 printk(KERN_ERR "megasas: Enable device failed\n");
4398                 return rval;
4399         }
4400
4401         pci_set_master(pdev);
4402
4403         if (megasas_set_dma_mask(pdev))
4404                 goto fail_set_dma_mask;
4405
4406         /*
4407          * Initialize MFI Firmware
4408          */
4409
4410         atomic_set(&instance->fw_outstanding, 0);
4411
4412         /*
4413          * We expect the FW state to be READY
4414          */
4415         if (megasas_transition_to_ready(instance, 0))
4416                 goto fail_ready_state;
4417
4418         /* Now re-enable MSI-X */
4419         if (instance->msix_vectors)
4420                 pci_enable_msix(instance->pdev, instance->msixentry,
4421                                 instance->msix_vectors);
4422
4423         switch (instance->pdev->device) {
4424         case PCI_DEVICE_ID_LSI_FUSION:
4425         case PCI_DEVICE_ID_LSI_INVADER:
4426         {
4427                 megasas_reset_reply_desc(instance);
4428                 if (megasas_ioc_init_fusion(instance)) {
4429                         megasas_free_cmds(instance);
4430                         megasas_free_cmds_fusion(instance);
4431                         goto fail_init_mfi;
4432                 }
4433                 if (!megasas_get_map_info(instance))
4434                         megasas_sync_map_info(instance);
4435         }
4436         break;
4437         default:
4438                 *instance->producer = 0;
4439                 *instance->consumer = 0;
4440                 if (megasas_issue_init_mfi(instance))
4441                         goto fail_init_mfi;
4442                 break;
4443         }
4444
4445         tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
4446                      (unsigned long)instance);
4447
4448         /*
4449          * Register IRQ
4450          */
4451         if (instance->msix_vectors) {
4452                 for (i = 0 ; i < instance->msix_vectors; i++) {
4453                         instance->irq_context[i].instance = instance;
4454                         instance->irq_context[i].MSIxIndex = i;
4455                         if (request_irq(instance->msixentry[i].vector,
4456                                         instance->instancet->service_isr, 0,
4457                                         "megasas",
4458                                         &instance->irq_context[i])) {
4459                                 printk(KERN_DEBUG "megasas: Failed to "
4460                                        "register IRQ for vector %d.\n", i);
4461                                 for (j = 0 ; j < i ; j++)
4462                                         free_irq(
4463                                                 instance->msixentry[j].vector,
4464                                                 &instance->irq_context[j]);
4465                                 goto fail_irq;
4466                         }
4467                 }
4468         } else {
4469                 instance->irq_context[0].instance = instance;
4470                 instance->irq_context[0].MSIxIndex = 0;
4471                 if (request_irq(pdev->irq, instance->instancet->service_isr,
4472                                 IRQF_SHARED, "megasas",
4473                                 &instance->irq_context[0])) {
4474                         printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
4475                         goto fail_irq;
4476                 }
4477         }
4478
4479         instance->instancet->enable_intr(instance->reg_set);
4480         instance->unload = 0;
4481
4482         /*
4483          * Initiate AEN (Asynchronous Event Notification)
4484          */
4485         if (megasas_start_aen(instance))
4486                 printk(KERN_ERR "megasas: Start AEN failed\n");
4487
4488         return 0;
4489
4490 fail_irq:
4491 fail_init_mfi:
4492         if (instance->evt_detail)
4493                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
4494                                 instance->evt_detail,
4495                                 instance->evt_detail_h);
4496
4497         if (instance->producer)
4498                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
4499                                 instance->producer_h);
4500         if (instance->consumer)
4501                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
4502                                 instance->consumer_h);
4503         scsi_host_put(host);
4504
4505 fail_set_dma_mask:
4506 fail_ready_state:
4507
4508         pci_disable_device(pdev);
4509
4510         return -ENODEV;
4511 }
4512 #else
4513 #define megasas_suspend NULL
4514 #define megasas_resume  NULL
4515 #endif
4516
4517 /**
4518  * megasas_detach_one - PCI hot"un"plug entry point
4519  * @pdev:               PCI device structure
4520  */
4521 static void __devexit megasas_detach_one(struct pci_dev *pdev)
4522 {
4523         int i;
4524         struct Scsi_Host *host;
4525         struct megasas_instance *instance;
4526         struct fusion_context *fusion;
4527
4528         instance = pci_get_drvdata(pdev);
4529         instance->unload = 1;
4530         host = instance->host;
4531         fusion = instance->ctrl_context;
4532
4533         scsi_remove_host(instance->host);
4534         megasas_flush_cache(instance);
4535         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
4536
4537         /* cancel the delayed work if this work still in queue*/
4538         if (instance->ev != NULL) {
4539                 struct megasas_aen_event *ev = instance->ev;
4540                 cancel_delayed_work_sync(
4541                         (struct delayed_work *)&ev->hotplug_work);
4542                 instance->ev = NULL;
4543         }
4544
4545         tasklet_kill(&instance->isr_tasklet);
4546
4547         /*
4548          * Take the instance off the instance array. Note that we will not
4549          * decrement the max_index. We let this array be sparse array
4550          */
4551         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
4552                 if (megasas_mgmt_info.instance[i] == instance) {
4553                         megasas_mgmt_info.count--;
4554                         megasas_mgmt_info.instance[i] = NULL;
4555
4556                         break;
4557                 }
4558         }
4559
4560         pci_set_drvdata(instance->pdev, NULL);
4561
4562         instance->instancet->disable_intr(instance->reg_set);
4563
4564         if (instance->msix_vectors)
4565                 for (i = 0 ; i < instance->msix_vectors; i++)
4566                         free_irq(instance->msixentry[i].vector,
4567                                  &instance->irq_context[i]);
4568         else
4569                 free_irq(instance->pdev->irq, &instance->irq_context[0]);
4570         if (instance->msix_vectors)
4571                 pci_disable_msix(instance->pdev);
4572
4573         switch (instance->pdev->device) {
4574         case PCI_DEVICE_ID_LSI_FUSION:
4575         case PCI_DEVICE_ID_LSI_INVADER:
4576                 megasas_release_fusion(instance);
4577                 for (i = 0; i < 2 ; i++)
4578                         if (fusion->ld_map[i])
4579                                 dma_free_coherent(&instance->pdev->dev,
4580                                                   fusion->map_sz,
4581                                                   fusion->ld_map[i],
4582                                                   fusion->
4583                                                   ld_map_phys[i]);
4584                 kfree(instance->ctrl_context);
4585                 break;
4586         default:
4587                 megasas_release_mfi(instance);
4588                 pci_free_consistent(pdev,
4589                                     sizeof(struct megasas_evt_detail),
4590                                     instance->evt_detail,
4591                                     instance->evt_detail_h);
4592                 pci_free_consistent(pdev, sizeof(u32),
4593                                     instance->producer,
4594                                     instance->producer_h);
4595                 pci_free_consistent(pdev, sizeof(u32),
4596                                     instance->consumer,
4597                                     instance->consumer_h);
4598                 break;
4599         }
4600
4601         scsi_host_put(host);
4602
4603         pci_set_drvdata(pdev, NULL);
4604
4605         pci_disable_device(pdev);
4606
4607         return;
4608 }
4609
4610 /**
4611  * megasas_shutdown -   Shutdown entry point
4612  * @device:             Generic device structure
4613  */
4614 static void megasas_shutdown(struct pci_dev *pdev)
4615 {
4616         int i;
4617         struct megasas_instance *instance = pci_get_drvdata(pdev);
4618
4619         instance->unload = 1;
4620         megasas_flush_cache(instance);
4621         megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
4622         instance->instancet->disable_intr(instance->reg_set);
4623         if (instance->msix_vectors)
4624                 for (i = 0 ; i < instance->msix_vectors; i++)
4625                         free_irq(instance->msixentry[i].vector,
4626                                  &instance->irq_context[i]);
4627         else
4628                 free_irq(instance->pdev->irq, &instance->irq_context[0]);
4629         if (instance->msix_vectors)
4630                 pci_disable_msix(instance->pdev);
4631 }
4632
4633 /**
4634  * megasas_mgmt_open -  char node "open" entry point
4635  */
4636 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
4637 {
4638         /*
4639          * Allow only those users with admin rights
4640          */
4641         if (!capable(CAP_SYS_ADMIN))
4642                 return -EACCES;
4643
4644         return 0;
4645 }
4646
4647 /**
4648  * megasas_mgmt_fasync -        Async notifier registration from applications
4649  *
4650  * This function adds the calling process to a driver global queue. When an
4651  * event occurs, SIGIO will be sent to all processes in this queue.
4652  */
4653 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
4654 {
4655         int rc;
4656
4657         mutex_lock(&megasas_async_queue_mutex);
4658
4659         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
4660
4661         mutex_unlock(&megasas_async_queue_mutex);
4662
4663         if (rc >= 0) {
4664                 /* For sanity check when we get ioctl */
4665                 filep->private_data = filep;
4666                 return 0;
4667         }
4668
4669         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
4670
4671         return rc;
4672 }
4673
4674 /**
4675  * megasas_mgmt_poll -  char node "poll" entry point
4676  * */
4677 static unsigned int megasas_mgmt_poll(struct file *file, poll_table *wait)
4678 {
4679         unsigned int mask;
4680         unsigned long flags;
4681         poll_wait(file, &megasas_poll_wait, wait);
4682         spin_lock_irqsave(&poll_aen_lock, flags);
4683         if (megasas_poll_wait_aen)
4684                 mask =   (POLLIN | POLLRDNORM);
4685         else
4686                 mask = 0;
4687         spin_unlock_irqrestore(&poll_aen_lock, flags);
4688         return mask;
4689 }
4690
4691 /**
4692  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
4693  * @instance:                   Adapter soft state
4694  * @argp:                       User's ioctl packet
4695  */
4696 static int
4697 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
4698                       struct megasas_iocpacket __user * user_ioc,
4699                       struct megasas_iocpacket *ioc)
4700 {
4701         struct megasas_sge32 *kern_sge32;
4702         struct megasas_cmd *cmd;
4703         void *kbuff_arr[MAX_IOCTL_SGE];
4704         dma_addr_t buf_handle = 0;
4705         int error = 0, i;
4706         void *sense = NULL;
4707         dma_addr_t sense_handle;
4708         unsigned long *sense_ptr;
4709
4710         memset(kbuff_arr, 0, sizeof(kbuff_arr));
4711
4712         if (ioc->sge_count > MAX_IOCTL_SGE) {
4713                 printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
4714                        ioc->sge_count, MAX_IOCTL_SGE);
4715                 return -EINVAL;
4716         }
4717
4718         cmd = megasas_get_cmd(instance);
4719         if (!cmd) {
4720                 printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
4721                 return -ENOMEM;
4722         }
4723
4724         /*
4725          * User's IOCTL packet has 2 frames (maximum). Copy those two
4726          * frames into our cmd's frames. cmd->frame's context will get
4727          * overwritten when we copy from user's frames. So set that value
4728          * alone separately
4729          */
4730         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
4731         cmd->frame->hdr.context = cmd->index;
4732         cmd->frame->hdr.pad_0 = 0;
4733         cmd->frame->hdr.flags &= ~(MFI_FRAME_IEEE | MFI_FRAME_SGL64 |
4734                                    MFI_FRAME_SENSE64);
4735
4736         /*
4737          * The management interface between applications and the fw uses
4738          * MFI frames. E.g, RAID configuration changes, LD property changes
4739          * etc are accomplishes through different kinds of MFI frames. The
4740          * driver needs to care only about substituting user buffers with
4741          * kernel buffers in SGLs. The location of SGL is embedded in the
4742          * struct iocpacket itself.
4743          */
4744         kern_sge32 = (struct megasas_sge32 *)
4745             ((unsigned long)cmd->frame + ioc->sgl_off);
4746
4747         /*
4748          * For each user buffer, create a mirror buffer and copy in
4749          */
4750         for (i = 0; i < ioc->sge_count; i++) {
4751                 if (!ioc->sgl[i].iov_len)
4752                         continue;
4753
4754                 kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
4755                                                     ioc->sgl[i].iov_len,
4756                                                     &buf_handle, GFP_KERNEL);
4757                 if (!kbuff_arr[i]) {
4758                         printk(KERN_DEBUG "megasas: Failed to alloc "
4759                                "kernel SGL buffer for IOCTL \n");
4760                         error = -ENOMEM;
4761                         goto out;
4762                 }
4763
4764                 /*
4765                  * We don't change the dma_coherent_mask, so
4766                  * pci_alloc_consistent only returns 32bit addresses
4767                  */
4768                 kern_sge32[i].phys_addr = (u32) buf_handle;
4769                 kern_sge32[i].length = ioc->sgl[i].iov_len;
4770
4771                 /*
4772                  * We created a kernel buffer corresponding to the
4773                  * user buffer. Now copy in from the user buffer
4774                  */
4775                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
4776                                    (u32) (ioc->sgl[i].iov_len))) {
4777                         error = -EFAULT;
4778                         goto out;
4779                 }
4780         }
4781
4782         if (ioc->sense_len) {
4783                 sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
4784                                              &sense_handle, GFP_KERNEL);
4785                 if (!sense) {
4786                         error = -ENOMEM;
4787                         goto out;
4788                 }
4789
4790                 sense_ptr =
4791                 (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
4792                 *sense_ptr = sense_handle;
4793         }
4794
4795         /*
4796          * Set the sync_cmd flag so that the ISR knows not to complete this
4797          * cmd to the SCSI mid-layer
4798          */
4799         cmd->sync_cmd = 1;
4800         megasas_issue_blocked_cmd(instance, cmd);
4801         cmd->sync_cmd = 0;
4802
4803         /*
4804          * copy out the kernel buffers to user buffers
4805          */
4806         for (i = 0; i < ioc->sge_count; i++) {
4807                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
4808                                  ioc->sgl[i].iov_len)) {
4809                         error = -EFAULT;
4810                         goto out;
4811                 }
4812         }
4813
4814         /*
4815          * copy out the sense
4816          */
4817         if (ioc->sense_len) {
4818                 /*
4819                  * sense_ptr points to the location that has the user
4820                  * sense buffer address
4821                  */
4822                 sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
4823                                 ioc->sense_off);
4824
4825                 if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
4826                                  sense, ioc->sense_len)) {
4827                         printk(KERN_ERR "megasas: Failed to copy out to user "
4828                                         "sense data\n");
4829                         error = -EFAULT;
4830                         goto out;
4831                 }
4832         }
4833
4834         /*
4835          * copy the status codes returned by the fw
4836          */
4837         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
4838                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
4839                 printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
4840                 error = -EFAULT;
4841         }
4842
4843       out:
4844         if (sense) {
4845                 dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
4846                                     sense, sense_handle);
4847         }
4848
4849         for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
4850                 dma_free_coherent(&instance->pdev->dev,
4851                                     kern_sge32[i].length,
4852                                     kbuff_arr[i], kern_sge32[i].phys_addr);
4853         }
4854
4855         megasas_return_cmd(instance, cmd);
4856         return error;
4857 }
4858
4859 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
4860 {
4861         struct megasas_iocpacket __user *user_ioc =
4862             (struct megasas_iocpacket __user *)arg;
4863         struct megasas_iocpacket *ioc;
4864         struct megasas_instance *instance;
4865         int error;
4866         int i;
4867         unsigned long flags;
4868         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
4869
4870         ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
4871         if (!ioc)
4872                 return -ENOMEM;
4873
4874         if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
4875                 error = -EFAULT;
4876                 goto out_kfree_ioc;
4877         }
4878
4879         instance = megasas_lookup_instance(ioc->host_no);
4880         if (!instance) {
4881                 error = -ENODEV;
4882                 goto out_kfree_ioc;
4883         }
4884
4885         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
4886                 printk(KERN_ERR "Controller in crit error\n");
4887                 error = -ENODEV;
4888                 goto out_kfree_ioc;
4889         }
4890
4891         if (instance->unload == 1) {
4892                 error = -ENODEV;
4893                 goto out_kfree_ioc;
4894         }
4895
4896         /*
4897          * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
4898          */
4899         if (down_interruptible(&instance->ioctl_sem)) {
4900                 error = -ERESTARTSYS;
4901                 goto out_kfree_ioc;
4902         }
4903
4904         for (i = 0; i < wait_time; i++) {
4905
4906                 spin_lock_irqsave(&instance->hba_lock, flags);
4907                 if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
4908                         spin_unlock_irqrestore(&instance->hba_lock, flags);
4909                         break;
4910                 }
4911                 spin_unlock_irqrestore(&instance->hba_lock, flags);
4912
4913                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
4914                         printk(KERN_NOTICE "megasas: waiting"
4915                                 "for controller reset to finish\n");
4916                 }
4917
4918                 msleep(1000);
4919         }
4920
4921         spin_lock_irqsave(&instance->hba_lock, flags);
4922         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
4923                 spin_unlock_irqrestore(&instance->hba_lock, flags);
4924
4925                 printk(KERN_ERR "megaraid_sas: timed out while"
4926                         "waiting for HBA to recover\n");
4927                 error = -ENODEV;
4928                 goto out_kfree_ioc;
4929         }
4930         spin_unlock_irqrestore(&instance->hba_lock, flags);
4931
4932         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
4933         up(&instance->ioctl_sem);
4934
4935       out_kfree_ioc:
4936         kfree(ioc);
4937         return error;
4938 }
4939
4940 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
4941 {
4942         struct megasas_instance *instance;
4943         struct megasas_aen aen;
4944         int error;
4945         int i;
4946         unsigned long flags;
4947         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
4948
4949         if (file->private_data != file) {
4950                 printk(KERN_DEBUG "megasas: fasync_helper was not "
4951                        "called first\n");
4952                 return -EINVAL;
4953         }
4954
4955         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
4956                 return -EFAULT;
4957
4958         instance = megasas_lookup_instance(aen.host_no);
4959
4960         if (!instance)
4961                 return -ENODEV;
4962
4963         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
4964                 return -ENODEV;
4965         }
4966
4967         if (instance->unload == 1) {
4968                 return -ENODEV;
4969         }
4970
4971         for (i = 0; i < wait_time; i++) {
4972
4973                 spin_lock_irqsave(&instance->hba_lock, flags);
4974                 if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
4975                         spin_unlock_irqrestore(&instance->hba_lock,
4976                                                 flags);
4977                         break;
4978                 }
4979
4980                 spin_unlock_irqrestore(&instance->hba_lock, flags);
4981
4982                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
4983                         printk(KERN_NOTICE "megasas: waiting for"
4984                                 "controller reset to finish\n");
4985                 }
4986
4987                 msleep(1000);
4988         }
4989
4990         spin_lock_irqsave(&instance->hba_lock, flags);
4991         if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
4992                 spin_unlock_irqrestore(&instance->hba_lock, flags);
4993                 printk(KERN_ERR "megaraid_sas: timed out while waiting"
4994                                 "for HBA to recover.\n");
4995                 return -ENODEV;
4996         }
4997         spin_unlock_irqrestore(&instance->hba_lock, flags);
4998
4999         mutex_lock(&instance->aen_mutex);
5000         error = megasas_register_aen(instance, aen.seq_num,
5001                                      aen.class_locale_word);
5002         mutex_unlock(&instance->aen_mutex);
5003         return error;
5004 }
5005
5006 /**
5007  * megasas_mgmt_ioctl - char node ioctl entry point
5008  */
5009 static long
5010 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5011 {
5012         switch (cmd) {
5013         case MEGASAS_IOC_FIRMWARE:
5014                 return megasas_mgmt_ioctl_fw(file, arg);
5015
5016         case MEGASAS_IOC_GET_AEN:
5017                 return megasas_mgmt_ioctl_aen(file, arg);
5018         }
5019
5020         return -ENOTTY;
5021 }
5022
5023 #ifdef CONFIG_COMPAT
5024 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
5025 {
5026         struct compat_megasas_iocpacket __user *cioc =
5027             (struct compat_megasas_iocpacket __user *)arg;
5028         struct megasas_iocpacket __user *ioc =
5029             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
5030         int i;
5031         int error = 0;
5032         compat_uptr_t ptr;
5033
5034         if (clear_user(ioc, sizeof(*ioc)))
5035                 return -EFAULT;
5036
5037         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
5038             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
5039             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
5040             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
5041             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
5042             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
5043                 return -EFAULT;
5044
5045         /*
5046          * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
5047          * sense_len is not null, so prepare the 64bit value under
5048          * the same condition.
5049          */
5050         if (ioc->sense_len) {
5051                 void __user **sense_ioc_ptr =
5052                         (void __user **)(ioc->frame.raw + ioc->sense_off);
5053                 compat_uptr_t *sense_cioc_ptr =
5054                         (compat_uptr_t *)(cioc->frame.raw + cioc->sense_off);
5055                 if (get_user(ptr, sense_cioc_ptr) ||
5056                     put_user(compat_ptr(ptr), sense_ioc_ptr))
5057                         return -EFAULT;
5058         }
5059
5060         for (i = 0; i < MAX_IOCTL_SGE; i++) {
5061                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
5062                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
5063                     copy_in_user(&ioc->sgl[i].iov_len,
5064                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
5065                         return -EFAULT;
5066         }
5067
5068         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
5069
5070         if (copy_in_user(&cioc->frame.hdr.cmd_status,
5071                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
5072                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
5073                 return -EFAULT;
5074         }
5075         return error;
5076 }
5077
5078 static long
5079 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
5080                           unsigned long arg)
5081 {
5082         switch (cmd) {
5083         case MEGASAS_IOC_FIRMWARE32:
5084                 return megasas_mgmt_compat_ioctl_fw(file, arg);
5085         case MEGASAS_IOC_GET_AEN:
5086                 return megasas_mgmt_ioctl_aen(file, arg);
5087         }
5088
5089         return -ENOTTY;
5090 }
5091 #endif
5092
5093 /*
5094  * File operations structure for management interface
5095  */
5096 static const struct file_operations megasas_mgmt_fops = {
5097         .owner = THIS_MODULE,
5098         .open = megasas_mgmt_open,
5099         .fasync = megasas_mgmt_fasync,
5100         .unlocked_ioctl = megasas_mgmt_ioctl,
5101         .poll = megasas_mgmt_poll,
5102 #ifdef CONFIG_COMPAT
5103         .compat_ioctl = megasas_mgmt_compat_ioctl,
5104 #endif
5105         .llseek = noop_llseek,
5106 };
5107
5108 /*
5109  * PCI hotplug support registration structure
5110  */
5111 static struct pci_driver megasas_pci_driver = {
5112
5113         .name = "megaraid_sas",
5114         .id_table = megasas_pci_table,
5115         .probe = megasas_probe_one,
5116         .remove = __devexit_p(megasas_detach_one),
5117         .suspend = megasas_suspend,
5118         .resume = megasas_resume,
5119         .shutdown = megasas_shutdown,
5120 };
5121
5122 /*
5123  * Sysfs driver attributes
5124  */
5125 static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
5126 {
5127         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
5128                         MEGASAS_VERSION);
5129 }
5130
5131 static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
5132
5133 static ssize_t
5134 megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
5135 {
5136         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
5137                         MEGASAS_RELDATE);
5138 }
5139
5140 static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
5141                    NULL);
5142
5143 static ssize_t
5144 megasas_sysfs_show_support_poll_for_event(struct device_driver *dd, char *buf)
5145 {
5146         return sprintf(buf, "%u\n", support_poll_for_event);
5147 }
5148
5149 static DRIVER_ATTR(support_poll_for_event, S_IRUGO,
5150                         megasas_sysfs_show_support_poll_for_event, NULL);
5151
5152  static ssize_t
5153 megasas_sysfs_show_support_device_change(struct device_driver *dd, char *buf)
5154 {
5155         return sprintf(buf, "%u\n", support_device_change);
5156 }
5157
5158 static DRIVER_ATTR(support_device_change, S_IRUGO,
5159                         megasas_sysfs_show_support_device_change, NULL);
5160
5161 static ssize_t
5162 megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
5163 {
5164         return sprintf(buf, "%u\n", megasas_dbg_lvl);
5165 }
5166
5167 static ssize_t
5168 megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
5169 {
5170         int retval = count;
5171         if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
5172                 printk(KERN_ERR "megasas: could not set dbg_lvl\n");
5173                 retval = -EINVAL;
5174         }
5175         return retval;
5176 }
5177
5178 static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl,
5179                 megasas_sysfs_set_dbg_lvl);
5180
5181 static void
5182 megasas_aen_polling(struct work_struct *work)
5183 {
5184         struct megasas_aen_event *ev =
5185                 container_of(work, struct megasas_aen_event, hotplug_work);
5186         struct megasas_instance *instance = ev->instance;
5187         union megasas_evt_class_locale class_locale;
5188         struct  Scsi_Host *host;
5189         struct  scsi_device *sdev1;
5190         u16     pd_index = 0;
5191         u16     ld_index = 0;
5192         int     i, j, doscan = 0;
5193         u32 seq_num;
5194         int error;
5195
5196         if (!instance) {
5197                 printk(KERN_ERR "invalid instance!\n");
5198                 kfree(ev);
5199                 return;
5200         }
5201         instance->ev = NULL;
5202         host = instance->host;
5203         if (instance->evt_detail) {
5204
5205                 switch (instance->evt_detail->code) {
5206                 case MR_EVT_PD_INSERTED:
5207                         if (megasas_get_pd_list(instance) == 0) {
5208                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
5209                                 for (j = 0;
5210                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
5211                                 j++) {
5212
5213                                 pd_index =
5214                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
5215
5216                                 sdev1 =
5217                                 scsi_device_lookup(host, i, j, 0);
5218
5219                                 if (instance->pd_list[pd_index].driveState
5220                                                 == MR_PD_STATE_SYSTEM) {
5221                                                 if (!sdev1) {
5222                                                 scsi_add_device(host, i, j, 0);
5223                                                 }
5224
5225                                         if (sdev1)
5226                                                 scsi_device_put(sdev1);
5227                                         }
5228                                 }
5229                         }
5230                         }
5231                         doscan = 0;
5232                         break;
5233
5234                 case MR_EVT_PD_REMOVED:
5235                         if (megasas_get_pd_list(instance) == 0) {
5236                         megasas_get_pd_list(instance);
5237                         for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
5238                                 for (j = 0;
5239                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
5240                                 j++) {
5241
5242                                 pd_index =
5243                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
5244
5245                                 sdev1 =
5246                                 scsi_device_lookup(host, i, j, 0);
5247
5248                                 if (instance->pd_list[pd_index].driveState
5249                                         == MR_PD_STATE_SYSTEM) {
5250                                         if (sdev1) {
5251                                                 scsi_device_put(sdev1);
5252                                         }
5253                                 } else {
5254                                         if (sdev1) {
5255                                                 scsi_remove_device(sdev1);
5256                                                 scsi_device_put(sdev1);
5257                                         }
5258                                 }
5259                                 }
5260                         }
5261                         }
5262                         doscan = 0;
5263                         break;
5264
5265                 case MR_EVT_LD_OFFLINE:
5266                 case MR_EVT_CFG_CLEARED:
5267                 case MR_EVT_LD_DELETED:
5268                         megasas_get_ld_list(instance);
5269                         for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
5270                                 for (j = 0;
5271                                 j < MEGASAS_MAX_DEV_PER_CHANNEL;
5272                                 j++) {
5273
5274                                 ld_index =
5275                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
5276
5277                                 sdev1 = scsi_device_lookup(host,
5278                                         i + MEGASAS_MAX_LD_CHANNELS,
5279                                         j,
5280                                         0);
5281
5282                                 if (instance->ld_ids[ld_index] != 0xff) {
5283                                         if (sdev1) {
5284                                                 scsi_device_put(sdev1);
5285                                         }
5286                                 } else {
5287                                         if (sdev1) {
5288                                                 scsi_remove_device(sdev1);
5289                                                 scsi_device_put(sdev1);
5290                                         }
5291                                 }
5292                                 }
5293                         }
5294                         doscan = 0;
5295                         break;
5296                 case MR_EVT_LD_CREATED:
5297                         megasas_get_ld_list(instance);
5298                         for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
5299                                 for (j = 0;
5300                                         j < MEGASAS_MAX_DEV_PER_CHANNEL;
5301                                         j++) {
5302                                         ld_index =
5303                                         (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
5304
5305                                         sdev1 = scsi_device_lookup(host,
5306                                                 i+MEGASAS_MAX_LD_CHANNELS,
5307                                                 j, 0);
5308
5309                                         if (instance->ld_ids[ld_index] !=
5310                                                                 0xff) {
5311                                                 if (!sdev1) {
5312                                                         scsi_add_device(host,
5313                                                                 i + 2,
5314                                                                 j, 0);
5315                                                 }
5316                                         }
5317                                         if (sdev1) {
5318                                                 scsi_device_put(sdev1);
5319                                         }
5320                                 }
5321                         }
5322                         doscan = 0;
5323                         break;
5324                 case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
5325                 case MR_EVT_FOREIGN_CFG_IMPORTED:
5326                 case MR_EVT_LD_STATE_CHANGE:
5327                         doscan = 1;
5328                         break;
5329                 default:
5330                         doscan = 0;
5331                         break;
5332                 }
5333         } else {
5334                 printk(KERN_ERR "invalid evt_detail!\n");
5335                 kfree(ev);
5336                 return;
5337         }
5338
5339         if (doscan) {
5340                 printk(KERN_INFO "scanning ...\n");
5341                 megasas_get_pd_list(instance);
5342                 for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
5343                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
5344                                 pd_index = i*MEGASAS_MAX_DEV_PER_CHANNEL + j;
5345                                 sdev1 = scsi_device_lookup(host, i, j, 0);
5346                                 if (instance->pd_list[pd_index].driveState ==
5347                                                         MR_PD_STATE_SYSTEM) {
5348                                         if (!sdev1) {
5349                                                 scsi_add_device(host, i, j, 0);
5350                                         }
5351                                         if (sdev1)
5352                                                 scsi_device_put(sdev1);
5353                                 } else {
5354                                         if (sdev1) {
5355                                                 scsi_remove_device(sdev1);
5356                                                 scsi_device_put(sdev1);
5357                                         }
5358                                 }
5359                         }
5360                 }
5361
5362                 megasas_get_ld_list(instance);
5363                 for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
5364                         for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
5365                                 ld_index =
5366                                 (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
5367
5368                                 sdev1 = scsi_device_lookup(host,
5369                                         i+MEGASAS_MAX_LD_CHANNELS, j, 0);
5370                                 if (instance->ld_ids[ld_index] != 0xff) {
5371                                         if (!sdev1) {
5372                                                 scsi_add_device(host,
5373                                                                 i+2,
5374                                                                 j, 0);
5375                                         } else {
5376                                                 scsi_device_put(sdev1);
5377                                         }
5378                                 } else {
5379                                         if (sdev1) {
5380                                                 scsi_remove_device(sdev1);
5381                                                 scsi_device_put(sdev1);
5382                                         }
5383                                 }
5384                         }
5385                 }
5386         }
5387
5388         if ( instance->aen_cmd != NULL ) {
5389                 kfree(ev);
5390                 return ;
5391         }
5392
5393         seq_num = instance->evt_detail->seq_num + 1;
5394
5395         /* Register AEN with FW for latest sequence number plus 1 */
5396         class_locale.members.reserved = 0;
5397         class_locale.members.locale = MR_EVT_LOCALE_ALL;
5398         class_locale.members.class = MR_EVT_CLASS_DEBUG;
5399         mutex_lock(&instance->aen_mutex);
5400         error = megasas_register_aen(instance, seq_num,
5401                                         class_locale.word);
5402         mutex_unlock(&instance->aen_mutex);
5403
5404         if (error)
5405                 printk(KERN_ERR "register aen failed error %x\n", error);
5406
5407         kfree(ev);
5408 }
5409
5410 /**
5411  * megasas_init - Driver load entry point
5412  */
5413 static int __init megasas_init(void)
5414 {
5415         int rval;
5416
5417         /*
5418          * Announce driver version and other information
5419          */
5420         printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
5421                MEGASAS_EXT_VERSION);
5422
5423         spin_lock_init(&poll_aen_lock);
5424
5425         support_poll_for_event = 2;
5426         support_device_change = 1;
5427
5428         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
5429
5430         /*
5431          * Register character device node
5432          */
5433         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
5434
5435         if (rval < 0) {
5436                 printk(KERN_DEBUG "megasas: failed to open device node\n");
5437                 return rval;
5438         }
5439
5440         megasas_mgmt_majorno = rval;
5441
5442         /*
5443          * Register ourselves as PCI hotplug module
5444          */
5445         rval = pci_register_driver(&megasas_pci_driver);
5446
5447         if (rval) {
5448                 printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
5449                 goto err_pcidrv;
5450         }
5451
5452         rval = driver_create_file(&megasas_pci_driver.driver,
5453                                   &driver_attr_version);
5454         if (rval)
5455                 goto err_dcf_attr_ver;
5456         rval = driver_create_file(&megasas_pci_driver.driver,
5457                                   &driver_attr_release_date);
5458         if (rval)
5459                 goto err_dcf_rel_date;
5460
5461         rval = driver_create_file(&megasas_pci_driver.driver,
5462                                 &driver_attr_support_poll_for_event);
5463         if (rval)
5464                 goto err_dcf_support_poll_for_event;
5465
5466         rval = driver_create_file(&megasas_pci_driver.driver,
5467                                   &driver_attr_dbg_lvl);
5468         if (rval)
5469                 goto err_dcf_dbg_lvl;
5470         rval = driver_create_file(&megasas_pci_driver.driver,
5471                                 &driver_attr_support_device_change);
5472         if (rval)
5473                 goto err_dcf_support_device_change;
5474
5475         return rval;
5476
5477 err_dcf_support_device_change:
5478         driver_remove_file(&megasas_pci_driver.driver,
5479                            &driver_attr_dbg_lvl);
5480 err_dcf_dbg_lvl:
5481         driver_remove_file(&megasas_pci_driver.driver,
5482                         &driver_attr_support_poll_for_event);
5483
5484 err_dcf_support_poll_for_event:
5485         driver_remove_file(&megasas_pci_driver.driver,
5486                            &driver_attr_release_date);
5487
5488 err_dcf_rel_date:
5489         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
5490 err_dcf_attr_ver:
5491         pci_unregister_driver(&megasas_pci_driver);
5492 err_pcidrv:
5493         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
5494         return rval;
5495 }
5496
5497 /**
5498  * megasas_exit - Driver unload entry point
5499  */
5500 static void __exit megasas_exit(void)
5501 {
5502         driver_remove_file(&megasas_pci_driver.driver,
5503                            &driver_attr_dbg_lvl);
5504         driver_remove_file(&megasas_pci_driver.driver,
5505                         &driver_attr_support_poll_for_event);
5506         driver_remove_file(&megasas_pci_driver.driver,
5507                         &driver_attr_support_device_change);
5508         driver_remove_file(&megasas_pci_driver.driver,
5509                            &driver_attr_release_date);
5510         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
5511
5512         pci_unregister_driver(&megasas_pci_driver);
5513         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
5514 }
5515
5516 module_init(megasas_init);
5517 module_exit(megasas_exit);