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