Version:  2.0.40 2.2.26 2.4.37 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 3.19

Linux/drivers/scsi/megaraid/megaraid_sas_base.c

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