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