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