]> Pileus Git - ~andy/linux/blob - drivers/scsi/megaraid/megaraid_sas_fusion.c
d6e2a663b1651692e94d801e301b8e18717df606
[~andy/linux] / drivers / scsi / megaraid / megaraid_sas_fusion.c
1 /*
2  *  Linux MegaRAID driver for SAS based RAID controllers
3  *
4  *  Copyright (c) 2009-2011  LSI Corporation.
5  *
6  *  This program is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU General Public License
8  *  as published by the Free Software Foundation; either version 2
9  *  of the License, or (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  *  FILE: megaraid_sas_fusion.c
21  *
22  *  Authors: LSI Corporation
23  *           Sumant Patro
24  *           Adam Radford <linuxraid@lsi.com>
25  *
26  *  Send feedback to: <megaraidlinux@lsi.com>
27  *
28  *  Mail to: LSI Corporation, 1621 Barber Lane, Milpitas, CA 95035
29  *     ATTN: Linuxraid
30  */
31
32 #include <linux/kernel.h>
33 #include <linux/types.h>
34 #include <linux/pci.h>
35 #include <linux/list.h>
36 #include <linux/moduleparam.h>
37 #include <linux/module.h>
38 #include <linux/spinlock.h>
39 #include <linux/interrupt.h>
40 #include <linux/delay.h>
41 #include <linux/uio.h>
42 #include <linux/uaccess.h>
43 #include <linux/fs.h>
44 #include <linux/compat.h>
45 #include <linux/blkdev.h>
46 #include <linux/mutex.h>
47 #include <linux/poll.h>
48
49 #include <scsi/scsi.h>
50 #include <scsi/scsi_cmnd.h>
51 #include <scsi/scsi_device.h>
52 #include <scsi/scsi_host.h>
53
54 #include "megaraid_sas_fusion.h"
55 #include "megaraid_sas.h"
56
57 extern void megasas_free_cmds(struct megasas_instance *instance);
58 extern struct megasas_cmd *megasas_get_cmd(struct megasas_instance
59                                            *instance);
60 extern void
61 megasas_complete_cmd(struct megasas_instance *instance,
62                      struct megasas_cmd *cmd, u8 alt_status);
63 int megasas_is_ldio(struct scsi_cmnd *cmd);
64 int
65 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd);
66
67 void
68 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd);
69 int megasas_alloc_cmds(struct megasas_instance *instance);
70 int
71 megasas_clear_intr_fusion(struct megasas_register_set __iomem *regs);
72 int
73 megasas_issue_polled(struct megasas_instance *instance,
74                      struct megasas_cmd *cmd);
75
76 u8
77 MR_BuildRaidContext(struct IO_REQUEST_INFO *io_info,
78                     struct RAID_CONTEXT *pRAID_Context,
79                     struct MR_FW_RAID_MAP_ALL *map);
80 u16 MR_TargetIdToLdGet(u32 ldTgtId, struct MR_FW_RAID_MAP_ALL *map);
81 struct MR_LD_RAID *MR_LdRaidGet(u32 ld, struct MR_FW_RAID_MAP_ALL *map);
82
83 u16 MR_GetLDTgtId(u32 ld, struct MR_FW_RAID_MAP_ALL *map);
84 u8 MR_ValidateMapInfo(struct MR_FW_RAID_MAP_ALL *map,
85                       struct LD_LOAD_BALANCE_INFO *lbInfo);
86 u16 get_updated_dev_handle(struct LD_LOAD_BALANCE_INFO *lbInfo,
87                            struct IO_REQUEST_INFO *in_info);
88 int megasas_transition_to_ready(struct megasas_instance *instance);
89 void megaraid_sas_kill_hba(struct megasas_instance *instance);
90
91 extern u32 megasas_dbg_lvl;
92
93 /**
94  * megasas_enable_intr_fusion - Enables interrupts
95  * @regs:                       MFI register set
96  */
97 void
98 megasas_enable_intr_fusion(struct megasas_register_set __iomem *regs)
99 {
100         writel(~MFI_FUSION_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
101
102         /* Dummy readl to force pci flush */
103         readl(&regs->outbound_intr_mask);
104 }
105
106 /**
107  * megasas_disable_intr_fusion - Disables interrupt
108  * @regs:                        MFI register set
109  */
110 void
111 megasas_disable_intr_fusion(struct megasas_register_set __iomem *regs)
112 {
113         u32 mask = 0xFFFFFFFF;
114         u32 status;
115
116         writel(mask, &regs->outbound_intr_mask);
117         /* Dummy readl to force pci flush */
118         status = readl(&regs->outbound_intr_mask);
119 }
120
121 int
122 megasas_clear_intr_fusion(struct megasas_register_set __iomem *regs)
123 {
124         u32 status;
125         /*
126          * Check if it is our interrupt
127          */
128         status = readl(&regs->outbound_intr_status);
129
130         if (status & 1) {
131                 writel(status, &regs->outbound_intr_status);
132                 readl(&regs->outbound_intr_status);
133                 return 1;
134         }
135         if (!(status & MFI_FUSION_ENABLE_INTERRUPT_MASK))
136                 return 0;
137
138         /*
139          * dummy read to flush PCI
140          */
141         readl(&regs->outbound_intr_status);
142
143         return 1;
144 }
145
146 /**
147  * megasas_get_cmd_fusion -     Get a command from the free pool
148  * @instance:           Adapter soft state
149  *
150  * Returns a free command from the pool
151  */
152 struct megasas_cmd_fusion *megasas_get_cmd_fusion(struct megasas_instance
153                                                   *instance)
154 {
155         unsigned long flags;
156         struct fusion_context *fusion =
157                 (struct fusion_context *)instance->ctrl_context;
158         struct megasas_cmd_fusion *cmd = NULL;
159
160         spin_lock_irqsave(&fusion->cmd_pool_lock, flags);
161
162         if (!list_empty(&fusion->cmd_pool)) {
163                 cmd = list_entry((&fusion->cmd_pool)->next,
164                                  struct megasas_cmd_fusion, list);
165                 list_del_init(&cmd->list);
166         } else {
167                 printk(KERN_ERR "megasas: Command pool (fusion) empty!\n");
168         }
169
170         spin_unlock_irqrestore(&fusion->cmd_pool_lock, flags);
171         return cmd;
172 }
173
174 /**
175  * megasas_return_cmd_fusion -  Return a cmd to free command pool
176  * @instance:           Adapter soft state
177  * @cmd:                Command packet to be returned to free command pool
178  */
179 static inline void
180 megasas_return_cmd_fusion(struct megasas_instance *instance,
181                           struct megasas_cmd_fusion *cmd)
182 {
183         unsigned long flags;
184         struct fusion_context *fusion =
185                 (struct fusion_context *)instance->ctrl_context;
186
187         spin_lock_irqsave(&fusion->cmd_pool_lock, flags);
188
189         cmd->scmd = NULL;
190         cmd->sync_cmd_idx = (u32)ULONG_MAX;
191         list_add_tail(&cmd->list, &fusion->cmd_pool);
192
193         spin_unlock_irqrestore(&fusion->cmd_pool_lock, flags);
194 }
195
196 /**
197  * megasas_teardown_frame_pool_fusion - Destroy the cmd frame DMA pool
198  * @instance:                           Adapter soft state
199  */
200 static void megasas_teardown_frame_pool_fusion(
201         struct megasas_instance *instance)
202 {
203         int i;
204         struct fusion_context *fusion = instance->ctrl_context;
205
206         u16 max_cmd = instance->max_fw_cmds;
207
208         struct megasas_cmd_fusion *cmd;
209
210         if (!fusion->sg_dma_pool || !fusion->sense_dma_pool) {
211                 printk(KERN_ERR "megasas: dma pool is null. SG Pool %p, "
212                        "sense pool : %p\n", fusion->sg_dma_pool,
213                        fusion->sense_dma_pool);
214                 return;
215         }
216
217         /*
218          * Return all frames to pool
219          */
220         for (i = 0; i < max_cmd; i++) {
221
222                 cmd = fusion->cmd_list[i];
223
224                 if (cmd->sg_frame)
225                         pci_pool_free(fusion->sg_dma_pool, cmd->sg_frame,
226                                       cmd->sg_frame_phys_addr);
227
228                 if (cmd->sense)
229                         pci_pool_free(fusion->sense_dma_pool, cmd->sense,
230                                       cmd->sense_phys_addr);
231         }
232
233         /*
234          * Now destroy the pool itself
235          */
236         pci_pool_destroy(fusion->sg_dma_pool);
237         pci_pool_destroy(fusion->sense_dma_pool);
238
239         fusion->sg_dma_pool = NULL;
240         fusion->sense_dma_pool = NULL;
241 }
242
243 /**
244  * megasas_free_cmds_fusion -   Free all the cmds in the free cmd pool
245  * @instance:           Adapter soft state
246  */
247 void
248 megasas_free_cmds_fusion(struct megasas_instance *instance)
249 {
250         int i;
251         struct fusion_context *fusion = instance->ctrl_context;
252
253         u32 max_cmds, req_sz, reply_sz, io_frames_sz;
254
255
256         req_sz = fusion->request_alloc_sz;
257         reply_sz = fusion->reply_alloc_sz;
258         io_frames_sz = fusion->io_frames_alloc_sz;
259
260         max_cmds = instance->max_fw_cmds;
261
262         /* Free descriptors and request Frames memory */
263         if (fusion->req_frames_desc)
264                 dma_free_coherent(&instance->pdev->dev, req_sz,
265                                   fusion->req_frames_desc,
266                                   fusion->req_frames_desc_phys);
267
268         if (fusion->reply_frames_desc) {
269                 pci_pool_free(fusion->reply_frames_desc_pool,
270                               fusion->reply_frames_desc,
271                               fusion->reply_frames_desc_phys);
272                 pci_pool_destroy(fusion->reply_frames_desc_pool);
273         }
274
275         if (fusion->io_request_frames) {
276                 pci_pool_free(fusion->io_request_frames_pool,
277                               fusion->io_request_frames,
278                               fusion->io_request_frames_phys);
279                 pci_pool_destroy(fusion->io_request_frames_pool);
280         }
281
282         /* Free the Fusion frame pool */
283         megasas_teardown_frame_pool_fusion(instance);
284
285         /* Free all the commands in the cmd_list */
286         for (i = 0; i < max_cmds; i++)
287                 kfree(fusion->cmd_list[i]);
288
289         /* Free the cmd_list buffer itself */
290         kfree(fusion->cmd_list);
291         fusion->cmd_list = NULL;
292
293         INIT_LIST_HEAD(&fusion->cmd_pool);
294 }
295
296 /**
297  * megasas_create_frame_pool_fusion -   Creates DMA pool for cmd frames
298  * @instance:                   Adapter soft state
299  *
300  */
301 static int megasas_create_frame_pool_fusion(struct megasas_instance *instance)
302 {
303         int i;
304         u32 max_cmd;
305         struct fusion_context *fusion;
306         struct megasas_cmd_fusion *cmd;
307         u32 total_sz_chain_frame;
308
309         fusion = instance->ctrl_context;
310         max_cmd = instance->max_fw_cmds;
311
312         total_sz_chain_frame = MEGASAS_MAX_SZ_CHAIN_FRAME;
313
314         /*
315          * Use DMA pool facility provided by PCI layer
316          */
317
318         fusion->sg_dma_pool = pci_pool_create("megasas sg pool fusion",
319                                               instance->pdev,
320                                               total_sz_chain_frame, 4,
321                                               0);
322         if (!fusion->sg_dma_pool) {
323                 printk(KERN_DEBUG "megasas: failed to setup request pool "
324                        "fusion\n");
325                 return -ENOMEM;
326         }
327         fusion->sense_dma_pool = pci_pool_create("megasas sense pool fusion",
328                                                  instance->pdev,
329                                                  SCSI_SENSE_BUFFERSIZE, 64, 0);
330
331         if (!fusion->sense_dma_pool) {
332                 printk(KERN_DEBUG "megasas: failed to setup sense pool "
333                        "fusion\n");
334                 pci_pool_destroy(fusion->sg_dma_pool);
335                 fusion->sg_dma_pool = NULL;
336                 return -ENOMEM;
337         }
338
339         /*
340          * Allocate and attach a frame to each of the commands in cmd_list
341          */
342         for (i = 0; i < max_cmd; i++) {
343
344                 cmd = fusion->cmd_list[i];
345
346                 cmd->sg_frame = pci_pool_alloc(fusion->sg_dma_pool,
347                                                GFP_KERNEL,
348                                                &cmd->sg_frame_phys_addr);
349
350                 cmd->sense = pci_pool_alloc(fusion->sense_dma_pool,
351                                             GFP_KERNEL, &cmd->sense_phys_addr);
352                 /*
353                  * megasas_teardown_frame_pool_fusion() takes care of freeing
354                  * whatever has been allocated
355                  */
356                 if (!cmd->sg_frame || !cmd->sense) {
357                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed\n");
358                         megasas_teardown_frame_pool_fusion(instance);
359                         return -ENOMEM;
360                 }
361         }
362         return 0;
363 }
364
365 /**
366  * megasas_alloc_cmds_fusion -  Allocates the command packets
367  * @instance:           Adapter soft state
368  *
369  *
370  * Each frame has a 32-bit field called context. This context is used to get
371  * back the megasas_cmd_fusion from the frame when a frame gets completed
372  * In this driver, the 32 bit values are the indices into an array cmd_list.
373  * This array is used only to look up the megasas_cmd_fusion given the context.
374  * The free commands themselves are maintained in a linked list called cmd_pool.
375  *
376  * cmds are formed in the io_request and sg_frame members of the
377  * megasas_cmd_fusion. The context field is used to get a request descriptor
378  * and is used as SMID of the cmd.
379  * SMID value range is from 1 to max_fw_cmds.
380  */
381 int
382 megasas_alloc_cmds_fusion(struct megasas_instance *instance)
383 {
384         int i, j;
385         u32 max_cmd, io_frames_sz;
386         struct fusion_context *fusion;
387         struct megasas_cmd_fusion *cmd;
388         union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
389         u32 offset;
390         dma_addr_t io_req_base_phys;
391         u8 *io_req_base;
392
393         fusion = instance->ctrl_context;
394
395         max_cmd = instance->max_fw_cmds;
396
397         fusion->req_frames_desc =
398                 dma_alloc_coherent(&instance->pdev->dev,
399                                    fusion->request_alloc_sz,
400                                    &fusion->req_frames_desc_phys, GFP_KERNEL);
401
402         if (!fusion->req_frames_desc) {
403                 printk(KERN_ERR "megasas; Could not allocate memory for "
404                        "request_frames\n");
405                 goto fail_req_desc;
406         }
407
408         fusion->reply_frames_desc_pool =
409                 pci_pool_create("reply_frames pool", instance->pdev,
410                                 fusion->reply_alloc_sz, 16, 0);
411
412         if (!fusion->reply_frames_desc_pool) {
413                 printk(KERN_ERR "megasas; Could not allocate memory for "
414                        "reply_frame pool\n");
415                 goto fail_reply_desc;
416         }
417
418         fusion->reply_frames_desc =
419                 pci_pool_alloc(fusion->reply_frames_desc_pool, GFP_KERNEL,
420                                &fusion->reply_frames_desc_phys);
421         if (!fusion->reply_frames_desc) {
422                 printk(KERN_ERR "megasas; Could not allocate memory for "
423                        "reply_frame pool\n");
424                 pci_pool_destroy(fusion->reply_frames_desc_pool);
425                 goto fail_reply_desc;
426         }
427
428         reply_desc = fusion->reply_frames_desc;
429         for (i = 0; i < fusion->reply_q_depth; i++, reply_desc++)
430                 reply_desc->Words = ULLONG_MAX;
431
432         io_frames_sz = fusion->io_frames_alloc_sz;
433
434         fusion->io_request_frames_pool =
435                 pci_pool_create("io_request_frames pool", instance->pdev,
436                                 fusion->io_frames_alloc_sz, 16, 0);
437
438         if (!fusion->io_request_frames_pool) {
439                 printk(KERN_ERR "megasas: Could not allocate memory for "
440                        "io_request_frame pool\n");
441                 goto fail_io_frames;
442         }
443
444         fusion->io_request_frames =
445                 pci_pool_alloc(fusion->io_request_frames_pool, GFP_KERNEL,
446                                &fusion->io_request_frames_phys);
447         if (!fusion->io_request_frames) {
448                 printk(KERN_ERR "megasas: Could not allocate memory for "
449                        "io_request_frames frames\n");
450                 pci_pool_destroy(fusion->io_request_frames_pool);
451                 goto fail_io_frames;
452         }
453
454         /*
455          * fusion->cmd_list is an array of struct megasas_cmd_fusion pointers.
456          * Allocate the dynamic array first and then allocate individual
457          * commands.
458          */
459         fusion->cmd_list = kmalloc(sizeof(struct megasas_cmd_fusion *)
460                                    *max_cmd, GFP_KERNEL);
461
462         if (!fusion->cmd_list) {
463                 printk(KERN_DEBUG "megasas: out of memory. Could not alloc "
464                        "memory for cmd_list_fusion\n");
465                 goto fail_cmd_list;
466         }
467
468         memset(fusion->cmd_list, 0, sizeof(struct megasas_cmd_fusion *)
469                *max_cmd);
470
471         max_cmd = instance->max_fw_cmds;
472         for (i = 0; i < max_cmd; i++) {
473                 fusion->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd_fusion),
474                                               GFP_KERNEL);
475                 if (!fusion->cmd_list[i]) {
476                         printk(KERN_ERR "Could not alloc cmd list fusion\n");
477
478                         for (j = 0; j < i; j++)
479                                 kfree(fusion->cmd_list[j]);
480
481                         kfree(fusion->cmd_list);
482                         fusion->cmd_list = NULL;
483                         goto fail_cmd_list;
484                 }
485         }
486
487         /* The first 256 bytes (SMID 0) is not used. Don't add to cmd list */
488         io_req_base = fusion->io_request_frames +
489                 MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
490         io_req_base_phys = fusion->io_request_frames_phys +
491                 MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
492
493         /*
494          * Add all the commands to command pool (fusion->cmd_pool)
495          */
496
497         /* SMID 0 is reserved. Set SMID/index from 1 */
498         for (i = 0; i < max_cmd; i++) {
499                 cmd = fusion->cmd_list[i];
500                 offset = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE * i;
501                 memset(cmd, 0, sizeof(struct megasas_cmd_fusion));
502                 cmd->index = i + 1;
503                 cmd->scmd = NULL;
504                 cmd->sync_cmd_idx = (u32)ULONG_MAX; /* Set to Invalid */
505                 cmd->instance = instance;
506                 cmd->io_request =
507                         (struct MPI2_RAID_SCSI_IO_REQUEST *)
508                   (io_req_base + offset);
509                 memset(cmd->io_request, 0,
510                        sizeof(struct MPI2_RAID_SCSI_IO_REQUEST));
511                 cmd->io_request_phys_addr = io_req_base_phys + offset;
512
513                 list_add_tail(&cmd->list, &fusion->cmd_pool);
514         }
515
516         /*
517          * Create a frame pool and assign one frame to each cmd
518          */
519         if (megasas_create_frame_pool_fusion(instance)) {
520                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
521                 megasas_free_cmds_fusion(instance);
522                 goto fail_req_desc;
523         }
524
525         return 0;
526
527 fail_cmd_list:
528         pci_pool_free(fusion->io_request_frames_pool, fusion->io_request_frames,
529                       fusion->io_request_frames_phys);
530         pci_pool_destroy(fusion->io_request_frames_pool);
531 fail_io_frames:
532         dma_free_coherent(&instance->pdev->dev, fusion->request_alloc_sz,
533                           fusion->reply_frames_desc,
534                           fusion->reply_frames_desc_phys);
535         pci_pool_free(fusion->reply_frames_desc_pool,
536                       fusion->reply_frames_desc,
537                       fusion->reply_frames_desc_phys);
538         pci_pool_destroy(fusion->reply_frames_desc_pool);
539
540 fail_reply_desc:
541         dma_free_coherent(&instance->pdev->dev, fusion->request_alloc_sz,
542                           fusion->req_frames_desc,
543                           fusion->req_frames_desc_phys);
544 fail_req_desc:
545         return -ENOMEM;
546 }
547
548 /**
549  * wait_and_poll -      Issues a polling command
550  * @instance:                   Adapter soft state
551  * @cmd:                        Command packet to be issued
552  *
553  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
554  */
555 int
556 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd)
557 {
558         int i;
559         struct megasas_header *frame_hdr = &cmd->frame->hdr;
560
561         u32 msecs = MFI_POLL_TIMEOUT_SECS * 1000;
562
563         /*
564          * Wait for cmd_status to change
565          */
566         for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i += 20) {
567                 rmb();
568                 msleep(20);
569         }
570
571         if (frame_hdr->cmd_status == 0xff)
572                 return -ETIME;
573
574         return 0;
575 }
576
577 /**
578  * megasas_ioc_init_fusion -    Initializes the FW
579  * @instance:           Adapter soft state
580  *
581  * Issues the IOC Init cmd
582  */
583 int
584 megasas_ioc_init_fusion(struct megasas_instance *instance)
585 {
586         struct megasas_init_frame *init_frame;
587         struct MPI2_IOC_INIT_REQUEST *IOCInitMessage;
588         dma_addr_t      ioc_init_handle;
589         u32 context;
590         struct megasas_cmd *cmd;
591         u8 ret;
592         struct fusion_context *fusion;
593         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
594         int i;
595         struct megasas_header *frame_hdr;
596
597         fusion = instance->ctrl_context;
598
599         cmd = megasas_get_cmd(instance);
600
601         if (!cmd) {
602                 printk(KERN_ERR "Could not allocate cmd for INIT Frame\n");
603                 ret = 1;
604                 goto fail_get_cmd;
605         }
606
607         IOCInitMessage =
608           dma_alloc_coherent(&instance->pdev->dev,
609                              sizeof(struct MPI2_IOC_INIT_REQUEST),
610                              &ioc_init_handle, GFP_KERNEL);
611
612         if (!IOCInitMessage) {
613                 printk(KERN_ERR "Could not allocate memory for "
614                        "IOCInitMessage\n");
615                 ret = 1;
616                 goto fail_fw_init;
617         }
618
619         memset(IOCInitMessage, 0, sizeof(struct MPI2_IOC_INIT_REQUEST));
620
621         IOCInitMessage->Function = MPI2_FUNCTION_IOC_INIT;
622         IOCInitMessage->WhoInit = MPI2_WHOINIT_HOST_DRIVER;
623         IOCInitMessage->MsgVersion = MPI2_VERSION;
624         IOCInitMessage->HeaderVersion = MPI2_HEADER_VERSION;
625         IOCInitMessage->SystemRequestFrameSize =
626                 MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE / 4;
627
628         IOCInitMessage->ReplyDescriptorPostQueueDepth = fusion->reply_q_depth;
629         IOCInitMessage->ReplyDescriptorPostQueueAddress =
630                 fusion->reply_frames_desc_phys;
631         IOCInitMessage->SystemRequestFrameBaseAddress =
632                 fusion->io_request_frames_phys;
633
634         init_frame = (struct megasas_init_frame *)cmd->frame;
635         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
636
637         frame_hdr = &cmd->frame->hdr;
638         context = init_frame->context;
639         init_frame->context = context;
640
641         frame_hdr->cmd_status = 0xFF;
642         frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
643
644         init_frame->cmd = MFI_CMD_INIT;
645         init_frame->cmd_status = 0xFF;
646
647         init_frame->queue_info_new_phys_addr_lo = ioc_init_handle;
648         init_frame->data_xfer_len = sizeof(struct MPI2_IOC_INIT_REQUEST);
649
650         req_desc =
651           (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)fusion->req_frames_desc;
652
653         req_desc->Words = cmd->frame_phys_addr;
654         req_desc->MFAIo.RequestFlags =
655                 (MEGASAS_REQ_DESCRIPT_FLAGS_MFA <<
656                  MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
657
658         /*
659          * disable the intr before firing the init frame
660          */
661         instance->instancet->disable_intr(instance->reg_set);
662
663         for (i = 0; i < (10 * 1000); i += 20) {
664                 if (readl(&instance->reg_set->doorbell) & 1)
665                         msleep(20);
666                 else
667                         break;
668         }
669
670         instance->instancet->fire_cmd(instance, req_desc->u.low,
671                                       req_desc->u.high, instance->reg_set);
672
673         wait_and_poll(instance, cmd);
674
675         frame_hdr = &cmd->frame->hdr;
676         if (frame_hdr->cmd_status != 0) {
677                 ret = 1;
678                 goto fail_fw_init;
679         }
680         printk(KERN_ERR "megasas:IOC Init cmd success\n");
681
682         ret = 0;
683
684 fail_fw_init:
685         megasas_return_cmd(instance, cmd);
686         if (IOCInitMessage)
687                 dma_free_coherent(&instance->pdev->dev,
688                                   sizeof(struct MPI2_IOC_INIT_REQUEST),
689                                   IOCInitMessage, ioc_init_handle);
690 fail_get_cmd:
691         return ret;
692 }
693
694 /*
695  * megasas_return_cmd_for_smid -        Returns a cmd_fusion for a SMID
696  * @instance:                           Adapter soft state
697  *
698  */
699 void
700 megasas_return_cmd_for_smid(struct megasas_instance *instance, u16 smid)
701 {
702         struct fusion_context *fusion;
703         struct megasas_cmd_fusion *cmd;
704
705         fusion = instance->ctrl_context;
706         cmd = fusion->cmd_list[smid - 1];
707         megasas_return_cmd_fusion(instance, cmd);
708 }
709
710 /*
711  * megasas_get_ld_map_info -    Returns FW's ld_map structure
712  * @instance:                           Adapter soft state
713  * @pend:                               Pend the command or not
714  * Issues an internal command (DCMD) to get the FW's controller PD
715  * list structure.  This information is mainly used to find out SYSTEM
716  * supported by the FW.
717  */
718 static int
719 megasas_get_ld_map_info(struct megasas_instance *instance)
720 {
721         int ret = 0;
722         struct megasas_cmd *cmd;
723         struct megasas_dcmd_frame *dcmd;
724         struct MR_FW_RAID_MAP_ALL *ci;
725         dma_addr_t ci_h = 0;
726         u32 size_map_info;
727         struct fusion_context *fusion;
728
729         cmd = megasas_get_cmd(instance);
730
731         if (!cmd) {
732                 printk(KERN_DEBUG "megasas: Failed to get cmd for map info.\n");
733                 return -ENOMEM;
734         }
735
736         fusion = instance->ctrl_context;
737
738         if (!fusion) {
739                 megasas_return_cmd(instance, cmd);
740                 return 1;
741         }
742
743         dcmd = &cmd->frame->dcmd;
744
745         size_map_info = sizeof(struct MR_FW_RAID_MAP) +
746                 (sizeof(struct MR_LD_SPAN_MAP) *(MAX_LOGICAL_DRIVES - 1));
747
748         ci = fusion->ld_map[(instance->map_id & 1)];
749         ci_h = fusion->ld_map_phys[(instance->map_id & 1)];
750
751         if (!ci) {
752                 printk(KERN_DEBUG "Failed to alloc mem for ld_map_info\n");
753                 megasas_return_cmd(instance, cmd);
754                 return -ENOMEM;
755         }
756
757         memset(ci, 0, sizeof(*ci));
758         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
759
760         dcmd->cmd = MFI_CMD_DCMD;
761         dcmd->cmd_status = 0xFF;
762         dcmd->sge_count = 1;
763         dcmd->flags = MFI_FRAME_DIR_READ;
764         dcmd->timeout = 0;
765         dcmd->pad_0 = 0;
766         dcmd->data_xfer_len = size_map_info;
767         dcmd->opcode = MR_DCMD_LD_MAP_GET_INFO;
768         dcmd->sgl.sge32[0].phys_addr = ci_h;
769         dcmd->sgl.sge32[0].length = size_map_info;
770
771         if (!megasas_issue_polled(instance, cmd))
772                 ret = 0;
773         else {
774                 printk(KERN_ERR "megasas: Get LD Map Info Failed\n");
775                 ret = -1;
776         }
777
778         megasas_return_cmd(instance, cmd);
779
780         return ret;
781 }
782
783 u8
784 megasas_get_map_info(struct megasas_instance *instance)
785 {
786         struct fusion_context *fusion = instance->ctrl_context;
787
788         fusion->fast_path_io = 0;
789         if (!megasas_get_ld_map_info(instance)) {
790                 if (MR_ValidateMapInfo(fusion->ld_map[(instance->map_id & 1)],
791                                        fusion->load_balance_info)) {
792                         fusion->fast_path_io = 1;
793                         return 0;
794                 }
795         }
796         return 1;
797 }
798
799 /*
800  * megasas_sync_map_info -      Returns FW's ld_map structure
801  * @instance:                           Adapter soft state
802  *
803  * Issues an internal command (DCMD) to get the FW's controller PD
804  * list structure.  This information is mainly used to find out SYSTEM
805  * supported by the FW.
806  */
807 int
808 megasas_sync_map_info(struct megasas_instance *instance)
809 {
810         int ret = 0, i;
811         struct megasas_cmd *cmd;
812         struct megasas_dcmd_frame *dcmd;
813         u32 size_sync_info, num_lds;
814         struct fusion_context *fusion;
815         struct MR_LD_TARGET_SYNC *ci = NULL;
816         struct MR_FW_RAID_MAP_ALL *map;
817         struct MR_LD_RAID  *raid;
818         struct MR_LD_TARGET_SYNC *ld_sync;
819         dma_addr_t ci_h = 0;
820         u32 size_map_info;
821
822         cmd = megasas_get_cmd(instance);
823
824         if (!cmd) {
825                 printk(KERN_DEBUG "megasas: Failed to get cmd for sync"
826                        "info.\n");
827                 return -ENOMEM;
828         }
829
830         fusion = instance->ctrl_context;
831
832         if (!fusion) {
833                 megasas_return_cmd(instance, cmd);
834                 return 1;
835         }
836
837         map = fusion->ld_map[instance->map_id & 1];
838
839         num_lds = map->raidMap.ldCount;
840
841         dcmd = &cmd->frame->dcmd;
842
843         size_sync_info = sizeof(struct MR_LD_TARGET_SYNC) *num_lds;
844
845         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
846
847         ci = (struct MR_LD_TARGET_SYNC *)
848           fusion->ld_map[(instance->map_id - 1) & 1];
849         memset(ci, 0, sizeof(struct MR_FW_RAID_MAP_ALL));
850
851         ci_h = fusion->ld_map_phys[(instance->map_id - 1) & 1];
852
853         ld_sync = (struct MR_LD_TARGET_SYNC *)ci;
854
855         for (i = 0; i < num_lds; i++, ld_sync++) {
856                 raid = MR_LdRaidGet(i, map);
857                 ld_sync->targetId = MR_GetLDTgtId(i, map);
858                 ld_sync->seqNum = raid->seqNum;
859         }
860
861         size_map_info = sizeof(struct MR_FW_RAID_MAP) +
862                 (sizeof(struct MR_LD_SPAN_MAP) *(MAX_LOGICAL_DRIVES - 1));
863
864         dcmd->cmd = MFI_CMD_DCMD;
865         dcmd->cmd_status = 0xFF;
866         dcmd->sge_count = 1;
867         dcmd->flags = MFI_FRAME_DIR_WRITE;
868         dcmd->timeout = 0;
869         dcmd->pad_0 = 0;
870         dcmd->data_xfer_len = size_map_info;
871         dcmd->mbox.b[0] = num_lds;
872         dcmd->mbox.b[1] = MEGASAS_DCMD_MBOX_PEND_FLAG;
873         dcmd->opcode = MR_DCMD_LD_MAP_GET_INFO;
874         dcmd->sgl.sge32[0].phys_addr = ci_h;
875         dcmd->sgl.sge32[0].length = size_map_info;
876
877         instance->map_update_cmd = cmd;
878
879         instance->instancet->issue_dcmd(instance, cmd);
880
881         return ret;
882 }
883
884 /**
885  * megasas_init_adapter_fusion -        Initializes the FW
886  * @instance:           Adapter soft state
887  *
888  * This is the main function for initializing firmware.
889  */
890 u32
891 megasas_init_adapter_fusion(struct megasas_instance *instance)
892 {
893         struct megasas_register_set __iomem *reg_set;
894         struct fusion_context *fusion;
895         u32 max_cmd;
896         int i = 0;
897
898         fusion = instance->ctrl_context;
899
900         reg_set = instance->reg_set;
901
902         /*
903          * Get various operational parameters from status register
904          */
905         instance->max_fw_cmds =
906                 instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
907         instance->max_fw_cmds = min(instance->max_fw_cmds, (u16)1008);
908
909         /*
910          * Reduce the max supported cmds by 1. This is to ensure that the
911          * reply_q_sz (1 more than the max cmd that driver may send)
912          * does not exceed max cmds that the FW can support
913          */
914         instance->max_fw_cmds = instance->max_fw_cmds-1;
915         /* Only internal cmds (DCMD) need to have MFI frames */
916         instance->max_mfi_cmds = MEGASAS_INT_CMDS;
917
918         max_cmd = instance->max_fw_cmds;
919
920         fusion->reply_q_depth = ((max_cmd + 1 + 15)/16)*16;
921
922         fusion->request_alloc_sz =
923                 sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) *max_cmd;
924         fusion->reply_alloc_sz = sizeof(union MPI2_REPLY_DESCRIPTORS_UNION)
925                 *(fusion->reply_q_depth);
926         fusion->io_frames_alloc_sz = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE +
927                 (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE *
928                  (max_cmd + 1)); /* Extra 1 for SMID 0 */
929
930         fusion->max_sge_in_main_msg =
931           (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE -
932            offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL))/16;
933
934         fusion->max_sge_in_chain =
935                 MEGASAS_MAX_SZ_CHAIN_FRAME / sizeof(union MPI2_SGE_IO_UNION);
936
937         instance->max_num_sge = fusion->max_sge_in_main_msg +
938                 fusion->max_sge_in_chain - 2;
939
940         /* Used for pass thru MFI frame (DCMD) */
941         fusion->chain_offset_mfi_pthru =
942                 offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL)/16;
943
944         fusion->chain_offset_io_request =
945                 (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE -
946                  sizeof(union MPI2_SGE_IO_UNION))/16;
947
948         fusion->last_reply_idx = 0;
949
950         /*
951          * Allocate memory for descriptors
952          * Create a pool of commands
953          */
954         if (megasas_alloc_cmds(instance))
955                 goto fail_alloc_mfi_cmds;
956         if (megasas_alloc_cmds_fusion(instance))
957                 goto fail_alloc_cmds;
958
959         if (megasas_ioc_init_fusion(instance))
960                 goto fail_ioc_init;
961
962         instance->flag_ieee = 1;
963
964         fusion->map_sz =  sizeof(struct MR_FW_RAID_MAP) +
965           (sizeof(struct MR_LD_SPAN_MAP) *(MAX_LOGICAL_DRIVES - 1));
966
967         fusion->fast_path_io = 0;
968
969         for (i = 0; i < 2; i++) {
970                 fusion->ld_map[i] = dma_alloc_coherent(&instance->pdev->dev,
971                                                        fusion->map_sz,
972                                                        &fusion->ld_map_phys[i],
973                                                        GFP_KERNEL);
974                 if (!fusion->ld_map[i]) {
975                         printk(KERN_ERR "megasas: Could not allocate memory "
976                                "for map info\n");
977                         goto fail_map_info;
978                 }
979         }
980
981         if (!megasas_get_map_info(instance))
982                 megasas_sync_map_info(instance);
983
984         return 0;
985
986 fail_alloc_cmds:
987 fail_alloc_mfi_cmds:
988 fail_map_info:
989         if (i == 1)
990                 dma_free_coherent(&instance->pdev->dev, fusion->map_sz,
991                                   fusion->ld_map[0], fusion->ld_map_phys[0]);
992 fail_ioc_init:
993         return 1;
994 }
995
996 /**
997  * megasas_fire_cmd_fusion -    Sends command to the FW
998  * @frame_phys_addr :           Physical address of cmd
999  * @frame_count :               Number of frames for the command
1000  * @regs :                      MFI register set
1001  */
1002 void
1003 megasas_fire_cmd_fusion(struct megasas_instance *instance,
1004                         dma_addr_t req_desc_lo,
1005                         u32 req_desc_hi,
1006                         struct megasas_register_set __iomem *regs)
1007 {
1008         unsigned long flags;
1009
1010         spin_lock_irqsave(&instance->hba_lock, flags);
1011
1012         writel(req_desc_lo,
1013                &(regs)->inbound_low_queue_port);
1014         writel(req_desc_hi, &(regs)->inbound_high_queue_port);
1015         spin_unlock_irqrestore(&instance->hba_lock, flags);
1016 }
1017
1018 /**
1019  * map_cmd_status -     Maps FW cmd status to OS cmd status
1020  * @cmd :               Pointer to cmd
1021  * @status :            status of cmd returned by FW
1022  * @ext_status :        ext status of cmd returned by FW
1023  */
1024
1025 void
1026 map_cmd_status(struct megasas_cmd_fusion *cmd, u8 status, u8 ext_status)
1027 {
1028
1029         switch (status) {
1030
1031         case MFI_STAT_OK:
1032                 cmd->scmd->result = DID_OK << 16;
1033                 break;
1034
1035         case MFI_STAT_SCSI_IO_FAILED:
1036         case MFI_STAT_LD_INIT_IN_PROGRESS:
1037                 cmd->scmd->result = (DID_ERROR << 16) | ext_status;
1038                 break;
1039
1040         case MFI_STAT_SCSI_DONE_WITH_ERROR:
1041
1042                 cmd->scmd->result = (DID_OK << 16) | ext_status;
1043                 if (ext_status == SAM_STAT_CHECK_CONDITION) {
1044                         memset(cmd->scmd->sense_buffer, 0,
1045                                SCSI_SENSE_BUFFERSIZE);
1046                         memcpy(cmd->scmd->sense_buffer, cmd->sense,
1047                                SCSI_SENSE_BUFFERSIZE);
1048                         cmd->scmd->result |= DRIVER_SENSE << 24;
1049                 }
1050                 break;
1051
1052         case MFI_STAT_LD_OFFLINE:
1053         case MFI_STAT_DEVICE_NOT_FOUND:
1054                 cmd->scmd->result = DID_BAD_TARGET << 16;
1055                 break;
1056
1057         default:
1058                 printk(KERN_DEBUG "megasas: FW status %#x\n", status);
1059                 cmd->scmd->result = DID_ERROR << 16;
1060                 break;
1061         }
1062 }
1063
1064 /**
1065  * megasas_make_sgl_fusion -    Prepares 32-bit SGL
1066  * @instance:           Adapter soft state
1067  * @scp:                SCSI command from the mid-layer
1068  * @sgl_ptr:            SGL to be filled in
1069  * @cmd:                cmd we are working on
1070  *
1071  * If successful, this function returns the number of SG elements.
1072  */
1073 static int
1074 megasas_make_sgl_fusion(struct megasas_instance *instance,
1075                         struct scsi_cmnd *scp,
1076                         struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr,
1077                         struct megasas_cmd_fusion *cmd)
1078 {
1079         int i, sg_processed;
1080         int sge_count, sge_idx;
1081         struct scatterlist *os_sgl;
1082         struct fusion_context *fusion;
1083
1084         fusion = instance->ctrl_context;
1085
1086         cmd->io_request->ChainOffset = 0;
1087
1088         sge_count = scsi_dma_map(scp);
1089
1090         BUG_ON(sge_count < 0);
1091
1092         if (sge_count > instance->max_num_sge || !sge_count)
1093                 return sge_count;
1094
1095         if (sge_count > fusion->max_sge_in_main_msg) {
1096                 /* One element to store the chain info */
1097                 sge_idx = fusion->max_sge_in_main_msg - 1;
1098         } else
1099                 sge_idx = sge_count;
1100
1101         scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1102                 sgl_ptr->Length = sg_dma_len(os_sgl);
1103                 sgl_ptr->Address = sg_dma_address(os_sgl);
1104                 sgl_ptr->Flags = 0;
1105                 sgl_ptr++;
1106
1107                 sg_processed = i + 1;
1108
1109                 if ((sg_processed ==  (fusion->max_sge_in_main_msg - 1)) &&
1110                     (sge_count > fusion->max_sge_in_main_msg)) {
1111
1112                         struct MPI25_IEEE_SGE_CHAIN64 *sg_chain;
1113                         cmd->io_request->ChainOffset =
1114                                 fusion->chain_offset_io_request;
1115                         sg_chain = sgl_ptr;
1116                         /* Prepare chain element */
1117                         sg_chain->NextChainOffset = 0;
1118                         sg_chain->Flags = (IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1119                                            MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
1120                         sg_chain->Length =  (sizeof(union MPI2_SGE_IO_UNION)
1121                                              *(sge_count - sg_processed));
1122                         sg_chain->Address = cmd->sg_frame_phys_addr;
1123
1124                         sgl_ptr =
1125                           (struct MPI25_IEEE_SGE_CHAIN64 *)cmd->sg_frame;
1126                 }
1127         }
1128
1129         return sge_count;
1130 }
1131
1132 /**
1133  * megasas_set_pd_lba - Sets PD LBA
1134  * @cdb:                CDB
1135  * @cdb_len:            cdb length
1136  * @start_blk:          Start block of IO
1137  *
1138  * Used to set the PD LBA in CDB for FP IOs
1139  */
1140 void
1141 megasas_set_pd_lba(struct MPI2_RAID_SCSI_IO_REQUEST *io_request, u8 cdb_len,
1142                    struct IO_REQUEST_INFO *io_info, struct scsi_cmnd *scp,
1143                    struct MR_FW_RAID_MAP_ALL *local_map_ptr, u32 ref_tag)
1144 {
1145         struct MR_LD_RAID *raid;
1146         u32 ld;
1147         u64 start_blk = io_info->pdBlock;
1148         u8 *cdb = io_request->CDB.CDB32;
1149         u32 num_blocks = io_info->numBlocks;
1150         u8 opcode, flagvals, groupnum, control;
1151
1152         /* Check if T10 PI (DIF) is enabled for this LD */
1153         ld = MR_TargetIdToLdGet(io_info->ldTgtId, local_map_ptr);
1154         raid = MR_LdRaidGet(ld, local_map_ptr);
1155         if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER) {
1156                 memset(cdb, 0, sizeof(io_request->CDB.CDB32));
1157                 cdb[0] =  MEGASAS_SCSI_VARIABLE_LENGTH_CMD;
1158                 cdb[7] =  MEGASAS_SCSI_ADDL_CDB_LEN;
1159
1160                 if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1161                         cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_READ32;
1162                 else
1163                         cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_WRITE32;
1164                 cdb[10] = MEGASAS_RD_WR_PROTECT_CHECK_ALL;
1165
1166                 /* LBA */
1167                 cdb[12] = (u8)((start_blk >> 56) & 0xff);
1168                 cdb[13] = (u8)((start_blk >> 48) & 0xff);
1169                 cdb[14] = (u8)((start_blk >> 40) & 0xff);
1170                 cdb[15] = (u8)((start_blk >> 32) & 0xff);
1171                 cdb[16] = (u8)((start_blk >> 24) & 0xff);
1172                 cdb[17] = (u8)((start_blk >> 16) & 0xff);
1173                 cdb[18] = (u8)((start_blk >> 8) & 0xff);
1174                 cdb[19] = (u8)(start_blk & 0xff);
1175
1176                 /* Logical block reference tag */
1177                 io_request->CDB.EEDP32.PrimaryReferenceTag =
1178                         cpu_to_be32(ref_tag);
1179                 io_request->CDB.EEDP32.PrimaryApplicationTagMask = 0xffff;
1180
1181                 io_request->DataLength = num_blocks * 512;
1182                 io_request->IoFlags = 32; /* Specify 32-byte cdb */
1183
1184                 /* Transfer length */
1185                 cdb[28] = (u8)((num_blocks >> 24) & 0xff);
1186                 cdb[29] = (u8)((num_blocks >> 16) & 0xff);
1187                 cdb[30] = (u8)((num_blocks >> 8) & 0xff);
1188                 cdb[31] = (u8)(num_blocks & 0xff);
1189
1190                 /* set SCSI IO EEDPFlags */
1191                 if (scp->sc_data_direction == PCI_DMA_FROMDEVICE) {
1192                         io_request->EEDPFlags =
1193                                 MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG  |
1194                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_REFTAG |
1195                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_REMOVE_OP |
1196                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_APPTAG |
1197                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_GUARD;
1198                 } else {
1199                         io_request->EEDPFlags =
1200                                 MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG |
1201                                 MPI2_SCSIIO_EEDPFLAGS_INSERT_OP;
1202                 }
1203                 io_request->Control |= (0x4 << 26);
1204                 io_request->EEDPBlockSize = MEGASAS_EEDPBLOCKSIZE;
1205         } else {
1206                 /* Some drives don't support 16/12 byte CDB's, convert to 10 */
1207                 if (((cdb_len == 12) || (cdb_len == 16)) &&
1208                     (start_blk <= 0xffffffff)) {
1209                         if (cdb_len == 16) {
1210                                 opcode = cdb[0] == READ_16 ? READ_10 : WRITE_10;
1211                                 flagvals = cdb[1];
1212                                 groupnum = cdb[14];
1213                                 control = cdb[15];
1214                         } else {
1215                                 opcode = cdb[0] == READ_12 ? READ_10 : WRITE_10;
1216                                 flagvals = cdb[1];
1217                                 groupnum = cdb[10];
1218                                 control = cdb[11];
1219                         }
1220
1221                         memset(cdb, 0, sizeof(io_request->CDB.CDB32));
1222
1223                         cdb[0] = opcode;
1224                         cdb[1] = flagvals;
1225                         cdb[6] = groupnum;
1226                         cdb[9] = control;
1227
1228                         /* Transfer length */
1229                         cdb[8] = (u8)(num_blocks & 0xff);
1230                         cdb[7] = (u8)((num_blocks >> 8) & 0xff);
1231
1232                         cdb_len = 10;
1233                 }
1234
1235                 /* Normal case, just load LBA here */
1236                 switch (cdb_len) {
1237                 case 6:
1238                 {
1239                         u8 val = cdb[1] & 0xE0;
1240                         cdb[3] = (u8)(start_blk & 0xff);
1241                         cdb[2] = (u8)((start_blk >> 8) & 0xff);
1242                         cdb[1] = val | ((u8)(start_blk >> 16) & 0x1f);
1243                         break;
1244                 }
1245                 case 10:
1246                         cdb[5] = (u8)(start_blk & 0xff);
1247                         cdb[4] = (u8)((start_blk >> 8) & 0xff);
1248                         cdb[3] = (u8)((start_blk >> 16) & 0xff);
1249                         cdb[2] = (u8)((start_blk >> 24) & 0xff);
1250                         break;
1251                 case 12:
1252                         cdb[5]    = (u8)(start_blk & 0xff);
1253                         cdb[4]    = (u8)((start_blk >> 8) & 0xff);
1254                         cdb[3]    = (u8)((start_blk >> 16) & 0xff);
1255                         cdb[2]    = (u8)((start_blk >> 24) & 0xff);
1256                         break;
1257                 case 16:
1258                         cdb[9]    = (u8)(start_blk & 0xff);
1259                         cdb[8]    = (u8)((start_blk >> 8) & 0xff);
1260                         cdb[7]    = (u8)((start_blk >> 16) & 0xff);
1261                         cdb[6]    = (u8)((start_blk >> 24) & 0xff);
1262                         cdb[5]    = (u8)((start_blk >> 32) & 0xff);
1263                         cdb[4]    = (u8)((start_blk >> 40) & 0xff);
1264                         cdb[3]    = (u8)((start_blk >> 48) & 0xff);
1265                         cdb[2]    = (u8)((start_blk >> 56) & 0xff);
1266                         break;
1267                 }
1268         }
1269 }
1270
1271 /**
1272  * megasas_build_ldio_fusion -  Prepares IOs to devices
1273  * @instance:           Adapter soft state
1274  * @scp:                SCSI command
1275  * @cmd:                Command to be prepared
1276  *
1277  * Prepares the io_request and chain elements (sg_frame) for IO
1278  * The IO can be for PD (Fast Path) or LD
1279  */
1280 void
1281 megasas_build_ldio_fusion(struct megasas_instance *instance,
1282                           struct scsi_cmnd *scp,
1283                           struct megasas_cmd_fusion *cmd)
1284 {
1285         u8 fp_possible;
1286         u32 start_lba_lo, start_lba_hi, device_id;
1287         struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
1288         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
1289         struct IO_REQUEST_INFO io_info;
1290         struct fusion_context *fusion;
1291         struct MR_FW_RAID_MAP_ALL *local_map_ptr;
1292
1293         device_id = MEGASAS_DEV_INDEX(instance, scp);
1294
1295         fusion = instance->ctrl_context;
1296
1297         io_request = cmd->io_request;
1298         io_request->RaidContext.VirtualDiskTgtId = device_id;
1299         io_request->RaidContext.status = 0;
1300         io_request->RaidContext.exStatus = 0;
1301
1302         req_desc = (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)cmd->request_desc;
1303
1304         start_lba_lo = 0;
1305         start_lba_hi = 0;
1306         fp_possible = 0;
1307
1308         /*
1309          * 6-byte READ(0x08) or WRITE(0x0A) cdb
1310          */
1311         if (scp->cmd_len == 6) {
1312                 io_request->DataLength = (u32) scp->cmnd[4];
1313                 start_lba_lo = ((u32) scp->cmnd[1] << 16) |
1314                         ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
1315
1316                 start_lba_lo &= 0x1FFFFF;
1317         }
1318
1319         /*
1320          * 10-byte READ(0x28) or WRITE(0x2A) cdb
1321          */
1322         else if (scp->cmd_len == 10) {
1323                 io_request->DataLength = (u32) scp->cmnd[8] |
1324                         ((u32) scp->cmnd[7] << 8);
1325                 start_lba_lo = ((u32) scp->cmnd[2] << 24) |
1326                         ((u32) scp->cmnd[3] << 16) |
1327                         ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
1328         }
1329
1330         /*
1331          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1332          */
1333         else if (scp->cmd_len == 12) {
1334                 io_request->DataLength = ((u32) scp->cmnd[6] << 24) |
1335                         ((u32) scp->cmnd[7] << 16) |
1336                         ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
1337                 start_lba_lo = ((u32) scp->cmnd[2] << 24) |
1338                         ((u32) scp->cmnd[3] << 16) |
1339                         ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
1340         }
1341
1342         /*
1343          * 16-byte READ(0x88) or WRITE(0x8A) cdb
1344          */
1345         else if (scp->cmd_len == 16) {
1346                 io_request->DataLength = ((u32) scp->cmnd[10] << 24) |
1347                         ((u32) scp->cmnd[11] << 16) |
1348                         ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
1349                 start_lba_lo = ((u32) scp->cmnd[6] << 24) |
1350                         ((u32) scp->cmnd[7] << 16) |
1351                         ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
1352
1353                 start_lba_hi = ((u32) scp->cmnd[2] << 24) |
1354                         ((u32) scp->cmnd[3] << 16) |
1355                         ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
1356         }
1357
1358         memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
1359         io_info.ldStartBlock = ((u64)start_lba_hi << 32) | start_lba_lo;
1360         io_info.numBlocks = io_request->DataLength;
1361         io_info.ldTgtId = device_id;
1362
1363         if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1364                 io_info.isRead = 1;
1365
1366         local_map_ptr = fusion->ld_map[(instance->map_id & 1)];
1367
1368         if ((MR_TargetIdToLdGet(device_id, local_map_ptr) >=
1369              MAX_LOGICAL_DRIVES) || (!fusion->fast_path_io)) {
1370                 io_request->RaidContext.regLockFlags  = 0;
1371                 fp_possible = 0;
1372         } else {
1373                 if (MR_BuildRaidContext(&io_info, &io_request->RaidContext,
1374                                         local_map_ptr))
1375                         fp_possible = io_info.fpOkForIo;
1376         }
1377
1378         if (fp_possible) {
1379                 megasas_set_pd_lba(io_request, scp->cmd_len, &io_info, scp,
1380                                    local_map_ptr, start_lba_lo);
1381                 io_request->DataLength = scsi_bufflen(scp);
1382                 io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
1383                 cmd->request_desc->SCSIIO.RequestFlags =
1384                         (MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY
1385                          << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1386                 if ((fusion->load_balance_info[device_id].loadBalanceFlag) &&
1387                     (io_info.isRead)) {
1388                         io_info.devHandle =
1389                                 get_updated_dev_handle(
1390                                         &fusion->load_balance_info[device_id],
1391                                         &io_info);
1392                         scp->SCp.Status |= MEGASAS_LOAD_BALANCE_FLAG;
1393                 } else
1394                         scp->SCp.Status &= ~MEGASAS_LOAD_BALANCE_FLAG;
1395                 cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
1396                 io_request->DevHandle = io_info.devHandle;
1397         } else {
1398                 io_request->RaidContext.timeoutValue =
1399                         local_map_ptr->raidMap.fpPdIoTimeoutSec;
1400                 io_request->Function = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
1401                 io_request->DevHandle = device_id;
1402                 cmd->request_desc->SCSIIO.RequestFlags =
1403                         (MEGASAS_REQ_DESCRIPT_FLAGS_LD_IO
1404                          << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1405         } /* Not FP */
1406 }
1407
1408 /**
1409  * megasas_build_dcdb_fusion -  Prepares IOs to devices
1410  * @instance:           Adapter soft state
1411  * @scp:                SCSI command
1412  * @cmd:                Command to be prepared
1413  *
1414  * Prepares the io_request frame for non-io cmds
1415  */
1416 static void
1417 megasas_build_dcdb_fusion(struct megasas_instance *instance,
1418                           struct scsi_cmnd *scmd,
1419                           struct megasas_cmd_fusion *cmd)
1420 {
1421         u32 device_id;
1422         struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
1423         u16 pd_index = 0;
1424         struct MR_FW_RAID_MAP_ALL *local_map_ptr;
1425         struct fusion_context *fusion = instance->ctrl_context;
1426
1427         io_request = cmd->io_request;
1428         device_id = MEGASAS_DEV_INDEX(instance, scmd);
1429         pd_index = (scmd->device->channel * MEGASAS_MAX_DEV_PER_CHANNEL)
1430                 +scmd->device->id;
1431         local_map_ptr = fusion->ld_map[(instance->map_id & 1)];
1432
1433         /* Check if this is a system PD I/O */
1434         if ((instance->pd_list[pd_index].driveState == MR_PD_STATE_SYSTEM) &&
1435             (instance->pd_list[pd_index].driveType == TYPE_DISK)) {
1436                 io_request->Function = 0;
1437                 io_request->DevHandle =
1438                         local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
1439                 io_request->RaidContext.timeoutValue =
1440                         local_map_ptr->raidMap.fpPdIoTimeoutSec;
1441                 io_request->RaidContext.regLockFlags = 0;
1442                 io_request->RaidContext.regLockRowLBA = 0;
1443                 io_request->RaidContext.regLockLength = 0;
1444                 io_request->RaidContext.RAIDFlags =
1445                         MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD <<
1446                         MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
1447                 cmd->request_desc->SCSIIO.RequestFlags =
1448                         (MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
1449                          MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1450         } else {
1451                 io_request->Function  = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
1452                 io_request->DevHandle = device_id;
1453                 cmd->request_desc->SCSIIO.RequestFlags =
1454                         (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1455                          MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1456         }
1457         io_request->RaidContext.VirtualDiskTgtId = device_id;
1458         io_request->LUN[0] = scmd->device->lun;
1459         io_request->DataLength = scsi_bufflen(scmd);
1460 }
1461
1462 /**
1463  * megasas_build_io_fusion -    Prepares IOs to devices
1464  * @instance:           Adapter soft state
1465  * @scp:                SCSI command
1466  * @cmd:                Command to be prepared
1467  *
1468  * Invokes helper functions to prepare request frames
1469  * and sets flags appropriate for IO/Non-IO cmd
1470  */
1471 int
1472 megasas_build_io_fusion(struct megasas_instance *instance,
1473                         struct scsi_cmnd *scp,
1474                         struct megasas_cmd_fusion *cmd)
1475 {
1476         u32 device_id, sge_count;
1477         struct MPI2_RAID_SCSI_IO_REQUEST *io_request = cmd->io_request;
1478
1479         device_id = MEGASAS_DEV_INDEX(instance, scp);
1480
1481         /* Zero out some fields so they don't get reused */
1482         io_request->LUN[0] = 0;
1483         io_request->CDB.EEDP32.PrimaryReferenceTag = 0;
1484         io_request->CDB.EEDP32.PrimaryApplicationTagMask = 0;
1485         io_request->EEDPFlags = 0;
1486         io_request->Control = 0;
1487         io_request->EEDPBlockSize = 0;
1488         io_request->IoFlags = 0;
1489         io_request->RaidContext.RAIDFlags = 0;
1490
1491         memcpy(io_request->CDB.CDB32, scp->cmnd, scp->cmd_len);
1492         /*
1493          * Just the CDB length,rest of the Flags are zero
1494          * This will be modified for FP in build_ldio_fusion
1495          */
1496         io_request->IoFlags = scp->cmd_len;
1497
1498         if (megasas_is_ldio(scp))
1499                 megasas_build_ldio_fusion(instance, scp, cmd);
1500         else
1501                 megasas_build_dcdb_fusion(instance, scp, cmd);
1502
1503         /*
1504          * Construct SGL
1505          */
1506
1507         sge_count =
1508                 megasas_make_sgl_fusion(instance, scp,
1509                                         (struct MPI25_IEEE_SGE_CHAIN64 *)
1510                                         &io_request->SGL, cmd);
1511
1512         if (sge_count > instance->max_num_sge) {
1513                 printk(KERN_ERR "megasas: Error. sge_count (0x%x) exceeds "
1514                        "max (0x%x) allowed\n", sge_count,
1515                        instance->max_num_sge);
1516                 return 1;
1517         }
1518
1519         io_request->RaidContext.numSGE = sge_count;
1520
1521         io_request->SGLFlags = MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
1522
1523         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1524                 io_request->Control |= MPI2_SCSIIO_CONTROL_WRITE;
1525         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1526                 io_request->Control |= MPI2_SCSIIO_CONTROL_READ;
1527
1528         io_request->SGLOffset0 =
1529                 offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL) / 4;
1530
1531         io_request->SenseBufferLowAddress = cmd->sense_phys_addr;
1532         io_request->SenseBufferLength = SCSI_SENSE_BUFFERSIZE;
1533
1534         cmd->scmd = scp;
1535         scp->SCp.ptr = (char *)cmd;
1536
1537         return 0;
1538 }
1539
1540 union MEGASAS_REQUEST_DESCRIPTOR_UNION *
1541 megasas_get_request_descriptor(struct megasas_instance *instance, u16 index)
1542 {
1543         u8 *p;
1544         struct fusion_context *fusion;
1545
1546         if (index >= instance->max_fw_cmds) {
1547                 printk(KERN_ERR "megasas: Invalid SMID (0x%x)request for "
1548                        "descriptor\n", index);
1549                 return NULL;
1550         }
1551         fusion = instance->ctrl_context;
1552         p = fusion->req_frames_desc
1553                 +sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) *index;
1554
1555         return (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)p;
1556 }
1557
1558 /**
1559  * megasas_build_and_issue_cmd_fusion -Main routine for building and
1560  *                                     issuing non IOCTL cmd
1561  * @instance:                   Adapter soft state
1562  * @scmd:                       pointer to scsi cmd from OS
1563  */
1564 static u32
1565 megasas_build_and_issue_cmd_fusion(struct megasas_instance *instance,
1566                                    struct scsi_cmnd *scmd)
1567 {
1568         struct megasas_cmd_fusion *cmd;
1569         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
1570         u32 index;
1571         struct fusion_context *fusion;
1572
1573         fusion = instance->ctrl_context;
1574
1575         cmd = megasas_get_cmd_fusion(instance);
1576         if (!cmd)
1577                 return SCSI_MLQUEUE_HOST_BUSY;
1578
1579         index = cmd->index;
1580
1581         req_desc = megasas_get_request_descriptor(instance, index-1);
1582         if (!req_desc)
1583                 return 1;
1584
1585         req_desc->Words = 0;
1586         cmd->request_desc = req_desc;
1587         cmd->request_desc->Words = 0;
1588
1589         if (megasas_build_io_fusion(instance, scmd, cmd)) {
1590                 megasas_return_cmd_fusion(instance, cmd);
1591                 printk(KERN_ERR "megasas: Error building command.\n");
1592                 cmd->request_desc = NULL;
1593                 return 1;
1594         }
1595
1596         req_desc = cmd->request_desc;
1597         req_desc->SCSIIO.SMID = index;
1598
1599         if (cmd->io_request->ChainOffset != 0 &&
1600             cmd->io_request->ChainOffset != 0xF)
1601                 printk(KERN_ERR "megasas: The chain offset value is not "
1602                        "correct : %x\n", cmd->io_request->ChainOffset);
1603
1604         /*
1605          * Issue the command to the FW
1606          */
1607         atomic_inc(&instance->fw_outstanding);
1608
1609         instance->instancet->fire_cmd(instance,
1610                                       req_desc->u.low, req_desc->u.high,
1611                                       instance->reg_set);
1612
1613         return 0;
1614 }
1615
1616 /**
1617  * complete_cmd_fusion -        Completes command
1618  * @instance:                   Adapter soft state
1619  * Completes all commands that is in reply descriptor queue
1620  */
1621 int
1622 complete_cmd_fusion(struct megasas_instance *instance)
1623 {
1624         union MPI2_REPLY_DESCRIPTORS_UNION *desc;
1625         struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *reply_desc;
1626         struct MPI2_RAID_SCSI_IO_REQUEST *scsi_io_req;
1627         struct fusion_context *fusion;
1628         struct megasas_cmd *cmd_mfi;
1629         struct megasas_cmd_fusion *cmd_fusion;
1630         u16 smid, num_completed;
1631         u8 reply_descript_type, arm;
1632         u32 status, extStatus, device_id;
1633         union desc_value d_val;
1634         struct LD_LOAD_BALANCE_INFO *lbinfo;
1635
1636         fusion = instance->ctrl_context;
1637
1638         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
1639                 return IRQ_HANDLED;
1640
1641         desc = fusion->reply_frames_desc;
1642         desc += fusion->last_reply_idx;
1643
1644         reply_desc = (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;
1645
1646         d_val.word = desc->Words;
1647
1648         reply_descript_type = reply_desc->ReplyFlags &
1649                 MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1650
1651         if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1652                 return IRQ_NONE;
1653
1654         d_val.word = desc->Words;
1655
1656         num_completed = 0;
1657
1658         while ((d_val.u.low != UINT_MAX) && (d_val.u.high != UINT_MAX)) {
1659                 smid = reply_desc->SMID;
1660
1661                 cmd_fusion = fusion->cmd_list[smid - 1];
1662
1663                 scsi_io_req =
1664                         (struct MPI2_RAID_SCSI_IO_REQUEST *)
1665                   cmd_fusion->io_request;
1666
1667                 if (cmd_fusion->scmd)
1668                         cmd_fusion->scmd->SCp.ptr = NULL;
1669
1670                 status = scsi_io_req->RaidContext.status;
1671                 extStatus = scsi_io_req->RaidContext.exStatus;
1672
1673                 switch (scsi_io_req->Function) {
1674                 case MPI2_FUNCTION_SCSI_IO_REQUEST:  /*Fast Path IO.*/
1675                         /* Update load balancing info */
1676                         device_id = MEGASAS_DEV_INDEX(instance,
1677                                                       cmd_fusion->scmd);
1678                         lbinfo = &fusion->load_balance_info[device_id];
1679                         if (cmd_fusion->scmd->SCp.Status &
1680                             MEGASAS_LOAD_BALANCE_FLAG) {
1681                                 arm = lbinfo->raid1DevHandle[0] ==
1682                                         cmd_fusion->io_request->DevHandle ? 0 :
1683                                         1;
1684                                 atomic_dec(&lbinfo->scsi_pending_cmds[arm]);
1685                                 cmd_fusion->scmd->SCp.Status &=
1686                                         ~MEGASAS_LOAD_BALANCE_FLAG;
1687                         }
1688                         if (reply_descript_type ==
1689                             MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS) {
1690                                 if (megasas_dbg_lvl == 5)
1691                                         printk(KERN_ERR "\nmegasas: FAST Path "
1692                                                "IO Success\n");
1693                         }
1694                         /* Fall thru and complete IO */
1695                 case MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST: /* LD-IO Path */
1696                         /* Map the FW Cmd Status */
1697                         map_cmd_status(cmd_fusion, status, extStatus);
1698                         scsi_dma_unmap(cmd_fusion->scmd);
1699                         cmd_fusion->scmd->scsi_done(cmd_fusion->scmd);
1700                         scsi_io_req->RaidContext.status = 0;
1701                         scsi_io_req->RaidContext.exStatus = 0;
1702                         megasas_return_cmd_fusion(instance, cmd_fusion);
1703                         atomic_dec(&instance->fw_outstanding);
1704
1705                         break;
1706                 case MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST: /*MFI command */
1707                         cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
1708                         megasas_complete_cmd(instance, cmd_mfi, DID_OK);
1709                         cmd_fusion->flags = 0;
1710                         megasas_return_cmd_fusion(instance, cmd_fusion);
1711
1712                         break;
1713                 }
1714
1715                 fusion->last_reply_idx++;
1716                 if (fusion->last_reply_idx >= fusion->reply_q_depth)
1717                         fusion->last_reply_idx = 0;
1718
1719                 desc->Words = ULLONG_MAX;
1720                 num_completed++;
1721
1722                 /* Get the next reply descriptor */
1723                 if (!fusion->last_reply_idx)
1724                         desc = fusion->reply_frames_desc;
1725                 else
1726                         desc++;
1727
1728                 reply_desc =
1729                   (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;
1730
1731                 d_val.word = desc->Words;
1732
1733                 reply_descript_type = reply_desc->ReplyFlags &
1734                         MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1735
1736                 if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1737                         break;
1738         }
1739
1740         if (!num_completed)
1741                 return IRQ_NONE;
1742
1743         wmb();
1744         writel(fusion->last_reply_idx,
1745                &instance->reg_set->reply_post_host_index);
1746
1747         return IRQ_HANDLED;
1748 }
1749
1750 /**
1751  * megasas_complete_cmd_dpc_fusion -    Completes command
1752  * @instance:                   Adapter soft state
1753  *
1754  * Tasklet to complete cmds
1755  */
1756 void
1757 megasas_complete_cmd_dpc_fusion(unsigned long instance_addr)
1758 {
1759         struct megasas_instance *instance =
1760                 (struct megasas_instance *)instance_addr;
1761         unsigned long flags;
1762
1763         /* If we have already declared adapter dead, donot complete cmds */
1764         spin_lock_irqsave(&instance->hba_lock, flags);
1765         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
1766                 spin_unlock_irqrestore(&instance->hba_lock, flags);
1767                 return;
1768         }
1769         spin_unlock_irqrestore(&instance->hba_lock, flags);
1770
1771         spin_lock_irqsave(&instance->completion_lock, flags);
1772         complete_cmd_fusion(instance);
1773         spin_unlock_irqrestore(&instance->completion_lock, flags);
1774 }
1775
1776 /**
1777  * megasas_isr_fusion - isr entry point
1778  */
1779 irqreturn_t megasas_isr_fusion(int irq, void *devp)
1780 {
1781         struct megasas_instance *instance = (struct megasas_instance *)devp;
1782         u32 mfiStatus, fw_state;
1783
1784         if (!instance->msi_flag) {
1785                 mfiStatus = instance->instancet->clear_intr(instance->reg_set);
1786                 if (!mfiStatus)
1787                         return IRQ_NONE;
1788         }
1789
1790         /* If we are resetting, bail */
1791         if (test_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags))
1792                 return IRQ_HANDLED;
1793
1794         if (!complete_cmd_fusion(instance)) {
1795                 /* If we didn't complete any commands, check for FW fault */
1796                 fw_state = instance->instancet->read_fw_status_reg(
1797                         instance->reg_set) & MFI_STATE_MASK;
1798                 if (fw_state == MFI_STATE_FAULT)
1799                         schedule_work(&instance->work_init);
1800         }
1801
1802         return IRQ_HANDLED;
1803 }
1804
1805 /**
1806  * build_mpt_mfi_pass_thru - builds a cmd fo MFI Pass thru
1807  * @instance:                   Adapter soft state
1808  * mfi_cmd:                     megasas_cmd pointer
1809  *
1810  */
1811 u8
1812 build_mpt_mfi_pass_thru(struct megasas_instance *instance,
1813                         struct megasas_cmd *mfi_cmd)
1814 {
1815         struct MPI25_IEEE_SGE_CHAIN64 *mpi25_ieee_chain;
1816         struct MPI2_RAID_SCSI_IO_REQUEST *io_req;
1817         struct megasas_cmd_fusion *cmd;
1818         struct fusion_context *fusion;
1819         struct megasas_header *frame_hdr = &mfi_cmd->frame->hdr;
1820
1821         cmd = megasas_get_cmd_fusion(instance);
1822         if (!cmd)
1823                 return 1;
1824
1825         /*  Save the smid. To be used for returning the cmd */
1826         mfi_cmd->context.smid = cmd->index;
1827
1828         cmd->sync_cmd_idx = mfi_cmd->index;
1829
1830         /*
1831          * For cmds where the flag is set, store the flag and check
1832          * on completion. For cmds with this flag, don't call
1833          * megasas_complete_cmd
1834          */
1835
1836         if (frame_hdr->flags & MFI_FRAME_DONT_POST_IN_REPLY_QUEUE)
1837                 cmd->flags = MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
1838
1839         fusion = instance->ctrl_context;
1840         io_req = cmd->io_request;
1841         mpi25_ieee_chain =
1842           (struct MPI25_IEEE_SGE_CHAIN64 *)&io_req->SGL.IeeeChain;
1843
1844         io_req->Function    = MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST;
1845         io_req->SGLOffset0  = offsetof(struct MPI2_RAID_SCSI_IO_REQUEST,
1846                                        SGL) / 4;
1847         io_req->ChainOffset = fusion->chain_offset_mfi_pthru;
1848
1849         mpi25_ieee_chain->Address = mfi_cmd->frame_phys_addr;
1850
1851         mpi25_ieee_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1852                 MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR;
1853
1854         mpi25_ieee_chain->Length = MEGASAS_MAX_SZ_CHAIN_FRAME;
1855
1856         return 0;
1857 }
1858
1859 /**
1860  * build_mpt_cmd - Calls helper function to build a cmd MFI Pass thru cmd
1861  * @instance:                   Adapter soft state
1862  * @cmd:                        mfi cmd to build
1863  *
1864  */
1865 union MEGASAS_REQUEST_DESCRIPTOR_UNION *
1866 build_mpt_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
1867 {
1868         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
1869         u16 index;
1870
1871         if (build_mpt_mfi_pass_thru(instance, cmd)) {
1872                 printk(KERN_ERR "Couldn't build MFI pass thru cmd\n");
1873                 return NULL;
1874         }
1875
1876         index = cmd->context.smid;
1877
1878         req_desc = megasas_get_request_descriptor(instance, index - 1);
1879
1880         if (!req_desc)
1881                 return NULL;
1882
1883         req_desc->Words = 0;
1884         req_desc->SCSIIO.RequestFlags = (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1885                                          MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1886
1887         req_desc->SCSIIO.SMID = index;
1888
1889         return req_desc;
1890 }
1891
1892 /**
1893  * megasas_issue_dcmd_fusion - Issues a MFI Pass thru cmd
1894  * @instance:                   Adapter soft state
1895  * @cmd:                        mfi cmd pointer
1896  *
1897  */
1898 void
1899 megasas_issue_dcmd_fusion(struct megasas_instance *instance,
1900                           struct megasas_cmd *cmd)
1901 {
1902         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
1903         union desc_value d_val;
1904
1905         req_desc = build_mpt_cmd(instance, cmd);
1906         if (!req_desc) {
1907                 printk(KERN_ERR "Couldn't issue MFI pass thru cmd\n");
1908                 return;
1909         }
1910         d_val.word = req_desc->Words;
1911
1912         instance->instancet->fire_cmd(instance, req_desc->u.low,
1913                                       req_desc->u.high, instance->reg_set);
1914 }
1915
1916 /**
1917  * megasas_release_fusion -     Reverses the FW initialization
1918  * @intance:                    Adapter soft state
1919  */
1920 void
1921 megasas_release_fusion(struct megasas_instance *instance)
1922 {
1923         megasas_free_cmds(instance);
1924         megasas_free_cmds_fusion(instance);
1925
1926         iounmap(instance->reg_set);
1927
1928         pci_release_selected_regions(instance->pdev, instance->bar);
1929 }
1930
1931 /**
1932  * megasas_read_fw_status_reg_fusion - returns the current FW status value
1933  * @regs:                       MFI register set
1934  */
1935 static u32
1936 megasas_read_fw_status_reg_fusion(struct megasas_register_set __iomem *regs)
1937 {
1938         return readl(&(regs)->outbound_scratch_pad);
1939 }
1940
1941 /**
1942  * megasas_adp_reset_fusion -   For controller reset
1943  * @regs:                               MFI register set
1944  */
1945 static int
1946 megasas_adp_reset_fusion(struct megasas_instance *instance,
1947                          struct megasas_register_set __iomem *regs)
1948 {
1949         return 0;
1950 }
1951
1952 /**
1953  * megasas_check_reset_fusion - For controller reset check
1954  * @regs:                               MFI register set
1955  */
1956 static int
1957 megasas_check_reset_fusion(struct megasas_instance *instance,
1958                            struct megasas_register_set __iomem *regs)
1959 {
1960         return 0;
1961 }
1962
1963 /* This function waits for outstanding commands on fusion to complete */
1964 int megasas_wait_for_outstanding_fusion(struct megasas_instance *instance)
1965 {
1966         int i, outstanding, retval = 0;
1967         u32 fw_state, wait_time = MEGASAS_RESET_WAIT_TIME;
1968
1969         for (i = 0; i < wait_time; i++) {
1970                 /* Check if firmware is in fault state */
1971                 fw_state = instance->instancet->read_fw_status_reg(
1972                         instance->reg_set) & MFI_STATE_MASK;
1973                 if (fw_state == MFI_STATE_FAULT) {
1974                         printk(KERN_WARNING "megasas: Found FW in FAULT state,"
1975                                " will reset adapter.\n");
1976                         retval = 1;
1977                         goto out;
1978                 }
1979
1980                 outstanding = atomic_read(&instance->fw_outstanding);
1981                 if (!outstanding)
1982                         goto out;
1983
1984                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
1985                         printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
1986                                "commands to complete\n", i, outstanding);
1987                         megasas_complete_cmd_dpc_fusion(
1988                                 (unsigned long)instance);
1989                 }
1990                 msleep(1000);
1991         }
1992
1993         if (atomic_read(&instance->fw_outstanding)) {
1994                 printk("megaraid_sas: pending commands remain after waiting, "
1995                        "will reset adapter.\n");
1996                 retval = 1;
1997         }
1998 out:
1999         return retval;
2000 }
2001
2002 void  megasas_reset_reply_desc(struct megasas_instance *instance)
2003 {
2004         int i;
2005         struct fusion_context *fusion;
2006         union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
2007
2008         fusion = instance->ctrl_context;
2009         fusion->last_reply_idx = 0;
2010         reply_desc = fusion->reply_frames_desc;
2011         for (i = 0 ; i < fusion->reply_q_depth; i++, reply_desc++)
2012                 reply_desc->Words = ULLONG_MAX;
2013 }
2014
2015 /* Core fusion reset function */
2016 int megasas_reset_fusion(struct Scsi_Host *shost)
2017 {
2018         int retval = SUCCESS, i, j, retry = 0;
2019         struct megasas_instance *instance;
2020         struct megasas_cmd_fusion *cmd_fusion;
2021         struct fusion_context *fusion;
2022         struct megasas_cmd *cmd_mfi;
2023         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2024         u32 host_diag, abs_state;
2025
2026         instance = (struct megasas_instance *)shost->hostdata;
2027         fusion = instance->ctrl_context;
2028
2029         mutex_lock(&instance->reset_mutex);
2030         set_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
2031         instance->adprecovery = MEGASAS_ADPRESET_SM_INFAULT;
2032         instance->instancet->disable_intr(instance->reg_set);
2033         msleep(1000);
2034
2035         if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
2036                 printk(KERN_WARNING "megaraid_sas: Hardware critical error, "
2037                        "returning FAILED.\n");
2038                 retval = FAILED;
2039                 goto out;
2040         }
2041
2042         /* First try waiting for commands to complete */
2043         if (megasas_wait_for_outstanding_fusion(instance)) {
2044                 printk(KERN_WARNING "megaraid_sas: resetting fusion "
2045                        "adapter.\n");
2046                 /* Now return commands back to the OS */
2047                 for (i = 0 ; i < instance->max_fw_cmds; i++) {
2048                         cmd_fusion = fusion->cmd_list[i];
2049                         if (cmd_fusion->scmd) {
2050                                 scsi_dma_unmap(cmd_fusion->scmd);
2051                                 cmd_fusion->scmd->result = (DID_RESET << 16);
2052                                 cmd_fusion->scmd->scsi_done(cmd_fusion->scmd);
2053                                 megasas_return_cmd_fusion(instance, cmd_fusion);
2054                                 atomic_dec(&instance->fw_outstanding);
2055                         }
2056                 }
2057
2058                 if (instance->disableOnlineCtrlReset == 1) {
2059                         /* Reset not supported, kill adapter */
2060                         printk(KERN_WARNING "megaraid_sas: Reset not supported"
2061                                ", killing adapter.\n");
2062                         megaraid_sas_kill_hba(instance);
2063                         instance->adprecovery = MEGASAS_HW_CRITICAL_ERROR;
2064                         retval = FAILED;
2065                         goto out;
2066                 }
2067
2068                 /* Now try to reset the chip */
2069                 for (i = 0; i < MEGASAS_FUSION_MAX_RESET_TRIES; i++) {
2070                         writel(MPI2_WRSEQ_FLUSH_KEY_VALUE,
2071                                &instance->reg_set->fusion_seq_offset);
2072                         writel(MPI2_WRSEQ_1ST_KEY_VALUE,
2073                                &instance->reg_set->fusion_seq_offset);
2074                         writel(MPI2_WRSEQ_2ND_KEY_VALUE,
2075                                &instance->reg_set->fusion_seq_offset);
2076                         writel(MPI2_WRSEQ_3RD_KEY_VALUE,
2077                                &instance->reg_set->fusion_seq_offset);
2078                         writel(MPI2_WRSEQ_4TH_KEY_VALUE,
2079                                &instance->reg_set->fusion_seq_offset);
2080                         writel(MPI2_WRSEQ_5TH_KEY_VALUE,
2081                                &instance->reg_set->fusion_seq_offset);
2082                         writel(MPI2_WRSEQ_6TH_KEY_VALUE,
2083                                &instance->reg_set->fusion_seq_offset);
2084
2085                         /* Check that the diag write enable (DRWE) bit is on */
2086                         host_diag = readl(&instance->reg_set->fusion_host_diag);
2087                         while (!(host_diag & HOST_DIAG_WRITE_ENABLE)) {
2088                                 msleep(100);
2089                                 host_diag =
2090                                 readl(&instance->reg_set->fusion_host_diag);
2091                                 if (retry++ == 100) {
2092                                         printk(KERN_WARNING "megaraid_sas: "
2093                                                "Host diag unlock failed!\n");
2094                                         break;
2095                                 }
2096                         }
2097                         if (!(host_diag & HOST_DIAG_WRITE_ENABLE))
2098                                 continue;
2099
2100                         /* Send chip reset command */
2101                         writel(host_diag | HOST_DIAG_RESET_ADAPTER,
2102                                &instance->reg_set->fusion_host_diag);
2103                         msleep(3000);
2104
2105                         /* Make sure reset adapter bit is cleared */
2106                         host_diag = readl(&instance->reg_set->fusion_host_diag);
2107                         retry = 0;
2108                         while (host_diag & HOST_DIAG_RESET_ADAPTER) {
2109                                 msleep(100);
2110                                 host_diag =
2111                                 readl(&instance->reg_set->fusion_host_diag);
2112                                 if (retry++ == 1000) {
2113                                         printk(KERN_WARNING "megaraid_sas: "
2114                                                "Diag reset adapter never "
2115                                                "cleared!\n");
2116                                         break;
2117                                 }
2118                         }
2119                         if (host_diag & HOST_DIAG_RESET_ADAPTER)
2120                                 continue;
2121
2122                         abs_state =
2123                                 instance->instancet->read_fw_status_reg(
2124                                         instance->reg_set);
2125                         retry = 0;
2126
2127                         while ((abs_state <= MFI_STATE_FW_INIT) &&
2128                                (retry++ < 1000)) {
2129                                 msleep(100);
2130                                 abs_state =
2131                                 instance->instancet->read_fw_status_reg(
2132                                         instance->reg_set);
2133                         }
2134                         if (abs_state <= MFI_STATE_FW_INIT) {
2135                                 printk(KERN_WARNING "megaraid_sas: firmware "
2136                                        "state < MFI_STATE_FW_INIT, state = "
2137                                        "0x%x\n", abs_state);
2138                                 continue;
2139                         }
2140
2141                         /* Wait for FW to become ready */
2142                         if (megasas_transition_to_ready(instance)) {
2143                                 printk(KERN_WARNING "megaraid_sas: Failed to "
2144                                        "transition controller to ready.\n");
2145                                 continue;
2146                         }
2147
2148                         megasas_reset_reply_desc(instance);
2149                         if (megasas_ioc_init_fusion(instance)) {
2150                                 printk(KERN_WARNING "megaraid_sas: "
2151                                        "megasas_ioc_init_fusion() failed!\n");
2152                                 continue;
2153                         }
2154
2155                         instance->instancet->enable_intr(instance->reg_set);
2156                         instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
2157
2158                         /* Re-fire management commands */
2159                         for (j = 0 ; j < instance->max_fw_cmds; j++) {
2160                                 cmd_fusion = fusion->cmd_list[j];
2161                                 if (cmd_fusion->sync_cmd_idx !=
2162                                     (u32)ULONG_MAX) {
2163                                         cmd_mfi =
2164                                         instance->
2165                                         cmd_list[cmd_fusion->sync_cmd_idx];
2166                                         if (cmd_mfi->frame->dcmd.opcode ==
2167                                             MR_DCMD_LD_MAP_GET_INFO) {
2168                                                 megasas_return_cmd(instance,
2169                                                                    cmd_mfi);
2170                                                 megasas_return_cmd_fusion(
2171                                                         instance, cmd_fusion);
2172                                         } else  {
2173                                                 req_desc =
2174                                                 megasas_get_request_descriptor(
2175                                                         instance,
2176                                                         cmd_mfi->context.smid
2177                                                         -1);
2178                                                 if (!req_desc)
2179                                                         printk(KERN_WARNING
2180                                                                "req_desc NULL"
2181                                                                "\n");
2182                                                 else {
2183                                                         instance->instancet->
2184                                                         fire_cmd(instance,
2185                                                                  req_desc->
2186                                                                  u.low,
2187                                                                  req_desc->
2188                                                                  u.high,
2189                                                                  instance->
2190                                                                  reg_set);
2191                                                 }
2192                                         }
2193                                 }
2194                         }
2195
2196                         /* Reset load balance info */
2197                         memset(fusion->load_balance_info, 0,
2198                                sizeof(struct LD_LOAD_BALANCE_INFO)
2199                                *MAX_LOGICAL_DRIVES);
2200
2201                         if (!megasas_get_map_info(instance))
2202                                 megasas_sync_map_info(instance);
2203
2204                         /* Adapter reset completed successfully */
2205                         printk(KERN_WARNING "megaraid_sas: Reset "
2206                                "successful.\n");
2207                         retval = SUCCESS;
2208                         goto out;
2209                 }
2210                 /* Reset failed, kill the adapter */
2211                 printk(KERN_WARNING "megaraid_sas: Reset failed, killing "
2212                        "adapter.\n");
2213                 megaraid_sas_kill_hba(instance);
2214                 retval = FAILED;
2215         } else {
2216                 instance->instancet->enable_intr(instance->reg_set);
2217                 instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
2218         }
2219 out:
2220         clear_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
2221         mutex_unlock(&instance->reset_mutex);
2222         return retval;
2223 }
2224
2225 /* Fusion OCR work queue */
2226 void megasas_fusion_ocr_wq(struct work_struct *work)
2227 {
2228         struct megasas_instance *instance =
2229                 container_of(work, struct megasas_instance, work_init);
2230
2231         megasas_reset_fusion(instance->host);
2232 }
2233
2234 struct megasas_instance_template megasas_instance_template_fusion = {
2235         .fire_cmd = megasas_fire_cmd_fusion,
2236         .enable_intr = megasas_enable_intr_fusion,
2237         .disable_intr = megasas_disable_intr_fusion,
2238         .clear_intr = megasas_clear_intr_fusion,
2239         .read_fw_status_reg = megasas_read_fw_status_reg_fusion,
2240         .adp_reset = megasas_adp_reset_fusion,
2241         .check_reset = megasas_check_reset_fusion,
2242         .service_isr = megasas_isr_fusion,
2243         .tasklet = megasas_complete_cmd_dpc_fusion,
2244         .init_adapter = megasas_init_adapter_fusion,
2245         .build_and_issue_cmd = megasas_build_and_issue_cmd_fusion,
2246         .issue_dcmd = megasas_issue_dcmd_fusion,
2247 };