GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / scsi / megaraid / megaraid_sas_fusion.c
1 /*
2  *  Linux MegaRAID driver for SAS based RAID controllers
3  *
4  *  Copyright (c) 2009-2013  LSI Corporation
5  *  Copyright (c) 2013-2014  Avago Technologies
6  *
7  *  This program is free software; you can redistribute it and/or
8  *  modify it under the terms of the GNU General Public License
9  *  as published by the Free Software Foundation; either version 2
10  *  of the License, or (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  *  FILE: megaraid_sas_fusion.c
21  *
22  *  Authors: Avago Technologies
23  *           Sumant Patro
24  *           Adam Radford
25  *           Kashyap Desai <kashyap.desai@avagotech.com>
26  *           Sumit Saxena <sumit.saxena@avagotech.com>
27  *
28  *  Send feedback to: megaraidlinux.pdl@avagotech.com
29  *
30  *  Mail to: Avago Technologies, 350 West Trimble Road, Building 90,
31  *  San Jose, California 95131
32  */
33
34 #include <linux/kernel.h>
35 #include <linux/types.h>
36 #include <linux/pci.h>
37 #include <linux/list.h>
38 #include <linux/moduleparam.h>
39 #include <linux/module.h>
40 #include <linux/spinlock.h>
41 #include <linux/interrupt.h>
42 #include <linux/delay.h>
43 #include <linux/uio.h>
44 #include <linux/uaccess.h>
45 #include <linux/fs.h>
46 #include <linux/compat.h>
47 #include <linux/blkdev.h>
48 #include <linux/mutex.h>
49 #include <linux/poll.h>
50 #include <linux/vmalloc.h>
51
52 #include <scsi/scsi.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsi_device.h>
55 #include <scsi/scsi_host.h>
56 #include <scsi/scsi_dbg.h>
57 #include <linux/dmi.h>
58
59 #include "megaraid_sas_fusion.h"
60 #include "megaraid_sas.h"
61
62
63 extern void megasas_free_cmds(struct megasas_instance *instance);
64 extern struct megasas_cmd *megasas_get_cmd(struct megasas_instance
65                                            *instance);
66 extern void
67 megasas_complete_cmd(struct megasas_instance *instance,
68                      struct megasas_cmd *cmd, u8 alt_status);
69 int
70 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
71               int seconds);
72
73 void
74 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd);
75 int megasas_alloc_cmds(struct megasas_instance *instance);
76 int
77 megasas_clear_intr_fusion(struct megasas_register_set __iomem *regs);
78 int
79 megasas_issue_polled(struct megasas_instance *instance,
80                      struct megasas_cmd *cmd);
81 void
82 megasas_check_and_restore_queue_depth(struct megasas_instance *instance);
83
84 int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
85 void megaraid_sas_kill_hba(struct megasas_instance *instance);
86
87 extern u32 megasas_dbg_lvl;
88 void megasas_sriov_heartbeat_handler(unsigned long instance_addr);
89 int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
90                                   int initial);
91 void megasas_start_timer(struct megasas_instance *instance,
92                         struct timer_list *timer,
93                          void *fn, unsigned long interval);
94 extern struct megasas_mgmt_info megasas_mgmt_info;
95 extern unsigned int resetwaittime;
96 extern unsigned int dual_qdepth_disable;
97 static void megasas_free_rdpq_fusion(struct megasas_instance *instance);
98 static void megasas_free_reply_fusion(struct megasas_instance *instance);
99
100
101
102 /**
103  * megasas_enable_intr_fusion - Enables interrupts
104  * @regs:                       MFI register set
105  */
106 void
107 megasas_enable_intr_fusion(struct megasas_instance *instance)
108 {
109         struct megasas_register_set __iomem *regs;
110         regs = instance->reg_set;
111
112         instance->mask_interrupts = 0;
113         /* For Thunderbolt/Invader also clear intr on enable */
114         writel(~0, &regs->outbound_intr_status);
115         readl(&regs->outbound_intr_status);
116
117         writel(~MFI_FUSION_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
118
119         /* Dummy readl to force pci flush */
120         readl(&regs->outbound_intr_mask);
121 }
122
123 /**
124  * megasas_disable_intr_fusion - Disables interrupt
125  * @regs:                        MFI register set
126  */
127 void
128 megasas_disable_intr_fusion(struct megasas_instance *instance)
129 {
130         u32 mask = 0xFFFFFFFF;
131         u32 status;
132         struct megasas_register_set __iomem *regs;
133         regs = instance->reg_set;
134         instance->mask_interrupts = 1;
135
136         writel(mask, &regs->outbound_intr_mask);
137         /* Dummy readl to force pci flush */
138         status = readl(&regs->outbound_intr_mask);
139 }
140
141 int
142 megasas_clear_intr_fusion(struct megasas_register_set __iomem *regs)
143 {
144         u32 status;
145         /*
146          * Check if it is our interrupt
147          */
148         status = readl(&regs->outbound_intr_status);
149
150         if (status & 1) {
151                 writel(status, &regs->outbound_intr_status);
152                 readl(&regs->outbound_intr_status);
153                 return 1;
154         }
155         if (!(status & MFI_FUSION_ENABLE_INTERRUPT_MASK))
156                 return 0;
157
158         return 1;
159 }
160
161 /**
162  * megasas_get_cmd_fusion -     Get a command from the free pool
163  * @instance:           Adapter soft state
164  *
165  * Returns a blk_tag indexed mpt frame
166  */
167 inline struct megasas_cmd_fusion *megasas_get_cmd_fusion(struct megasas_instance
168                                                   *instance, u32 blk_tag)
169 {
170         struct fusion_context *fusion;
171
172         fusion = instance->ctrl_context;
173         return fusion->cmd_list[blk_tag];
174 }
175
176 /**
177  * megasas_return_cmd_fusion -  Return a cmd to free command pool
178  * @instance:           Adapter soft state
179  * @cmd:                Command packet to be returned to free command pool
180  */
181 inline void megasas_return_cmd_fusion(struct megasas_instance *instance,
182         struct megasas_cmd_fusion *cmd)
183 {
184         cmd->scmd = NULL;
185         memset(cmd->io_request, 0, MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE);
186         cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
187         cmd->cmd_completed = false;
188 }
189
190 /**
191  * megasas_fire_cmd_fusion -    Sends command to the FW
192  * @instance:                   Adapter soft state
193  * @req_desc:                   64bit Request descriptor
194  *
195  * Perform PCI Write.
196  */
197
198 static void
199 megasas_fire_cmd_fusion(struct megasas_instance *instance,
200                 union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc)
201 {
202 #if defined(writeq) && defined(CONFIG_64BIT)
203         u64 req_data = (((u64)le32_to_cpu(req_desc->u.high) << 32) |
204                 le32_to_cpu(req_desc->u.low));
205
206         writeq(req_data, &instance->reg_set->inbound_low_queue_port);
207 #else
208         unsigned long flags;
209         spin_lock_irqsave(&instance->hba_lock, flags);
210         writel(le32_to_cpu(req_desc->u.low),
211                 &instance->reg_set->inbound_low_queue_port);
212         writel(le32_to_cpu(req_desc->u.high),
213                 &instance->reg_set->inbound_high_queue_port);
214         mmiowb();
215         spin_unlock_irqrestore(&instance->hba_lock, flags);
216 #endif
217 }
218
219 /**
220  * megasas_fusion_update_can_queue -    Do all Adapter Queue depth related calculations here
221  * @instance:                                                   Adapter soft state
222  * fw_boot_context:                                             Whether this function called during probe or after OCR
223  *
224  * This function is only for fusion controllers.
225  * Update host can queue, if firmware downgrade max supported firmware commands.
226  * Firmware upgrade case will be skiped because underlying firmware has
227  * more resource than exposed to the OS.
228  *
229  */
230 static void
231 megasas_fusion_update_can_queue(struct megasas_instance *instance, int fw_boot_context)
232 {
233         u16 cur_max_fw_cmds = 0;
234         u16 ldio_threshold = 0;
235         struct megasas_register_set __iomem *reg_set;
236
237         reg_set = instance->reg_set;
238
239         /* ventura FW does not fill outbound_scratch_pad_3 with queue depth */
240         if (instance->adapter_type < VENTURA_SERIES)
241                 cur_max_fw_cmds =
242                 readl(&instance->reg_set->outbound_scratch_pad_3) & 0x00FFFF;
243
244         if (dual_qdepth_disable || !cur_max_fw_cmds)
245                 cur_max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
246         else
247                 ldio_threshold =
248                         (instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF) - MEGASAS_FUSION_IOCTL_CMDS;
249
250         dev_info(&instance->pdev->dev,
251                         "Current firmware maximum commands: %d\t LDIO threshold: %d\n",
252                         cur_max_fw_cmds, ldio_threshold);
253
254         if (fw_boot_context == OCR_CONTEXT) {
255                 cur_max_fw_cmds = cur_max_fw_cmds - 1;
256                 if (cur_max_fw_cmds < instance->max_fw_cmds) {
257                         instance->cur_can_queue =
258                                 cur_max_fw_cmds - (MEGASAS_FUSION_INTERNAL_CMDS +
259                                                 MEGASAS_FUSION_IOCTL_CMDS);
260                         instance->host->can_queue = instance->cur_can_queue;
261                         instance->ldio_threshold = ldio_threshold;
262                 }
263         } else {
264                 instance->max_fw_cmds = cur_max_fw_cmds;
265                 instance->ldio_threshold = ldio_threshold;
266
267                 if (!instance->is_rdpq)
268                         instance->max_fw_cmds =
269                                 min_t(u16, instance->max_fw_cmds, 1024);
270
271                 if (reset_devices)
272                         instance->max_fw_cmds = min(instance->max_fw_cmds,
273                                                 (u16)MEGASAS_KDUMP_QUEUE_DEPTH);
274                 /*
275                 * Reduce the max supported cmds by 1. This is to ensure that the
276                 * reply_q_sz (1 more than the max cmd that driver may send)
277                 * does not exceed max cmds that the FW can support
278                 */
279                 instance->max_fw_cmds = instance->max_fw_cmds-1;
280
281                 instance->max_scsi_cmds = instance->max_fw_cmds -
282                                 (MEGASAS_FUSION_INTERNAL_CMDS +
283                                 MEGASAS_FUSION_IOCTL_CMDS);
284                 instance->cur_can_queue = instance->max_scsi_cmds;
285                 instance->host->can_queue = instance->cur_can_queue;
286         }
287
288         if (instance->adapter_type == VENTURA_SERIES)
289                 instance->max_mpt_cmds =
290                 instance->max_fw_cmds * RAID_1_PEER_CMDS;
291         else
292                 instance->max_mpt_cmds = instance->max_fw_cmds;
293 }
294 /**
295  * megasas_free_cmds_fusion -   Free all the cmds in the free cmd pool
296  * @instance:           Adapter soft state
297  */
298 void
299 megasas_free_cmds_fusion(struct megasas_instance *instance)
300 {
301         int i;
302         struct fusion_context *fusion = instance->ctrl_context;
303         struct megasas_cmd_fusion *cmd;
304
305         /* SG, Sense */
306         for (i = 0; i < instance->max_mpt_cmds; i++) {
307                 cmd = fusion->cmd_list[i];
308                 if (cmd) {
309                         if (cmd->sg_frame)
310                                 dma_pool_free(fusion->sg_dma_pool, cmd->sg_frame,
311                                       cmd->sg_frame_phys_addr);
312                         if (cmd->sense)
313                                 dma_pool_free(fusion->sense_dma_pool, cmd->sense,
314                                       cmd->sense_phys_addr);
315                 }
316         }
317
318         if (fusion->sg_dma_pool) {
319                 dma_pool_destroy(fusion->sg_dma_pool);
320                 fusion->sg_dma_pool = NULL;
321         }
322         if (fusion->sense_dma_pool) {
323                 dma_pool_destroy(fusion->sense_dma_pool);
324                 fusion->sense_dma_pool = NULL;
325         }
326
327
328         /* Reply Frame, Desc*/
329         if (instance->is_rdpq)
330                 megasas_free_rdpq_fusion(instance);
331         else
332                 megasas_free_reply_fusion(instance);
333
334         /* Request Frame, Desc*/
335         if (fusion->req_frames_desc)
336                 dma_free_coherent(&instance->pdev->dev,
337                         fusion->request_alloc_sz, fusion->req_frames_desc,
338                         fusion->req_frames_desc_phys);
339         if (fusion->io_request_frames)
340                 dma_pool_free(fusion->io_request_frames_pool,
341                         fusion->io_request_frames,
342                         fusion->io_request_frames_phys);
343         if (fusion->io_request_frames_pool) {
344                 dma_pool_destroy(fusion->io_request_frames_pool);
345                 fusion->io_request_frames_pool = NULL;
346         }
347
348
349         /* cmd_list */
350         for (i = 0; i < instance->max_mpt_cmds; i++)
351                 kfree(fusion->cmd_list[i]);
352
353         kfree(fusion->cmd_list);
354 }
355
356 /**
357  * megasas_create_sg_sense_fusion -     Creates DMA pool for cmd frames
358  * @instance:                   Adapter soft state
359  *
360  */
361 static int megasas_create_sg_sense_fusion(struct megasas_instance *instance)
362 {
363         int i;
364         u16 max_cmd;
365         struct fusion_context *fusion;
366         struct megasas_cmd_fusion *cmd;
367
368         fusion = instance->ctrl_context;
369         max_cmd = instance->max_fw_cmds;
370
371
372         fusion->sg_dma_pool =
373                         dma_pool_create("mr_sg", &instance->pdev->dev,
374                                 instance->max_chain_frame_sz,
375                                 MR_DEFAULT_NVME_PAGE_SIZE, 0);
376         /* SCSI_SENSE_BUFFERSIZE  = 96 bytes */
377         fusion->sense_dma_pool =
378                         dma_pool_create("mr_sense", &instance->pdev->dev,
379                                 SCSI_SENSE_BUFFERSIZE, 64, 0);
380
381         if (!fusion->sense_dma_pool || !fusion->sg_dma_pool) {
382                 dev_err(&instance->pdev->dev,
383                         "Failed from %s %d\n",  __func__, __LINE__);
384                 return -ENOMEM;
385         }
386
387         /*
388          * Allocate and attach a frame to each of the commands in cmd_list
389          */
390         for (i = 0; i < max_cmd; i++) {
391                 cmd = fusion->cmd_list[i];
392                 cmd->sg_frame = dma_pool_alloc(fusion->sg_dma_pool,
393                                         GFP_KERNEL, &cmd->sg_frame_phys_addr);
394
395                 cmd->sense = dma_pool_alloc(fusion->sense_dma_pool,
396                                         GFP_KERNEL, &cmd->sense_phys_addr);
397                 if (!cmd->sg_frame || !cmd->sense) {
398                         dev_err(&instance->pdev->dev,
399                                 "Failed from %s %d\n",  __func__, __LINE__);
400                         return -ENOMEM;
401                 }
402         }
403
404         /* create sense buffer for the raid 1/10 fp */
405         for (i = max_cmd; i < instance->max_mpt_cmds; i++) {
406                 cmd = fusion->cmd_list[i];
407                 cmd->sense = dma_pool_alloc(fusion->sense_dma_pool,
408                         GFP_KERNEL, &cmd->sense_phys_addr);
409                 if (!cmd->sense) {
410                         dev_err(&instance->pdev->dev,
411                                 "Failed from %s %d\n",  __func__, __LINE__);
412                         return -ENOMEM;
413                 }
414         }
415
416         return 0;
417 }
418
419 int
420 megasas_alloc_cmdlist_fusion(struct megasas_instance *instance)
421 {
422         u32 max_mpt_cmd, i, j;
423         struct fusion_context *fusion;
424
425         fusion = instance->ctrl_context;
426
427         max_mpt_cmd = instance->max_mpt_cmds;
428
429         /*
430          * fusion->cmd_list is an array of struct megasas_cmd_fusion pointers.
431          * Allocate the dynamic array first and then allocate individual
432          * commands.
433          */
434         fusion->cmd_list =
435                 kzalloc(sizeof(struct megasas_cmd_fusion *) * max_mpt_cmd,
436                         GFP_KERNEL);
437         if (!fusion->cmd_list) {
438                 dev_err(&instance->pdev->dev,
439                         "Failed from %s %d\n",  __func__, __LINE__);
440                 return -ENOMEM;
441         }
442
443         for (i = 0; i < max_mpt_cmd; i++) {
444                 fusion->cmd_list[i] = kzalloc(sizeof(struct megasas_cmd_fusion),
445                                               GFP_KERNEL);
446                 if (!fusion->cmd_list[i]) {
447                         for (j = 0; j < i; j++)
448                                 kfree(fusion->cmd_list[j]);
449                         kfree(fusion->cmd_list);
450                         dev_err(&instance->pdev->dev,
451                                 "Failed from %s %d\n",  __func__, __LINE__);
452                         return -ENOMEM;
453                 }
454         }
455
456         return 0;
457 }
458 int
459 megasas_alloc_request_fusion(struct megasas_instance *instance)
460 {
461         struct fusion_context *fusion;
462
463         fusion = instance->ctrl_context;
464
465         fusion->req_frames_desc =
466                 dma_alloc_coherent(&instance->pdev->dev,
467                         fusion->request_alloc_sz,
468                         &fusion->req_frames_desc_phys, GFP_KERNEL);
469         if (!fusion->req_frames_desc) {
470                 dev_err(&instance->pdev->dev,
471                         "Failed from %s %d\n",  __func__, __LINE__);
472                 return -ENOMEM;
473         }
474
475         fusion->io_request_frames_pool =
476                         dma_pool_create("mr_ioreq", &instance->pdev->dev,
477                                 fusion->io_frames_alloc_sz, 16, 0);
478
479         if (!fusion->io_request_frames_pool) {
480                 dev_err(&instance->pdev->dev,
481                         "Failed from %s %d\n",  __func__, __LINE__);
482                 return -ENOMEM;
483         }
484
485         fusion->io_request_frames =
486                         dma_pool_alloc(fusion->io_request_frames_pool,
487                                 GFP_KERNEL, &fusion->io_request_frames_phys);
488         if (!fusion->io_request_frames) {
489                 dev_err(&instance->pdev->dev,
490                         "Failed from %s %d\n",  __func__, __LINE__);
491                 return -ENOMEM;
492         }
493         return 0;
494 }
495
496 int
497 megasas_alloc_reply_fusion(struct megasas_instance *instance)
498 {
499         int i, count;
500         struct fusion_context *fusion;
501         union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
502         fusion = instance->ctrl_context;
503
504         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
505         fusion->reply_frames_desc_pool =
506                         dma_pool_create("mr_reply", &instance->pdev->dev,
507                                 fusion->reply_alloc_sz * count, 16, 0);
508
509         if (!fusion->reply_frames_desc_pool) {
510                 dev_err(&instance->pdev->dev,
511                         "Failed from %s %d\n",  __func__, __LINE__);
512                 return -ENOMEM;
513         }
514
515         fusion->reply_frames_desc[0] =
516                 dma_pool_alloc(fusion->reply_frames_desc_pool,
517                         GFP_KERNEL, &fusion->reply_frames_desc_phys[0]);
518         if (!fusion->reply_frames_desc[0]) {
519                 dev_err(&instance->pdev->dev,
520                         "Failed from %s %d\n",  __func__, __LINE__);
521                 return -ENOMEM;
522         }
523         reply_desc = fusion->reply_frames_desc[0];
524         for (i = 0; i < fusion->reply_q_depth * count; i++, reply_desc++)
525                 reply_desc->Words = cpu_to_le64(ULLONG_MAX);
526
527         /* This is not a rdpq mode, but driver still populate
528          * reply_frame_desc array to use same msix index in ISR path.
529          */
530         for (i = 0; i < (count - 1); i++)
531                 fusion->reply_frames_desc[i + 1] =
532                         fusion->reply_frames_desc[i] +
533                         (fusion->reply_alloc_sz)/sizeof(union MPI2_REPLY_DESCRIPTORS_UNION);
534
535         return 0;
536 }
537
538 int
539 megasas_alloc_rdpq_fusion(struct megasas_instance *instance)
540 {
541         int i, j, count;
542         struct fusion_context *fusion;
543         union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
544
545         fusion = instance->ctrl_context;
546
547         fusion->rdpq_virt = pci_alloc_consistent(instance->pdev,
548                                 sizeof(struct MPI2_IOC_INIT_RDPQ_ARRAY_ENTRY) * MAX_MSIX_QUEUES_FUSION,
549                                 &fusion->rdpq_phys);
550         if (!fusion->rdpq_virt) {
551                 dev_err(&instance->pdev->dev,
552                         "Failed from %s %d\n",  __func__, __LINE__);
553                 return -ENOMEM;
554         }
555
556         memset(fusion->rdpq_virt, 0,
557                         sizeof(struct MPI2_IOC_INIT_RDPQ_ARRAY_ENTRY) * MAX_MSIX_QUEUES_FUSION);
558         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
559         fusion->reply_frames_desc_pool = dma_pool_create("mr_rdpq",
560                                                          &instance->pdev->dev,
561                                                          fusion->reply_alloc_sz,
562                                                          16, 0);
563
564         if (!fusion->reply_frames_desc_pool) {
565                 dev_err(&instance->pdev->dev,
566                         "Failed from %s %d\n",  __func__, __LINE__);
567                 return -ENOMEM;
568         }
569
570         for (i = 0; i < count; i++) {
571                 fusion->reply_frames_desc[i] =
572                                 dma_pool_alloc(fusion->reply_frames_desc_pool,
573                                         GFP_KERNEL, &fusion->reply_frames_desc_phys[i]);
574                 if (!fusion->reply_frames_desc[i]) {
575                         dev_err(&instance->pdev->dev,
576                                 "Failed from %s %d\n",  __func__, __LINE__);
577                         return -ENOMEM;
578                 }
579
580                 fusion->rdpq_virt[i].RDPQBaseAddress =
581                         cpu_to_le64(fusion->reply_frames_desc_phys[i]);
582
583                 reply_desc = fusion->reply_frames_desc[i];
584                 for (j = 0; j < fusion->reply_q_depth; j++, reply_desc++)
585                         reply_desc->Words = cpu_to_le64(ULLONG_MAX);
586         }
587         return 0;
588 }
589
590 static void
591 megasas_free_rdpq_fusion(struct megasas_instance *instance) {
592
593         int i;
594         struct fusion_context *fusion;
595
596         fusion = instance->ctrl_context;
597
598         for (i = 0; i < MAX_MSIX_QUEUES_FUSION; i++) {
599                 if (fusion->reply_frames_desc[i])
600                         dma_pool_free(fusion->reply_frames_desc_pool,
601                                 fusion->reply_frames_desc[i],
602                                 fusion->reply_frames_desc_phys[i]);
603         }
604
605         if (fusion->reply_frames_desc_pool)
606                 dma_pool_destroy(fusion->reply_frames_desc_pool);
607
608         if (fusion->rdpq_virt)
609                 pci_free_consistent(instance->pdev,
610                         sizeof(struct MPI2_IOC_INIT_RDPQ_ARRAY_ENTRY) * MAX_MSIX_QUEUES_FUSION,
611                         fusion->rdpq_virt, fusion->rdpq_phys);
612 }
613
614 static void
615 megasas_free_reply_fusion(struct megasas_instance *instance) {
616
617         struct fusion_context *fusion;
618
619         fusion = instance->ctrl_context;
620
621         if (fusion->reply_frames_desc[0])
622                 dma_pool_free(fusion->reply_frames_desc_pool,
623                         fusion->reply_frames_desc[0],
624                         fusion->reply_frames_desc_phys[0]);
625
626         if (fusion->reply_frames_desc_pool)
627                 dma_pool_destroy(fusion->reply_frames_desc_pool);
628
629 }
630
631
632 /**
633  * megasas_alloc_cmds_fusion -  Allocates the command packets
634  * @instance:           Adapter soft state
635  *
636  *
637  * Each frame has a 32-bit field called context. This context is used to get
638  * back the megasas_cmd_fusion from the frame when a frame gets completed
639  * In this driver, the 32 bit values are the indices into an array cmd_list.
640  * This array is used only to look up the megasas_cmd_fusion given the context.
641  * The free commands themselves are maintained in a linked list called cmd_pool.
642  *
643  * cmds are formed in the io_request and sg_frame members of the
644  * megasas_cmd_fusion. The context field is used to get a request descriptor
645  * and is used as SMID of the cmd.
646  * SMID value range is from 1 to max_fw_cmds.
647  */
648 int
649 megasas_alloc_cmds_fusion(struct megasas_instance *instance)
650 {
651         int i;
652         struct fusion_context *fusion;
653         struct megasas_cmd_fusion *cmd;
654         u32 offset;
655         dma_addr_t io_req_base_phys;
656         u8 *io_req_base;
657
658
659         fusion = instance->ctrl_context;
660
661         if (megasas_alloc_cmdlist_fusion(instance))
662                 goto fail_exit;
663
664         if (megasas_alloc_request_fusion(instance))
665                 goto fail_exit;
666
667         if (instance->is_rdpq) {
668                 if (megasas_alloc_rdpq_fusion(instance))
669                         goto fail_exit;
670         } else
671                 if (megasas_alloc_reply_fusion(instance))
672                         goto fail_exit;
673
674
675         /* The first 256 bytes (SMID 0) is not used. Don't add to the cmd list */
676         io_req_base = fusion->io_request_frames + MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
677         io_req_base_phys = fusion->io_request_frames_phys + MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE;
678
679         /*
680          * Add all the commands to command pool (fusion->cmd_pool)
681          */
682
683         /* SMID 0 is reserved. Set SMID/index from 1 */
684         for (i = 0; i < instance->max_mpt_cmds; i++) {
685                 cmd = fusion->cmd_list[i];
686                 offset = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE * i;
687                 memset(cmd, 0, sizeof(struct megasas_cmd_fusion));
688                 cmd->index = i + 1;
689                 cmd->scmd = NULL;
690                 cmd->sync_cmd_idx =
691                 (i >= instance->max_scsi_cmds && i < instance->max_fw_cmds) ?
692                                 (i - instance->max_scsi_cmds) :
693                                 (u32)ULONG_MAX; /* Set to Invalid */
694                 cmd->instance = instance;
695                 cmd->io_request =
696                         (struct MPI2_RAID_SCSI_IO_REQUEST *)
697                   (io_req_base + offset);
698                 memset(cmd->io_request, 0,
699                        sizeof(struct MPI2_RAID_SCSI_IO_REQUEST));
700                 cmd->io_request_phys_addr = io_req_base_phys + offset;
701                 cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
702         }
703
704         if (megasas_create_sg_sense_fusion(instance))
705                 goto fail_exit;
706
707         return 0;
708
709 fail_exit:
710         megasas_free_cmds_fusion(instance);
711         return -ENOMEM;
712 }
713
714 /**
715  * wait_and_poll -      Issues a polling command
716  * @instance:                   Adapter soft state
717  * @cmd:                        Command packet to be issued
718  *
719  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
720  */
721 int
722 wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
723         int seconds)
724 {
725         int i;
726         struct megasas_header *frame_hdr = &cmd->frame->hdr;
727         struct fusion_context *fusion;
728
729         u32 msecs = seconds * 1000;
730
731         fusion = instance->ctrl_context;
732         /*
733          * Wait for cmd_status to change
734          */
735         for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i += 20) {
736                 rmb();
737                 msleep(20);
738         }
739
740         if (frame_hdr->cmd_status == MFI_STAT_INVALID_STATUS)
741                 return DCMD_TIMEOUT;
742         else if (frame_hdr->cmd_status == MFI_STAT_OK)
743                 return DCMD_SUCCESS;
744         else
745                 return DCMD_FAILED;
746 }
747
748 /**
749  * megasas_ioc_init_fusion -    Initializes the FW
750  * @instance:           Adapter soft state
751  *
752  * Issues the IOC Init cmd
753  */
754 int
755 megasas_ioc_init_fusion(struct megasas_instance *instance)
756 {
757         struct megasas_init_frame *init_frame;
758         struct MPI2_IOC_INIT_REQUEST *IOCInitMessage = NULL;
759         dma_addr_t      ioc_init_handle;
760         struct megasas_cmd *cmd;
761         u8 ret, cur_rdpq_mode;
762         struct fusion_context *fusion;
763         union MEGASAS_REQUEST_DESCRIPTOR_UNION req_desc;
764         int i;
765         struct megasas_header *frame_hdr;
766         const char *sys_info;
767         MFI_CAPABILITIES *drv_ops;
768         u32 scratch_pad_2;
769
770         fusion = instance->ctrl_context;
771
772         cmd = megasas_get_cmd(instance);
773
774         if (!cmd) {
775                 dev_err(&instance->pdev->dev, "Could not allocate cmd for INIT Frame\n");
776                 ret = 1;
777                 goto fail_get_cmd;
778         }
779
780         scratch_pad_2 = readl
781                 (&instance->reg_set->outbound_scratch_pad_2);
782
783         cur_rdpq_mode = (scratch_pad_2 & MR_RDPQ_MODE_OFFSET) ? 1 : 0;
784
785         if (instance->is_rdpq && !cur_rdpq_mode) {
786                 dev_err(&instance->pdev->dev, "Firmware downgrade *NOT SUPPORTED*"
787                         " from RDPQ mode to non RDPQ mode\n");
788                 ret = 1;
789                 goto fail_fw_init;
790         }
791
792         instance->fw_sync_cache_support = (scratch_pad_2 &
793                 MR_CAN_HANDLE_SYNC_CACHE_OFFSET) ? 1 : 0;
794         dev_info(&instance->pdev->dev, "FW supports sync cache\t: %s\n",
795                  instance->fw_sync_cache_support ? "Yes" : "No");
796
797         IOCInitMessage =
798           dma_alloc_coherent(&instance->pdev->dev,
799                              sizeof(struct MPI2_IOC_INIT_REQUEST),
800                              &ioc_init_handle, GFP_KERNEL);
801
802         if (!IOCInitMessage) {
803                 dev_err(&instance->pdev->dev, "Could not allocate memory for "
804                        "IOCInitMessage\n");
805                 ret = 1;
806                 goto fail_fw_init;
807         }
808
809         memset(IOCInitMessage, 0, sizeof(struct MPI2_IOC_INIT_REQUEST));
810
811         IOCInitMessage->Function = MPI2_FUNCTION_IOC_INIT;
812         IOCInitMessage->WhoInit = MPI2_WHOINIT_HOST_DRIVER;
813         IOCInitMessage->MsgVersion = cpu_to_le16(MPI2_VERSION);
814         IOCInitMessage->HeaderVersion = cpu_to_le16(MPI2_HEADER_VERSION);
815         IOCInitMessage->SystemRequestFrameSize = cpu_to_le16(MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE / 4);
816
817         IOCInitMessage->ReplyDescriptorPostQueueDepth = cpu_to_le16(fusion->reply_q_depth);
818         IOCInitMessage->ReplyDescriptorPostQueueAddress = instance->is_rdpq ?
819                         cpu_to_le64(fusion->rdpq_phys) :
820                         cpu_to_le64(fusion->reply_frames_desc_phys[0]);
821         IOCInitMessage->MsgFlags = instance->is_rdpq ?
822                         MPI2_IOCINIT_MSGFLAG_RDPQ_ARRAY_MODE : 0;
823         IOCInitMessage->SystemRequestFrameBaseAddress = cpu_to_le64(fusion->io_request_frames_phys);
824         IOCInitMessage->HostMSIxVectors = instance->msix_vectors;
825         IOCInitMessage->HostPageSize = MR_DEFAULT_NVME_PAGE_SHIFT;
826         init_frame = (struct megasas_init_frame *)cmd->frame;
827         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
828
829         frame_hdr = &cmd->frame->hdr;
830         frame_hdr->cmd_status = 0xFF;
831         frame_hdr->flags = cpu_to_le16(
832                 le16_to_cpu(frame_hdr->flags) |
833                 MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
834
835         init_frame->cmd = MFI_CMD_INIT;
836         init_frame->cmd_status = 0xFF;
837
838         drv_ops = (MFI_CAPABILITIES *) &(init_frame->driver_operations);
839
840         /* driver support Extended MSIX */
841         if (instance->adapter_type >= INVADER_SERIES)
842                 drv_ops->mfi_capabilities.support_additional_msix = 1;
843         /* driver supports HA / Remote LUN over Fast Path interface */
844         drv_ops->mfi_capabilities.support_fp_remote_lun = 1;
845
846         drv_ops->mfi_capabilities.support_max_255lds = 1;
847         drv_ops->mfi_capabilities.support_ndrive_r1_lb = 1;
848         drv_ops->mfi_capabilities.security_protocol_cmds_fw = 1;
849
850         if (instance->max_chain_frame_sz > MEGASAS_CHAIN_FRAME_SZ_MIN)
851                 drv_ops->mfi_capabilities.support_ext_io_size = 1;
852
853         drv_ops->mfi_capabilities.support_fp_rlbypass = 1;
854         if (!dual_qdepth_disable)
855                 drv_ops->mfi_capabilities.support_ext_queue_depth = 1;
856
857         drv_ops->mfi_capabilities.support_qd_throttling = 1;
858         drv_ops->mfi_capabilities.support_pd_map_target_id = 1;
859         /* Convert capability to LE32 */
860         cpu_to_le32s((u32 *)&init_frame->driver_operations.mfi_capabilities);
861
862         sys_info = dmi_get_system_info(DMI_PRODUCT_UUID);
863         if (instance->system_info_buf && sys_info) {
864                 memcpy(instance->system_info_buf->systemId, sys_info,
865                         strlen(sys_info) > 64 ? 64 : strlen(sys_info));
866                 instance->system_info_buf->systemIdLength =
867                         strlen(sys_info) > 64 ? 64 : strlen(sys_info);
868                 init_frame->system_info_lo = instance->system_info_h;
869                 init_frame->system_info_hi = 0;
870         }
871
872         init_frame->queue_info_new_phys_addr_hi =
873                 cpu_to_le32(upper_32_bits(ioc_init_handle));
874         init_frame->queue_info_new_phys_addr_lo =
875                 cpu_to_le32(lower_32_bits(ioc_init_handle));
876         init_frame->data_xfer_len = cpu_to_le32(sizeof(struct MPI2_IOC_INIT_REQUEST));
877
878         req_desc.u.low = cpu_to_le32(lower_32_bits(cmd->frame_phys_addr));
879         req_desc.u.high = cpu_to_le32(upper_32_bits(cmd->frame_phys_addr));
880         req_desc.MFAIo.RequestFlags =
881                 (MEGASAS_REQ_DESCRIPT_FLAGS_MFA <<
882                 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
883
884         /*
885          * disable the intr before firing the init frame
886          */
887         instance->instancet->disable_intr(instance);
888
889         for (i = 0; i < (10 * 1000); i += 20) {
890                 if (readl(&instance->reg_set->doorbell) & 1)
891                         msleep(20);
892                 else
893                         break;
894         }
895
896         megasas_fire_cmd_fusion(instance, &req_desc);
897
898         wait_and_poll(instance, cmd, MFI_POLL_TIMEOUT_SECS);
899
900         frame_hdr = &cmd->frame->hdr;
901         if (frame_hdr->cmd_status != 0) {
902                 ret = 1;
903                 goto fail_fw_init;
904         }
905
906         return 0;
907
908 fail_fw_init:
909         megasas_return_cmd(instance, cmd);
910         if (IOCInitMessage)
911                 dma_free_coherent(&instance->pdev->dev,
912                                   sizeof(struct MPI2_IOC_INIT_REQUEST),
913                                   IOCInitMessage, ioc_init_handle);
914 fail_get_cmd:
915         dev_err(&instance->pdev->dev,
916                 "Init cmd return status FAILED for SCSI host %d\n",
917                 instance->host->host_no);
918
919         return ret;
920 }
921
922 /**
923  * megasas_sync_pd_seq_num -    JBOD SEQ MAP
924  * @instance:           Adapter soft state
925  * @pend:               set to 1, if it is pended jbod map.
926  *
927  * Issue Jbod map to the firmware. If it is pended command,
928  * issue command and return. If it is first instance of jbod map
929  * issue and receive command.
930  */
931 int
932 megasas_sync_pd_seq_num(struct megasas_instance *instance, bool pend) {
933         int ret = 0;
934         u32 pd_seq_map_sz;
935         struct megasas_cmd *cmd;
936         struct megasas_dcmd_frame *dcmd;
937         struct fusion_context *fusion = instance->ctrl_context;
938         struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
939         dma_addr_t pd_seq_h;
940
941         pd_sync = (void *)fusion->pd_seq_sync[(instance->pd_seq_map_id & 1)];
942         pd_seq_h = fusion->pd_seq_phys[(instance->pd_seq_map_id & 1)];
943         pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) +
944                         (sizeof(struct MR_PD_CFG_SEQ) *
945                         (MAX_PHYSICAL_DEVICES - 1));
946
947         cmd = megasas_get_cmd(instance);
948         if (!cmd) {
949                 dev_err(&instance->pdev->dev,
950                         "Could not get mfi cmd. Fail from %s %d\n",
951                         __func__, __LINE__);
952                 return -ENOMEM;
953         }
954
955         dcmd = &cmd->frame->dcmd;
956
957         memset(pd_sync, 0, pd_seq_map_sz);
958         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
959         dcmd->cmd = MFI_CMD_DCMD;
960         dcmd->cmd_status = 0xFF;
961         dcmd->sge_count = 1;
962         dcmd->timeout = 0;
963         dcmd->pad_0 = 0;
964         dcmd->data_xfer_len = cpu_to_le32(pd_seq_map_sz);
965         dcmd->opcode = cpu_to_le32(MR_DCMD_SYSTEM_PD_MAP_GET_INFO);
966         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(pd_seq_h);
967         dcmd->sgl.sge32[0].length = cpu_to_le32(pd_seq_map_sz);
968
969         if (pend) {
970                 dcmd->mbox.b[0] = MEGASAS_DCMD_MBOX_PEND_FLAG;
971                 dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_WRITE);
972                 instance->jbod_seq_cmd = cmd;
973                 instance->instancet->issue_dcmd(instance, cmd);
974                 return 0;
975         }
976
977         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
978
979         /* Below code is only for non pended DCMD */
980         if (instance->ctrl_context && !instance->mask_interrupts)
981                 ret = megasas_issue_blocked_cmd(instance, cmd,
982                         MFI_IO_TIMEOUT_SECS);
983         else
984                 ret = megasas_issue_polled(instance, cmd);
985
986         if (le32_to_cpu(pd_sync->count) > MAX_PHYSICAL_DEVICES) {
987                 dev_warn(&instance->pdev->dev,
988                         "driver supports max %d JBOD, but FW reports %d\n",
989                         MAX_PHYSICAL_DEVICES, le32_to_cpu(pd_sync->count));
990                 ret = -EINVAL;
991         }
992
993         if (ret == DCMD_TIMEOUT && instance->ctrl_context)
994                 megaraid_sas_kill_hba(instance);
995
996         if (ret == DCMD_SUCCESS)
997                 instance->pd_seq_map_id++;
998
999         megasas_return_cmd(instance, cmd);
1000         return ret;
1001 }
1002
1003 /*
1004  * megasas_get_ld_map_info -    Returns FW's ld_map structure
1005  * @instance:                           Adapter soft state
1006  * @pend:                               Pend the command or not
1007  * Issues an internal command (DCMD) to get the FW's controller PD
1008  * list structure.  This information is mainly used to find out SYSTEM
1009  * supported by the FW.
1010  * dcmd.mbox value setting for MR_DCMD_LD_MAP_GET_INFO
1011  * dcmd.mbox.b[0]       - number of LDs being sync'd
1012  * dcmd.mbox.b[1]       - 0 - complete command immediately.
1013  *                      - 1 - pend till config change
1014  * dcmd.mbox.b[2]       - 0 - supports max 64 lds and uses legacy MR_FW_RAID_MAP
1015  *                      - 1 - supports max MAX_LOGICAL_DRIVES_EXT lds and
1016  *                              uses extended struct MR_FW_RAID_MAP_EXT
1017  */
1018 static int
1019 megasas_get_ld_map_info(struct megasas_instance *instance)
1020 {
1021         int ret = 0;
1022         struct megasas_cmd *cmd;
1023         struct megasas_dcmd_frame *dcmd;
1024         void *ci;
1025         dma_addr_t ci_h = 0;
1026         u32 size_map_info;
1027         struct fusion_context *fusion;
1028
1029         cmd = megasas_get_cmd(instance);
1030
1031         if (!cmd) {
1032                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get cmd for map info\n");
1033                 return -ENOMEM;
1034         }
1035
1036         fusion = instance->ctrl_context;
1037
1038         if (!fusion) {
1039                 megasas_return_cmd(instance, cmd);
1040                 return -ENXIO;
1041         }
1042
1043         dcmd = &cmd->frame->dcmd;
1044
1045         size_map_info = fusion->current_map_sz;
1046
1047         ci = (void *) fusion->ld_map[(instance->map_id & 1)];
1048         ci_h = fusion->ld_map_phys[(instance->map_id & 1)];
1049
1050         if (!ci) {
1051                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to alloc mem for ld_map_info\n");
1052                 megasas_return_cmd(instance, cmd);
1053                 return -ENOMEM;
1054         }
1055
1056         memset(ci, 0, fusion->max_map_sz);
1057         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1058         dcmd->cmd = MFI_CMD_DCMD;
1059         dcmd->cmd_status = 0xFF;
1060         dcmd->sge_count = 1;
1061         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
1062         dcmd->timeout = 0;
1063         dcmd->pad_0 = 0;
1064         dcmd->data_xfer_len = cpu_to_le32(size_map_info);
1065         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_MAP_GET_INFO);
1066         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
1067         dcmd->sgl.sge32[0].length = cpu_to_le32(size_map_info);
1068
1069         if (instance->ctrl_context && !instance->mask_interrupts)
1070                 ret = megasas_issue_blocked_cmd(instance, cmd,
1071                         MFI_IO_TIMEOUT_SECS);
1072         else
1073                 ret = megasas_issue_polled(instance, cmd);
1074
1075         if (ret == DCMD_TIMEOUT && instance->ctrl_context)
1076                 megaraid_sas_kill_hba(instance);
1077
1078         megasas_return_cmd(instance, cmd);
1079
1080         return ret;
1081 }
1082
1083 u8
1084 megasas_get_map_info(struct megasas_instance *instance)
1085 {
1086         struct fusion_context *fusion = instance->ctrl_context;
1087
1088         fusion->fast_path_io = 0;
1089         if (!megasas_get_ld_map_info(instance)) {
1090                 if (MR_ValidateMapInfo(instance)) {
1091                         fusion->fast_path_io = 1;
1092                         return 0;
1093                 }
1094         }
1095         return 1;
1096 }
1097
1098 /*
1099  * megasas_sync_map_info -      Returns FW's ld_map structure
1100  * @instance:                           Adapter soft state
1101  *
1102  * Issues an internal command (DCMD) to get the FW's controller PD
1103  * list structure.  This information is mainly used to find out SYSTEM
1104  * supported by the FW.
1105  */
1106 int
1107 megasas_sync_map_info(struct megasas_instance *instance)
1108 {
1109         int i;
1110         struct megasas_cmd *cmd;
1111         struct megasas_dcmd_frame *dcmd;
1112         u16 num_lds;
1113         u32 size_sync_info;
1114         struct fusion_context *fusion;
1115         struct MR_LD_TARGET_SYNC *ci = NULL;
1116         struct MR_DRV_RAID_MAP_ALL *map;
1117         struct MR_LD_RAID  *raid;
1118         struct MR_LD_TARGET_SYNC *ld_sync;
1119         dma_addr_t ci_h = 0;
1120         u32 size_map_info;
1121
1122         cmd = megasas_get_cmd(instance);
1123
1124         if (!cmd) {
1125                 dev_printk(KERN_DEBUG, &instance->pdev->dev, "Failed to get cmd for sync info\n");
1126                 return -ENOMEM;
1127         }
1128
1129         fusion = instance->ctrl_context;
1130
1131         if (!fusion) {
1132                 megasas_return_cmd(instance, cmd);
1133                 return 1;
1134         }
1135
1136         map = fusion->ld_drv_map[instance->map_id & 1];
1137
1138         num_lds = le16_to_cpu(map->raidMap.ldCount);
1139
1140         dcmd = &cmd->frame->dcmd;
1141
1142         size_sync_info = sizeof(struct MR_LD_TARGET_SYNC) *num_lds;
1143
1144         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1145
1146         ci = (struct MR_LD_TARGET_SYNC *)
1147           fusion->ld_map[(instance->map_id - 1) & 1];
1148         memset(ci, 0, fusion->max_map_sz);
1149
1150         ci_h = fusion->ld_map_phys[(instance->map_id - 1) & 1];
1151
1152         ld_sync = (struct MR_LD_TARGET_SYNC *)ci;
1153
1154         for (i = 0; i < num_lds; i++, ld_sync++) {
1155                 raid = MR_LdRaidGet(i, map);
1156                 ld_sync->targetId = MR_GetLDTgtId(i, map);
1157                 ld_sync->seqNum = raid->seqNum;
1158         }
1159
1160         size_map_info = fusion->current_map_sz;
1161
1162         dcmd->cmd = MFI_CMD_DCMD;
1163         dcmd->cmd_status = 0xFF;
1164         dcmd->sge_count = 1;
1165         dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_WRITE);
1166         dcmd->timeout = 0;
1167         dcmd->pad_0 = 0;
1168         dcmd->data_xfer_len = cpu_to_le32(size_map_info);
1169         dcmd->mbox.b[0] = num_lds;
1170         dcmd->mbox.b[1] = MEGASAS_DCMD_MBOX_PEND_FLAG;
1171         dcmd->opcode = cpu_to_le32(MR_DCMD_LD_MAP_GET_INFO);
1172         dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
1173         dcmd->sgl.sge32[0].length = cpu_to_le32(size_map_info);
1174
1175         instance->map_update_cmd = cmd;
1176
1177         instance->instancet->issue_dcmd(instance, cmd);
1178
1179         return 0;
1180 }
1181
1182 /*
1183  * meagasas_display_intel_branding - Display branding string
1184  * @instance: per adapter object
1185  *
1186  * Return nothing.
1187  */
1188 static void
1189 megasas_display_intel_branding(struct megasas_instance *instance)
1190 {
1191         if (instance->pdev->subsystem_vendor != PCI_VENDOR_ID_INTEL)
1192                 return;
1193
1194         switch (instance->pdev->device) {
1195         case PCI_DEVICE_ID_LSI_INVADER:
1196                 switch (instance->pdev->subsystem_device) {
1197                 case MEGARAID_INTEL_RS3DC080_SSDID:
1198                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1199                                 instance->host->host_no,
1200                                 MEGARAID_INTEL_RS3DC080_BRANDING);
1201                         break;
1202                 case MEGARAID_INTEL_RS3DC040_SSDID:
1203                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1204                                 instance->host->host_no,
1205                                 MEGARAID_INTEL_RS3DC040_BRANDING);
1206                         break;
1207                 case MEGARAID_INTEL_RS3SC008_SSDID:
1208                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1209                                 instance->host->host_no,
1210                                 MEGARAID_INTEL_RS3SC008_BRANDING);
1211                         break;
1212                 case MEGARAID_INTEL_RS3MC044_SSDID:
1213                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1214                                 instance->host->host_no,
1215                                 MEGARAID_INTEL_RS3MC044_BRANDING);
1216                         break;
1217                 default:
1218                         break;
1219                 }
1220                 break;
1221         case PCI_DEVICE_ID_LSI_FURY:
1222                 switch (instance->pdev->subsystem_device) {
1223                 case MEGARAID_INTEL_RS3WC080_SSDID:
1224                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1225                                 instance->host->host_no,
1226                                 MEGARAID_INTEL_RS3WC080_BRANDING);
1227                         break;
1228                 case MEGARAID_INTEL_RS3WC040_SSDID:
1229                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1230                                 instance->host->host_no,
1231                                 MEGARAID_INTEL_RS3WC040_BRANDING);
1232                         break;
1233                 default:
1234                         break;
1235                 }
1236                 break;
1237         case PCI_DEVICE_ID_LSI_CUTLASS_52:
1238         case PCI_DEVICE_ID_LSI_CUTLASS_53:
1239                 switch (instance->pdev->subsystem_device) {
1240                 case MEGARAID_INTEL_RMS3BC160_SSDID:
1241                         dev_info(&instance->pdev->dev, "scsi host %d: %s\n",
1242                                 instance->host->host_no,
1243                                 MEGARAID_INTEL_RMS3BC160_BRANDING);
1244                         break;
1245                 default:
1246                         break;
1247                 }
1248                 break;
1249         default:
1250                 break;
1251         }
1252 }
1253
1254 /**
1255  * megasas_allocate_raid_maps - Allocate memory for RAID maps
1256  * @instance:                           Adapter soft state
1257  *
1258  * return:                              if success: return 0
1259  *                                      failed:  return -ENOMEM
1260  */
1261 static inline int megasas_allocate_raid_maps(struct megasas_instance *instance)
1262 {
1263         struct fusion_context *fusion;
1264         int i = 0;
1265
1266         fusion = instance->ctrl_context;
1267
1268         fusion->drv_map_pages = get_order(fusion->drv_map_sz);
1269
1270         for (i = 0; i < 2; i++) {
1271                 fusion->ld_map[i] = NULL;
1272
1273                 fusion->ld_drv_map[i] = (void *)
1274                         __get_free_pages(__GFP_ZERO | GFP_KERNEL,
1275                                          fusion->drv_map_pages);
1276
1277                 if (!fusion->ld_drv_map[i]) {
1278                         fusion->ld_drv_map[i] = vzalloc(fusion->drv_map_sz);
1279
1280                         if (!fusion->ld_drv_map[i]) {
1281                                 dev_err(&instance->pdev->dev,
1282                                         "Could not allocate memory for local map"
1283                                         " size requested: %d\n",
1284                                         fusion->drv_map_sz);
1285                                 goto ld_drv_map_alloc_fail;
1286                         }
1287                 }
1288         }
1289
1290         for (i = 0; i < 2; i++) {
1291                 fusion->ld_map[i] = dma_alloc_coherent(&instance->pdev->dev,
1292                                                        fusion->max_map_sz,
1293                                                        &fusion->ld_map_phys[i],
1294                                                        GFP_KERNEL);
1295                 if (!fusion->ld_map[i]) {
1296                         dev_err(&instance->pdev->dev,
1297                                 "Could not allocate memory for map info %s:%d\n",
1298                                 __func__, __LINE__);
1299                         goto ld_map_alloc_fail;
1300                 }
1301         }
1302
1303         return 0;
1304
1305 ld_map_alloc_fail:
1306         for (i = 0; i < 2; i++) {
1307                 if (fusion->ld_map[i])
1308                         dma_free_coherent(&instance->pdev->dev,
1309                                           fusion->max_map_sz,
1310                                           fusion->ld_map[i],
1311                                           fusion->ld_map_phys[i]);
1312         }
1313
1314 ld_drv_map_alloc_fail:
1315         for (i = 0; i < 2; i++) {
1316                 if (fusion->ld_drv_map[i]) {
1317                         if (is_vmalloc_addr(fusion->ld_drv_map[i]))
1318                                 vfree(fusion->ld_drv_map[i]);
1319                         else
1320                                 free_pages((ulong)fusion->ld_drv_map[i],
1321                                            fusion->drv_map_pages);
1322                 }
1323         }
1324
1325         return -ENOMEM;
1326 }
1327
1328 /**
1329  * megasas_init_adapter_fusion -        Initializes the FW
1330  * @instance:           Adapter soft state
1331  *
1332  * This is the main function for initializing firmware.
1333  */
1334 u32
1335 megasas_init_adapter_fusion(struct megasas_instance *instance)
1336 {
1337         struct megasas_register_set __iomem *reg_set;
1338         struct fusion_context *fusion;
1339         u16 max_cmd;
1340         u32 scratch_pad_2;
1341         int i = 0, count;
1342
1343         fusion = instance->ctrl_context;
1344
1345         reg_set = instance->reg_set;
1346
1347         megasas_fusion_update_can_queue(instance, PROBE_CONTEXT);
1348
1349         /*
1350          * Only Driver's internal DCMDs and IOCTL DCMDs needs to have MFI frames
1351          */
1352         instance->max_mfi_cmds =
1353                 MEGASAS_FUSION_INTERNAL_CMDS + MEGASAS_FUSION_IOCTL_CMDS;
1354
1355         max_cmd = instance->max_fw_cmds;
1356
1357         fusion->reply_q_depth = 2 * (((max_cmd + 1 + 15)/16)*16);
1358
1359         fusion->request_alloc_sz =
1360         sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) * instance->max_mpt_cmds;
1361         fusion->reply_alloc_sz = sizeof(union MPI2_REPLY_DESCRIPTORS_UNION)
1362                 *(fusion->reply_q_depth);
1363         fusion->io_frames_alloc_sz = MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE +
1364                 (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE
1365                 * (instance->max_mpt_cmds + 1)); /* Extra 1 for SMID 0 */
1366
1367         scratch_pad_2 = readl(&instance->reg_set->outbound_scratch_pad_2);
1368         /* If scratch_pad_2 & MEGASAS_MAX_CHAIN_SIZE_UNITS_MASK is set,
1369          * Firmware support extended IO chain frame which is 4 times more than
1370          * legacy Firmware.
1371          * Legacy Firmware - Frame size is (8 * 128) = 1K
1372          * 1M IO Firmware  - Frame size is (8 * 128 * 4)  = 4K
1373          */
1374         if (scratch_pad_2 & MEGASAS_MAX_CHAIN_SIZE_UNITS_MASK)
1375                 instance->max_chain_frame_sz =
1376                         ((scratch_pad_2 & MEGASAS_MAX_CHAIN_SIZE_MASK) >>
1377                         MEGASAS_MAX_CHAIN_SHIFT) * MEGASAS_1MB_IO;
1378         else
1379                 instance->max_chain_frame_sz =
1380                         ((scratch_pad_2 & MEGASAS_MAX_CHAIN_SIZE_MASK) >>
1381                         MEGASAS_MAX_CHAIN_SHIFT) * MEGASAS_256K_IO;
1382
1383         if (instance->max_chain_frame_sz < MEGASAS_CHAIN_FRAME_SZ_MIN) {
1384                 dev_warn(&instance->pdev->dev, "frame size %d invalid, fall back to legacy max frame size %d\n",
1385                         instance->max_chain_frame_sz,
1386                         MEGASAS_CHAIN_FRAME_SZ_MIN);
1387                 instance->max_chain_frame_sz = MEGASAS_CHAIN_FRAME_SZ_MIN;
1388         }
1389
1390         fusion->max_sge_in_main_msg =
1391                 (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE
1392                         - offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL))/16;
1393
1394         fusion->max_sge_in_chain =
1395                 instance->max_chain_frame_sz
1396                         / sizeof(union MPI2_SGE_IO_UNION);
1397
1398         instance->max_num_sge =
1399                 rounddown_pow_of_two(fusion->max_sge_in_main_msg
1400                         + fusion->max_sge_in_chain - 2);
1401
1402         /* Used for pass thru MFI frame (DCMD) */
1403         fusion->chain_offset_mfi_pthru =
1404                 offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL)/16;
1405
1406         fusion->chain_offset_io_request =
1407                 (MEGA_MPI2_RAID_DEFAULT_IO_FRAME_SIZE -
1408                  sizeof(union MPI2_SGE_IO_UNION))/16;
1409
1410         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
1411         for (i = 0 ; i < count; i++)
1412                 fusion->last_reply_idx[i] = 0;
1413
1414         /*
1415          * For fusion adapters, 3 commands for IOCTL and 8 commands
1416          * for driver's internal DCMDs.
1417          */
1418         instance->max_scsi_cmds = instance->max_fw_cmds -
1419                                 (MEGASAS_FUSION_INTERNAL_CMDS +
1420                                 MEGASAS_FUSION_IOCTL_CMDS);
1421         sema_init(&instance->ioctl_sem, MEGASAS_FUSION_IOCTL_CMDS);
1422
1423         /*
1424          * Allocate memory for descriptors
1425          * Create a pool of commands
1426          */
1427         if (megasas_alloc_cmds(instance))
1428                 goto fail_alloc_mfi_cmds;
1429         if (megasas_alloc_cmds_fusion(instance))
1430                 goto fail_alloc_cmds;
1431
1432         if (megasas_ioc_init_fusion(instance))
1433                 goto fail_ioc_init;
1434
1435         megasas_display_intel_branding(instance);
1436         if (megasas_get_ctrl_info(instance)) {
1437                 dev_err(&instance->pdev->dev,
1438                         "Could not get controller info. Fail from %s %d\n",
1439                         __func__, __LINE__);
1440                 goto fail_ioc_init;
1441         }
1442
1443         instance->flag_ieee = 1;
1444         instance->r1_ldio_hint_default =  MR_R1_LDIO_PIGGYBACK_DEFAULT;
1445         fusion->fast_path_io = 0;
1446
1447         if (megasas_allocate_raid_maps(instance))
1448                 goto fail_ioc_init;
1449
1450         if (!megasas_get_map_info(instance))
1451                 megasas_sync_map_info(instance);
1452
1453         return 0;
1454
1455 fail_ioc_init:
1456         megasas_free_cmds_fusion(instance);
1457 fail_alloc_cmds:
1458         megasas_free_cmds(instance);
1459 fail_alloc_mfi_cmds:
1460         return 1;
1461 }
1462
1463 /**
1464  * map_cmd_status -     Maps FW cmd status to OS cmd status
1465  * @cmd :               Pointer to cmd
1466  * @status :            status of cmd returned by FW
1467  * @ext_status :        ext status of cmd returned by FW
1468  */
1469
1470 void
1471 map_cmd_status(struct fusion_context *fusion,
1472                 struct scsi_cmnd *scmd, u8 status, u8 ext_status,
1473                 u32 data_length, u8 *sense)
1474 {
1475         u8 cmd_type;
1476         int resid;
1477
1478         cmd_type = megasas_cmd_type(scmd);
1479         switch (status) {
1480
1481         case MFI_STAT_OK:
1482                 scmd->result = DID_OK << 16;
1483                 break;
1484
1485         case MFI_STAT_SCSI_IO_FAILED:
1486         case MFI_STAT_LD_INIT_IN_PROGRESS:
1487                 scmd->result = (DID_ERROR << 16) | ext_status;
1488                 break;
1489
1490         case MFI_STAT_SCSI_DONE_WITH_ERROR:
1491
1492                 scmd->result = (DID_OK << 16) | ext_status;
1493                 if (ext_status == SAM_STAT_CHECK_CONDITION) {
1494                         memset(scmd->sense_buffer, 0,
1495                                SCSI_SENSE_BUFFERSIZE);
1496                         memcpy(scmd->sense_buffer, sense,
1497                                SCSI_SENSE_BUFFERSIZE);
1498                         scmd->result |= DRIVER_SENSE << 24;
1499                 }
1500
1501                 /*
1502                  * If the  IO request is partially completed, then MR FW will
1503                  * update "io_request->DataLength" field with actual number of
1504                  * bytes transferred.Driver will set residual bytes count in
1505                  * SCSI command structure.
1506                  */
1507                 resid = (scsi_bufflen(scmd) - data_length);
1508                 scsi_set_resid(scmd, resid);
1509
1510                 if (resid &&
1511                         ((cmd_type == READ_WRITE_LDIO) ||
1512                         (cmd_type == READ_WRITE_SYSPDIO)))
1513                         scmd_printk(KERN_INFO, scmd, "BRCM Debug mfi stat 0x%x, data len"
1514                                 " requested/completed 0x%x/0x%x\n",
1515                                 status, scsi_bufflen(scmd), data_length);
1516                 break;
1517
1518         case MFI_STAT_LD_OFFLINE:
1519         case MFI_STAT_DEVICE_NOT_FOUND:
1520                 scmd->result = DID_BAD_TARGET << 16;
1521                 break;
1522         case MFI_STAT_CONFIG_SEQ_MISMATCH:
1523                 scmd->result = DID_IMM_RETRY << 16;
1524                 break;
1525         default:
1526                 scmd->result = DID_ERROR << 16;
1527                 break;
1528         }
1529 }
1530
1531 /**
1532  * megasas_is_prp_possible -
1533  * Checks if native NVMe PRPs can be built for the IO
1534  *
1535  * @instance:           Adapter soft state
1536  * @scmd:               SCSI command from the mid-layer
1537  * @sge_count:          scatter gather element count.
1538  *
1539  * Returns:             true: PRPs can be built
1540  *                      false: IEEE SGLs needs to be built
1541  */
1542 static bool
1543 megasas_is_prp_possible(struct megasas_instance *instance,
1544                         struct scsi_cmnd *scmd, int sge_count)
1545 {
1546         struct fusion_context *fusion;
1547         int i;
1548         u32 data_length = 0;
1549         struct scatterlist *sg_scmd;
1550         bool build_prp = false;
1551         u32 mr_nvme_pg_size;
1552
1553         mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
1554                                 MR_DEFAULT_NVME_PAGE_SIZE);
1555         fusion = instance->ctrl_context;
1556         data_length = scsi_bufflen(scmd);
1557         sg_scmd = scsi_sglist(scmd);
1558
1559         /*
1560          * NVMe uses one PRP for each page (or part of a page)
1561          * look at the data length - if 4 pages or less then IEEE is OK
1562          * if  > 5 pages then we need to build a native SGL
1563          * if > 4 and <= 5 pages, then check physical address of 1st SG entry
1564          * if this first size in the page is >= the residual beyond 4 pages
1565          * then use IEEE, otherwise use native SGL
1566          */
1567
1568         if (data_length > (mr_nvme_pg_size * 5)) {
1569                 build_prp = true;
1570         } else if ((data_length > (mr_nvme_pg_size * 4)) &&
1571                         (data_length <= (mr_nvme_pg_size * 5)))  {
1572                 /* check if 1st SG entry size is < residual beyond 4 pages */
1573                 if (sg_dma_len(sg_scmd) < (data_length - (mr_nvme_pg_size * 4)))
1574                         build_prp = true;
1575         }
1576
1577 /*
1578  * Below code detects gaps/holes in IO data buffers.
1579  * What does holes/gaps mean?
1580  * Any SGE except first one in a SGL starts at non NVME page size
1581  * aligned address OR Any SGE except last one in a SGL ends at
1582  * non NVME page size boundary.
1583  *
1584  * Driver has already informed block layer by setting boundary rules for
1585  * bio merging done at NVME page size boundary calling kernel API
1586  * blk_queue_virt_boundary inside slave_config.
1587  * Still there is possibility of IO coming with holes to driver because of
1588  * IO merging done by IO scheduler.
1589  *
1590  * With SCSI BLK MQ enabled, there will be no IO with holes as there is no
1591  * IO scheduling so no IO merging.
1592  *
1593  * With SCSI BLK MQ disabled, IO scheduler may attempt to merge IOs and
1594  * then sending IOs with holes.
1595  *
1596  * Though driver can request block layer to disable IO merging by calling-
1597  * queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, sdev->request_queue) but
1598  * user may tune sysfs parameter- nomerges again to 0 or 1.
1599  *
1600  * If in future IO scheduling is enabled with SCSI BLK MQ,
1601  * this algorithm to detect holes will be required in driver
1602  * for SCSI BLK MQ enabled case as well.
1603  *
1604  *
1605  */
1606         scsi_for_each_sg(scmd, sg_scmd, sge_count, i) {
1607                 if ((i != 0) && (i != (sge_count - 1))) {
1608                         if (mega_mod64(sg_dma_len(sg_scmd), mr_nvme_pg_size) ||
1609                             mega_mod64(sg_dma_address(sg_scmd),
1610                                        mr_nvme_pg_size)) {
1611                                 build_prp = false;
1612                                 atomic_inc(&instance->sge_holes_type1);
1613                                 break;
1614                         }
1615                 }
1616
1617                 if ((sge_count > 1) && (i == 0)) {
1618                         if ((mega_mod64((sg_dma_address(sg_scmd) +
1619                                         sg_dma_len(sg_scmd)),
1620                                         mr_nvme_pg_size))) {
1621                                 build_prp = false;
1622                                 atomic_inc(&instance->sge_holes_type2);
1623                                 break;
1624                         }
1625                 }
1626
1627                 if ((sge_count > 1) && (i == (sge_count - 1))) {
1628                         if (mega_mod64(sg_dma_address(sg_scmd),
1629                                        mr_nvme_pg_size)) {
1630                                 build_prp = false;
1631                                 atomic_inc(&instance->sge_holes_type3);
1632                                 break;
1633                         }
1634                 }
1635         }
1636
1637         return build_prp;
1638 }
1639
1640 /**
1641  * megasas_make_prp_nvme -
1642  * Prepare PRPs(Physical Region Page)- SGLs specific to NVMe drives only
1643  *
1644  * @instance:           Adapter soft state
1645  * @scmd:               SCSI command from the mid-layer
1646  * @sgl_ptr:            SGL to be filled in
1647  * @cmd:                Fusion command frame
1648  * @sge_count:          scatter gather element count.
1649  *
1650  * Returns:             true: PRPs are built
1651  *                      false: IEEE SGLs needs to be built
1652  */
1653 static bool
1654 megasas_make_prp_nvme(struct megasas_instance *instance, struct scsi_cmnd *scmd,
1655                       struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr,
1656                       struct megasas_cmd_fusion *cmd, int sge_count)
1657 {
1658         int sge_len, offset, num_prp_in_chain = 0;
1659         struct MPI25_IEEE_SGE_CHAIN64 *main_chain_element, *ptr_first_sgl;
1660         u64 *ptr_sgl;
1661         dma_addr_t ptr_sgl_phys;
1662         u64 sge_addr;
1663         u32 page_mask, page_mask_result;
1664         struct scatterlist *sg_scmd;
1665         u32 first_prp_len;
1666         bool build_prp = false;
1667         int data_len = scsi_bufflen(scmd);
1668         struct fusion_context *fusion;
1669         u32 mr_nvme_pg_size = max_t(u32, instance->nvme_page_size,
1670                                         MR_DEFAULT_NVME_PAGE_SIZE);
1671
1672         fusion = instance->ctrl_context;
1673
1674         build_prp = megasas_is_prp_possible(instance, scmd, sge_count);
1675
1676         if (!build_prp)
1677                 return false;
1678
1679         /*
1680          * Nvme has a very convoluted prp format.  One prp is required
1681          * for each page or partial page. Driver need to split up OS sg_list
1682          * entries if it is longer than one page or cross a page
1683          * boundary.  Driver also have to insert a PRP list pointer entry as
1684          * the last entry in each physical page of the PRP list.
1685          *
1686          * NOTE: The first PRP "entry" is actually placed in the first
1687          * SGL entry in the main message as IEEE 64 format.  The 2nd
1688          * entry in the main message is the chain element, and the rest
1689          * of the PRP entries are built in the contiguous pcie buffer.
1690          */
1691         page_mask = mr_nvme_pg_size - 1;
1692         ptr_sgl = (u64 *)cmd->sg_frame;
1693         ptr_sgl_phys = cmd->sg_frame_phys_addr;
1694         memset(ptr_sgl, 0, instance->max_chain_frame_sz);
1695
1696         /* Build chain frame element which holds all prps except first*/
1697         main_chain_element = (struct MPI25_IEEE_SGE_CHAIN64 *)
1698             ((u8 *)sgl_ptr + sizeof(struct MPI25_IEEE_SGE_CHAIN64));
1699
1700         main_chain_element->Address = cpu_to_le64(ptr_sgl_phys);
1701         main_chain_element->NextChainOffset = 0;
1702         main_chain_element->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1703                                         IEEE_SGE_FLAGS_SYSTEM_ADDR |
1704                                         MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
1705
1706         /* Build first prp, sge need not to be page aligned*/
1707         ptr_first_sgl = sgl_ptr;
1708         sg_scmd = scsi_sglist(scmd);
1709         sge_addr = sg_dma_address(sg_scmd);
1710         sge_len = sg_dma_len(sg_scmd);
1711
1712         offset = (u32)(sge_addr & page_mask);
1713         first_prp_len = mr_nvme_pg_size - offset;
1714
1715         ptr_first_sgl->Address = cpu_to_le64(sge_addr);
1716         ptr_first_sgl->Length = cpu_to_le32(first_prp_len);
1717
1718         data_len -= first_prp_len;
1719
1720         if (sge_len > first_prp_len) {
1721                 sge_addr += first_prp_len;
1722                 sge_len -= first_prp_len;
1723         } else if (sge_len == first_prp_len) {
1724                 sg_scmd = sg_next(sg_scmd);
1725                 sge_addr = sg_dma_address(sg_scmd);
1726                 sge_len = sg_dma_len(sg_scmd);
1727         }
1728
1729         for (;;) {
1730                 offset = (u32)(sge_addr & page_mask);
1731
1732                 /* Put PRP pointer due to page boundary*/
1733                 page_mask_result = (uintptr_t)(ptr_sgl + 1) & page_mask;
1734                 if (unlikely(!page_mask_result)) {
1735                         scmd_printk(KERN_NOTICE,
1736                                     scmd, "page boundary ptr_sgl: 0x%p\n",
1737                                     ptr_sgl);
1738                         ptr_sgl_phys += 8;
1739                         *ptr_sgl = cpu_to_le64(ptr_sgl_phys);
1740                         ptr_sgl++;
1741                         num_prp_in_chain++;
1742                 }
1743
1744                 *ptr_sgl = cpu_to_le64(sge_addr);
1745                 ptr_sgl++;
1746                 ptr_sgl_phys += 8;
1747                 num_prp_in_chain++;
1748
1749                 sge_addr += mr_nvme_pg_size;
1750                 sge_len -= mr_nvme_pg_size;
1751                 data_len -= mr_nvme_pg_size;
1752
1753                 if (data_len <= 0)
1754                         break;
1755
1756                 if (sge_len > 0)
1757                         continue;
1758
1759                 sg_scmd = sg_next(sg_scmd);
1760                 sge_addr = sg_dma_address(sg_scmd);
1761                 sge_len = sg_dma_len(sg_scmd);
1762         }
1763
1764         main_chain_element->Length =
1765                         cpu_to_le32(num_prp_in_chain * sizeof(u64));
1766
1767         atomic_inc(&instance->prp_sgl);
1768         return build_prp;
1769 }
1770
1771 /**
1772  * megasas_make_sgl_fusion -    Prepares 32-bit SGL
1773  * @instance:           Adapter soft state
1774  * @scp:                SCSI command from the mid-layer
1775  * @sgl_ptr:            SGL to be filled in
1776  * @cmd:                cmd we are working on
1777  * @sge_count           sge count
1778  *
1779  */
1780 static void
1781 megasas_make_sgl_fusion(struct megasas_instance *instance,
1782                         struct scsi_cmnd *scp,
1783                         struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr,
1784                         struct megasas_cmd_fusion *cmd, int sge_count)
1785 {
1786         int i, sg_processed;
1787         struct scatterlist *os_sgl;
1788         struct fusion_context *fusion;
1789
1790         fusion = instance->ctrl_context;
1791
1792         if (instance->adapter_type >= INVADER_SERIES) {
1793                 struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr_end = sgl_ptr;
1794                 sgl_ptr_end += fusion->max_sge_in_main_msg - 1;
1795                 sgl_ptr_end->Flags = 0;
1796         }
1797
1798         scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1799                 sgl_ptr->Length = cpu_to_le32(sg_dma_len(os_sgl));
1800                 sgl_ptr->Address = cpu_to_le64(sg_dma_address(os_sgl));
1801                 sgl_ptr->Flags = 0;
1802                 if (instance->adapter_type >= INVADER_SERIES)
1803                         if (i == sge_count - 1)
1804                                 sgl_ptr->Flags = IEEE_SGE_FLAGS_END_OF_LIST;
1805                 sgl_ptr++;
1806                 sg_processed = i + 1;
1807
1808                 if ((sg_processed ==  (fusion->max_sge_in_main_msg - 1)) &&
1809                     (sge_count > fusion->max_sge_in_main_msg)) {
1810
1811                         struct MPI25_IEEE_SGE_CHAIN64 *sg_chain;
1812                         if (instance->adapter_type >= INVADER_SERIES) {
1813                                 if ((le16_to_cpu(cmd->io_request->IoFlags) &
1814                                         MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) !=
1815                                         MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1816                                         cmd->io_request->ChainOffset =
1817                                                 fusion->
1818                                                 chain_offset_io_request;
1819                                 else
1820                                         cmd->io_request->ChainOffset = 0;
1821                         } else
1822                                 cmd->io_request->ChainOffset =
1823                                         fusion->chain_offset_io_request;
1824
1825                         sg_chain = sgl_ptr;
1826                         /* Prepare chain element */
1827                         sg_chain->NextChainOffset = 0;
1828                         if (instance->adapter_type >= INVADER_SERIES)
1829                                 sg_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT;
1830                         else
1831                                 sg_chain->Flags =
1832                                         (IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1833                                          MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
1834                         sg_chain->Length =  cpu_to_le32((sizeof(union MPI2_SGE_IO_UNION) * (sge_count - sg_processed)));
1835                         sg_chain->Address = cpu_to_le64(cmd->sg_frame_phys_addr);
1836
1837                         sgl_ptr =
1838                           (struct MPI25_IEEE_SGE_CHAIN64 *)cmd->sg_frame;
1839                         memset(sgl_ptr, 0, instance->max_chain_frame_sz);
1840                 }
1841         }
1842         atomic_inc(&instance->ieee_sgl);
1843 }
1844
1845 /**
1846  * megasas_make_sgl -   Build Scatter Gather List(SGLs)
1847  * @scp:                SCSI command pointer
1848  * @instance:           Soft instance of controller
1849  * @cmd:                Fusion command pointer
1850  *
1851  * This function will build sgls based on device type.
1852  * For nvme drives, there is different way of building sgls in nvme native
1853  * format- PRPs(Physical Region Page).
1854  *
1855  * Returns the number of sg lists actually used, zero if the sg lists
1856  * is NULL, or -ENOMEM if the mapping failed
1857  */
1858 static
1859 int megasas_make_sgl(struct megasas_instance *instance, struct scsi_cmnd *scp,
1860                      struct megasas_cmd_fusion *cmd)
1861 {
1862         int sge_count;
1863         bool build_prp = false;
1864         struct MPI25_IEEE_SGE_CHAIN64 *sgl_chain64;
1865
1866         sge_count = scsi_dma_map(scp);
1867
1868         if ((sge_count > instance->max_num_sge) || (sge_count <= 0))
1869                 return sge_count;
1870
1871         sgl_chain64 = (struct MPI25_IEEE_SGE_CHAIN64 *)&cmd->io_request->SGL;
1872         if ((le16_to_cpu(cmd->io_request->IoFlags) &
1873             MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) &&
1874             (cmd->pd_interface == NVME_PD))
1875                 build_prp = megasas_make_prp_nvme(instance, scp, sgl_chain64,
1876                                                   cmd, sge_count);
1877
1878         if (!build_prp)
1879                 megasas_make_sgl_fusion(instance, scp, sgl_chain64,
1880                                         cmd, sge_count);
1881
1882         return sge_count;
1883 }
1884
1885 /**
1886  * megasas_set_pd_lba - Sets PD LBA
1887  * @cdb:                CDB
1888  * @cdb_len:            cdb length
1889  * @start_blk:          Start block of IO
1890  *
1891  * Used to set the PD LBA in CDB for FP IOs
1892  */
1893 void
1894 megasas_set_pd_lba(struct MPI2_RAID_SCSI_IO_REQUEST *io_request, u8 cdb_len,
1895                    struct IO_REQUEST_INFO *io_info, struct scsi_cmnd *scp,
1896                    struct MR_DRV_RAID_MAP_ALL *local_map_ptr, u32 ref_tag)
1897 {
1898         struct MR_LD_RAID *raid;
1899         u16 ld;
1900         u64 start_blk = io_info->pdBlock;
1901         u8 *cdb = io_request->CDB.CDB32;
1902         u32 num_blocks = io_info->numBlocks;
1903         u8 opcode = 0, flagvals = 0, groupnum = 0, control = 0;
1904
1905         /* Check if T10 PI (DIF) is enabled for this LD */
1906         ld = MR_TargetIdToLdGet(io_info->ldTgtId, local_map_ptr);
1907         raid = MR_LdRaidGet(ld, local_map_ptr);
1908         if (raid->capability.ldPiMode == MR_PROT_INFO_TYPE_CONTROLLER) {
1909                 memset(cdb, 0, sizeof(io_request->CDB.CDB32));
1910                 cdb[0] =  MEGASAS_SCSI_VARIABLE_LENGTH_CMD;
1911                 cdb[7] =  MEGASAS_SCSI_ADDL_CDB_LEN;
1912
1913                 if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1914                         cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_READ32;
1915                 else
1916                         cdb[9] = MEGASAS_SCSI_SERVICE_ACTION_WRITE32;
1917                 cdb[10] = MEGASAS_RD_WR_PROTECT_CHECK_ALL;
1918
1919                 /* LBA */
1920                 cdb[12] = (u8)((start_blk >> 56) & 0xff);
1921                 cdb[13] = (u8)((start_blk >> 48) & 0xff);
1922                 cdb[14] = (u8)((start_blk >> 40) & 0xff);
1923                 cdb[15] = (u8)((start_blk >> 32) & 0xff);
1924                 cdb[16] = (u8)((start_blk >> 24) & 0xff);
1925                 cdb[17] = (u8)((start_blk >> 16) & 0xff);
1926                 cdb[18] = (u8)((start_blk >> 8) & 0xff);
1927                 cdb[19] = (u8)(start_blk & 0xff);
1928
1929                 /* Logical block reference tag */
1930                 io_request->CDB.EEDP32.PrimaryReferenceTag =
1931                         cpu_to_be32(ref_tag);
1932                 io_request->CDB.EEDP32.PrimaryApplicationTagMask = cpu_to_be16(0xffff);
1933                 io_request->IoFlags = cpu_to_le16(32); /* Specify 32-byte cdb */
1934
1935                 /* Transfer length */
1936                 cdb[28] = (u8)((num_blocks >> 24) & 0xff);
1937                 cdb[29] = (u8)((num_blocks >> 16) & 0xff);
1938                 cdb[30] = (u8)((num_blocks >> 8) & 0xff);
1939                 cdb[31] = (u8)(num_blocks & 0xff);
1940
1941                 /* set SCSI IO EEDPFlags */
1942                 if (scp->sc_data_direction == PCI_DMA_FROMDEVICE) {
1943                         io_request->EEDPFlags = cpu_to_le16(
1944                                 MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG  |
1945                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_REFTAG |
1946                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_REMOVE_OP |
1947                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_APPTAG |
1948                                 MPI25_SCSIIO_EEDPFLAGS_DO_NOT_DISABLE_MODE |
1949                                 MPI2_SCSIIO_EEDPFLAGS_CHECK_GUARD);
1950                 } else {
1951                         io_request->EEDPFlags = cpu_to_le16(
1952                                 MPI2_SCSIIO_EEDPFLAGS_INC_PRI_REFTAG |
1953                                 MPI2_SCSIIO_EEDPFLAGS_INSERT_OP);
1954                 }
1955                 io_request->Control |= cpu_to_le32((0x4 << 26));
1956                 io_request->EEDPBlockSize = cpu_to_le32(scp->device->sector_size);
1957         } else {
1958                 /* Some drives don't support 16/12 byte CDB's, convert to 10 */
1959                 if (((cdb_len == 12) || (cdb_len == 16)) &&
1960                     (start_blk <= 0xffffffff)) {
1961                         if (cdb_len == 16) {
1962                                 opcode = cdb[0] == READ_16 ? READ_10 : WRITE_10;
1963                                 flagvals = cdb[1];
1964                                 groupnum = cdb[14];
1965                                 control = cdb[15];
1966                         } else {
1967                                 opcode = cdb[0] == READ_12 ? READ_10 : WRITE_10;
1968                                 flagvals = cdb[1];
1969                                 groupnum = cdb[10];
1970                                 control = cdb[11];
1971                         }
1972
1973                         memset(cdb, 0, sizeof(io_request->CDB.CDB32));
1974
1975                         cdb[0] = opcode;
1976                         cdb[1] = flagvals;
1977                         cdb[6] = groupnum;
1978                         cdb[9] = control;
1979
1980                         /* Transfer length */
1981                         cdb[8] = (u8)(num_blocks & 0xff);
1982                         cdb[7] = (u8)((num_blocks >> 8) & 0xff);
1983
1984                         io_request->IoFlags = cpu_to_le16(10); /* Specify 10-byte cdb */
1985                         cdb_len = 10;
1986                 } else if ((cdb_len < 16) && (start_blk > 0xffffffff)) {
1987                         /* Convert to 16 byte CDB for large LBA's */
1988                         switch (cdb_len) {
1989                         case 6:
1990                                 opcode = cdb[0] == READ_6 ? READ_16 : WRITE_16;
1991                                 control = cdb[5];
1992                                 break;
1993                         case 10:
1994                                 opcode =
1995                                         cdb[0] == READ_10 ? READ_16 : WRITE_16;
1996                                 flagvals = cdb[1];
1997                                 groupnum = cdb[6];
1998                                 control = cdb[9];
1999                                 break;
2000                         case 12:
2001                                 opcode =
2002                                         cdb[0] == READ_12 ? READ_16 : WRITE_16;
2003                                 flagvals = cdb[1];
2004                                 groupnum = cdb[10];
2005                                 control = cdb[11];
2006                                 break;
2007                         }
2008
2009                         memset(cdb, 0, sizeof(io_request->CDB.CDB32));
2010
2011                         cdb[0] = opcode;
2012                         cdb[1] = flagvals;
2013                         cdb[14] = groupnum;
2014                         cdb[15] = control;
2015
2016                         /* Transfer length */
2017                         cdb[13] = (u8)(num_blocks & 0xff);
2018                         cdb[12] = (u8)((num_blocks >> 8) & 0xff);
2019                         cdb[11] = (u8)((num_blocks >> 16) & 0xff);
2020                         cdb[10] = (u8)((num_blocks >> 24) & 0xff);
2021
2022                         io_request->IoFlags = cpu_to_le16(16); /* Specify 16-byte cdb */
2023                         cdb_len = 16;
2024                 }
2025
2026                 /* Normal case, just load LBA here */
2027                 switch (cdb_len) {
2028                 case 6:
2029                 {
2030                         u8 val = cdb[1] & 0xE0;
2031                         cdb[3] = (u8)(start_blk & 0xff);
2032                         cdb[2] = (u8)((start_blk >> 8) & 0xff);
2033                         cdb[1] = val | ((u8)(start_blk >> 16) & 0x1f);
2034                         break;
2035                 }
2036                 case 10:
2037                         cdb[5] = (u8)(start_blk & 0xff);
2038                         cdb[4] = (u8)((start_blk >> 8) & 0xff);
2039                         cdb[3] = (u8)((start_blk >> 16) & 0xff);
2040                         cdb[2] = (u8)((start_blk >> 24) & 0xff);
2041                         break;
2042                 case 12:
2043                         cdb[5]    = (u8)(start_blk & 0xff);
2044                         cdb[4]    = (u8)((start_blk >> 8) & 0xff);
2045                         cdb[3]    = (u8)((start_blk >> 16) & 0xff);
2046                         cdb[2]    = (u8)((start_blk >> 24) & 0xff);
2047                         break;
2048                 case 16:
2049                         cdb[9]    = (u8)(start_blk & 0xff);
2050                         cdb[8]    = (u8)((start_blk >> 8) & 0xff);
2051                         cdb[7]    = (u8)((start_blk >> 16) & 0xff);
2052                         cdb[6]    = (u8)((start_blk >> 24) & 0xff);
2053                         cdb[5]    = (u8)((start_blk >> 32) & 0xff);
2054                         cdb[4]    = (u8)((start_blk >> 40) & 0xff);
2055                         cdb[3]    = (u8)((start_blk >> 48) & 0xff);
2056                         cdb[2]    = (u8)((start_blk >> 56) & 0xff);
2057                         break;
2058                 }
2059         }
2060 }
2061
2062 /**
2063  * megasas_stream_detect -      stream detection on read and and write IOs
2064  * @instance:           Adapter soft state
2065  * @cmd:                    Command to be prepared
2066  * @io_info:            IO Request info
2067  *
2068  */
2069
2070 /** stream detection on read and and write IOs */
2071 static void megasas_stream_detect(struct megasas_instance *instance,
2072                                   struct megasas_cmd_fusion *cmd,
2073                                   struct IO_REQUEST_INFO *io_info)
2074 {
2075         struct fusion_context *fusion = instance->ctrl_context;
2076         u32 device_id = io_info->ldTgtId;
2077         struct LD_STREAM_DETECT *current_ld_sd
2078                 = fusion->stream_detect_by_ld[device_id];
2079         u32 *track_stream = &current_ld_sd->mru_bit_map, stream_num;
2080         u32 shifted_values, unshifted_values;
2081         u32 index_value_mask, shifted_values_mask;
2082         int i;
2083         bool is_read_ahead = false;
2084         struct STREAM_DETECT *current_sd;
2085         /* find possible stream */
2086         for (i = 0; i < MAX_STREAMS_TRACKED; ++i) {
2087                 stream_num = (*track_stream >>
2088                         (i * BITS_PER_INDEX_STREAM)) &
2089                         STREAM_MASK;
2090                 current_sd = &current_ld_sd->stream_track[stream_num];
2091                 /* if we found a stream, update the raid
2092                  *  context and also update the mruBitMap
2093                  */
2094                 /*      boundary condition */
2095                 if ((current_sd->next_seq_lba) &&
2096                     (io_info->ldStartBlock >= current_sd->next_seq_lba) &&
2097                     (io_info->ldStartBlock <= (current_sd->next_seq_lba + 32)) &&
2098                     (current_sd->is_read == io_info->isRead)) {
2099
2100                         if ((io_info->ldStartBlock != current_sd->next_seq_lba) &&
2101                             ((!io_info->isRead) || (!is_read_ahead)))
2102                                 /*
2103                                  * Once the API availible we need to change this.
2104                                  * At this point we are not allowing any gap
2105                                  */
2106                                 continue;
2107
2108                         SET_STREAM_DETECTED(cmd->io_request->RaidContext.raid_context_g35);
2109                         current_sd->next_seq_lba =
2110                         io_info->ldStartBlock + io_info->numBlocks;
2111                         /*
2112                          *      update the mruBitMap LRU
2113                          */
2114                         shifted_values_mask =
2115                                 (1 <<  i * BITS_PER_INDEX_STREAM) - 1;
2116                         shifted_values = ((*track_stream & shifted_values_mask)
2117                                                 << BITS_PER_INDEX_STREAM);
2118                         index_value_mask =
2119                                 STREAM_MASK << i * BITS_PER_INDEX_STREAM;
2120                         unshifted_values =
2121                                 *track_stream & ~(shifted_values_mask |
2122                                 index_value_mask);
2123                         *track_stream =
2124                                 unshifted_values | shifted_values | stream_num;
2125                         return;
2126                 }
2127         }
2128         /*
2129          * if we did not find any stream, create a new one
2130          * from the least recently used
2131          */
2132         stream_num = (*track_stream >>
2133                 ((MAX_STREAMS_TRACKED - 1) * BITS_PER_INDEX_STREAM)) &
2134                 STREAM_MASK;
2135         current_sd = &current_ld_sd->stream_track[stream_num];
2136         current_sd->is_read = io_info->isRead;
2137         current_sd->next_seq_lba = io_info->ldStartBlock + io_info->numBlocks;
2138         *track_stream = (((*track_stream & ZERO_LAST_STREAM) << 4) | stream_num);
2139         return;
2140 }
2141
2142 /**
2143  * megasas_set_raidflag_cpu_affinity - This function sets the cpu
2144  * affinity (cpu of the controller) and raid_flags in the raid context
2145  * based on IO type.
2146  *
2147  * @praid_context:      IO RAID context
2148  * @raid:               LD raid map
2149  * @fp_possible:        Is fast path possible?
2150  * @is_read:            Is read IO?
2151  *
2152  */
2153 static void
2154 megasas_set_raidflag_cpu_affinity(union RAID_CONTEXT_UNION *praid_context,
2155                                   struct MR_LD_RAID *raid, bool fp_possible,
2156                                   u8 is_read, u32 scsi_buff_len)
2157 {
2158         u8 cpu_sel = MR_RAID_CTX_CPUSEL_0;
2159         struct RAID_CONTEXT_G35 *rctx_g35;
2160
2161         rctx_g35 = &praid_context->raid_context_g35;
2162         if (fp_possible) {
2163                 if (is_read) {
2164                         if ((raid->cpuAffinity.pdRead.cpu0) &&
2165                             (raid->cpuAffinity.pdRead.cpu1))
2166                                 cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2167                         else if (raid->cpuAffinity.pdRead.cpu1)
2168                                 cpu_sel = MR_RAID_CTX_CPUSEL_1;
2169                 } else {
2170                         if ((raid->cpuAffinity.pdWrite.cpu0) &&
2171                             (raid->cpuAffinity.pdWrite.cpu1))
2172                                 cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2173                         else if (raid->cpuAffinity.pdWrite.cpu1)
2174                                 cpu_sel = MR_RAID_CTX_CPUSEL_1;
2175                         /* Fast path cache by pass capable R0/R1 VD */
2176                         if ((raid->level <= 1) &&
2177                             (raid->capability.fp_cache_bypass_capable)) {
2178                                 rctx_g35->routing_flags |=
2179                                         (1 << MR_RAID_CTX_ROUTINGFLAGS_SLD_SHIFT);
2180                                 rctx_g35->raid_flags =
2181                                         (MR_RAID_FLAGS_IO_SUB_TYPE_CACHE_BYPASS
2182                                         << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT);
2183                         }
2184                 }
2185         } else {
2186                 if (is_read) {
2187                         if ((raid->cpuAffinity.ldRead.cpu0) &&
2188                             (raid->cpuAffinity.ldRead.cpu1))
2189                                 cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2190                         else if (raid->cpuAffinity.ldRead.cpu1)
2191                                 cpu_sel = MR_RAID_CTX_CPUSEL_1;
2192                 } else {
2193                         if ((raid->cpuAffinity.ldWrite.cpu0) &&
2194                             (raid->cpuAffinity.ldWrite.cpu1))
2195                                 cpu_sel = MR_RAID_CTX_CPUSEL_FCFS;
2196                         else if (raid->cpuAffinity.ldWrite.cpu1)
2197                                 cpu_sel = MR_RAID_CTX_CPUSEL_1;
2198
2199                         if (is_stream_detected(rctx_g35) &&
2200                             ((raid->level == 5) || (raid->level == 6)) &&
2201                             (raid->writeMode == MR_RL_WRITE_THROUGH_MODE) &&
2202                             (cpu_sel == MR_RAID_CTX_CPUSEL_FCFS))
2203                                 cpu_sel = MR_RAID_CTX_CPUSEL_0;
2204                 }
2205         }
2206
2207         rctx_g35->routing_flags |=
2208                 (cpu_sel << MR_RAID_CTX_ROUTINGFLAGS_CPUSEL_SHIFT);
2209
2210         /* Always give priority to MR_RAID_FLAGS_IO_SUB_TYPE_LDIO_BW_LIMIT
2211          * vs MR_RAID_FLAGS_IO_SUB_TYPE_CACHE_BYPASS.
2212          * IO Subtype is not bitmap.
2213          */
2214         if ((raid->level == 1) && (!is_read)) {
2215                 if (scsi_buff_len > MR_LARGE_IO_MIN_SIZE)
2216                         praid_context->raid_context_g35.raid_flags =
2217                                 (MR_RAID_FLAGS_IO_SUB_TYPE_LDIO_BW_LIMIT
2218                                 << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT);
2219         }
2220 }
2221
2222 /**
2223  * megasas_build_ldio_fusion -  Prepares IOs to devices
2224  * @instance:           Adapter soft state
2225  * @scp:                SCSI command
2226  * @cmd:                Command to be prepared
2227  *
2228  * Prepares the io_request and chain elements (sg_frame) for IO
2229  * The IO can be for PD (Fast Path) or LD
2230  */
2231 void
2232 megasas_build_ldio_fusion(struct megasas_instance *instance,
2233                           struct scsi_cmnd *scp,
2234                           struct megasas_cmd_fusion *cmd)
2235 {
2236         bool fp_possible;
2237         u16 ld;
2238         u32 start_lba_lo, start_lba_hi, device_id, datalength = 0;
2239         u32 scsi_buff_len;
2240         struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
2241         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2242         struct IO_REQUEST_INFO io_info;
2243         struct fusion_context *fusion;
2244         struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
2245         u8 *raidLUN;
2246         unsigned long spinlock_flags;
2247         union RAID_CONTEXT_UNION *praid_context;
2248         struct MR_LD_RAID *raid = NULL;
2249         struct MR_PRIV_DEVICE *mrdev_priv;
2250
2251         device_id = MEGASAS_DEV_INDEX(scp);
2252
2253         fusion = instance->ctrl_context;
2254
2255         io_request = cmd->io_request;
2256         io_request->RaidContext.raid_context.virtual_disk_tgt_id =
2257                 cpu_to_le16(device_id);
2258         io_request->RaidContext.raid_context.status = 0;
2259         io_request->RaidContext.raid_context.ex_status = 0;
2260
2261         req_desc = (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)cmd->request_desc;
2262
2263         start_lba_lo = 0;
2264         start_lba_hi = 0;
2265         fp_possible = false;
2266
2267         /*
2268          * 6-byte READ(0x08) or WRITE(0x0A) cdb
2269          */
2270         if (scp->cmd_len == 6) {
2271                 datalength = (u32) scp->cmnd[4];
2272                 start_lba_lo = ((u32) scp->cmnd[1] << 16) |
2273                         ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
2274
2275                 start_lba_lo &= 0x1FFFFF;
2276         }
2277
2278         /*
2279          * 10-byte READ(0x28) or WRITE(0x2A) cdb
2280          */
2281         else if (scp->cmd_len == 10) {
2282                 datalength = (u32) scp->cmnd[8] |
2283                         ((u32) scp->cmnd[7] << 8);
2284                 start_lba_lo = ((u32) scp->cmnd[2] << 24) |
2285                         ((u32) scp->cmnd[3] << 16) |
2286                         ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
2287         }
2288
2289         /*
2290          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
2291          */
2292         else if (scp->cmd_len == 12) {
2293                 datalength = ((u32) scp->cmnd[6] << 24) |
2294                         ((u32) scp->cmnd[7] << 16) |
2295                         ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
2296                 start_lba_lo = ((u32) scp->cmnd[2] << 24) |
2297                         ((u32) scp->cmnd[3] << 16) |
2298                         ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
2299         }
2300
2301         /*
2302          * 16-byte READ(0x88) or WRITE(0x8A) cdb
2303          */
2304         else if (scp->cmd_len == 16) {
2305                 datalength = ((u32) scp->cmnd[10] << 24) |
2306                         ((u32) scp->cmnd[11] << 16) |
2307                         ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
2308                 start_lba_lo = ((u32) scp->cmnd[6] << 24) |
2309                         ((u32) scp->cmnd[7] << 16) |
2310                         ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
2311
2312                 start_lba_hi = ((u32) scp->cmnd[2] << 24) |
2313                         ((u32) scp->cmnd[3] << 16) |
2314                         ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
2315         }
2316
2317         memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
2318         io_info.ldStartBlock = ((u64)start_lba_hi << 32) | start_lba_lo;
2319         io_info.numBlocks = datalength;
2320         io_info.ldTgtId = device_id;
2321         io_info.r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
2322         scsi_buff_len = scsi_bufflen(scp);
2323         io_request->DataLength = cpu_to_le32(scsi_buff_len);
2324
2325         if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
2326                 io_info.isRead = 1;
2327
2328         local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
2329         ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
2330
2331         if (ld < instance->fw_supported_vd_count)
2332                 raid = MR_LdRaidGet(ld, local_map_ptr);
2333
2334         if (!raid || (!fusion->fast_path_io)) {
2335                 io_request->RaidContext.raid_context.reg_lock_flags  = 0;
2336                 fp_possible = false;
2337         } else {
2338                 if (MR_BuildRaidContext(instance, &io_info,
2339                                         &io_request->RaidContext.raid_context,
2340                                         local_map_ptr, &raidLUN))
2341                         fp_possible = (io_info.fpOkForIo > 0) ? true : false;
2342         }
2343
2344         cmd->request_desc->SCSIIO.MSIxIndex =
2345                 instance->reply_map[raw_smp_processor_id()];
2346
2347         praid_context = &io_request->RaidContext;
2348
2349         if (instance->adapter_type == VENTURA_SERIES) {
2350                 spin_lock_irqsave(&instance->stream_lock, spinlock_flags);
2351                 megasas_stream_detect(instance, cmd, &io_info);
2352                 spin_unlock_irqrestore(&instance->stream_lock, spinlock_flags);
2353                 /* In ventura if stream detected for a read and it is read ahead
2354                  *  capable make this IO as LDIO
2355                  */
2356                 if (is_stream_detected(&io_request->RaidContext.raid_context_g35) &&
2357                     io_info.isRead && io_info.ra_capable)
2358                         fp_possible = false;
2359
2360                 /* FP for Optimal raid level 1.
2361                  * All large RAID-1 writes (> 32 KiB, both WT and WB modes)
2362                  * are built by the driver as LD I/Os.
2363                  * All small RAID-1 WT writes (<= 32 KiB) are built as FP I/Os
2364                  * (there is never a reason to process these as buffered writes)
2365                  * All small RAID-1 WB writes (<= 32 KiB) are built as FP I/Os
2366                  * with the SLD bit asserted.
2367                  */
2368                 if (io_info.r1_alt_dev_handle != MR_DEVHANDLE_INVALID) {
2369                         mrdev_priv = scp->device->hostdata;
2370
2371                         if (atomic_inc_return(&instance->fw_outstanding) >
2372                                 (instance->host->can_queue)) {
2373                                 fp_possible = false;
2374                                 atomic_dec(&instance->fw_outstanding);
2375                         } else if ((scsi_buff_len > MR_LARGE_IO_MIN_SIZE) ||
2376                                    (atomic_dec_if_positive(&mrdev_priv->r1_ldio_hint) > 0)) {
2377                                 fp_possible = false;
2378                                 atomic_dec(&instance->fw_outstanding);
2379                                 if (scsi_buff_len > MR_LARGE_IO_MIN_SIZE)
2380                                         atomic_set(&mrdev_priv->r1_ldio_hint,
2381                                                    instance->r1_ldio_hint_default);
2382                         }
2383                 }
2384
2385                 /* If raid is NULL, set CPU affinity to default CPU0 */
2386                 if (raid)
2387                         megasas_set_raidflag_cpu_affinity(praid_context,
2388                                 raid, fp_possible, io_info.isRead,
2389                                 scsi_buff_len);
2390                 else
2391                         praid_context->raid_context_g35.routing_flags |=
2392                                 (MR_RAID_CTX_CPUSEL_0 << MR_RAID_CTX_ROUTINGFLAGS_CPUSEL_SHIFT);
2393         }
2394
2395         if (fp_possible) {
2396                 megasas_set_pd_lba(io_request, scp->cmd_len, &io_info, scp,
2397                                    local_map_ptr, start_lba_lo);
2398                 io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
2399                 cmd->request_desc->SCSIIO.RequestFlags =
2400                         (MPI2_REQ_DESCRIPT_FLAGS_FP_IO
2401                          << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2402                 if (instance->adapter_type == INVADER_SERIES) {
2403                         if (io_request->RaidContext.raid_context.reg_lock_flags ==
2404                             REGION_TYPE_UNUSED)
2405                                 cmd->request_desc->SCSIIO.RequestFlags =
2406                                         (MEGASAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
2407                                         MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2408                         io_request->RaidContext.raid_context.type
2409                                 = MPI2_TYPE_CUDA;
2410                         io_request->RaidContext.raid_context.nseg = 0x1;
2411                         io_request->IoFlags |= cpu_to_le16(MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH);
2412                         io_request->RaidContext.raid_context.reg_lock_flags |=
2413                           (MR_RL_FLAGS_GRANT_DESTINATION_CUDA |
2414                            MR_RL_FLAGS_SEQ_NUM_ENABLE);
2415                 } else if (instance->adapter_type == VENTURA_SERIES) {
2416                         io_request->RaidContext.raid_context_g35.nseg_type |=
2417                                                 (1 << RAID_CONTEXT_NSEG_SHIFT);
2418                         io_request->RaidContext.raid_context_g35.nseg_type |=
2419                                                 (MPI2_TYPE_CUDA << RAID_CONTEXT_TYPE_SHIFT);
2420                         io_request->RaidContext.raid_context_g35.routing_flags |=
2421                                                 (1 << MR_RAID_CTX_ROUTINGFLAGS_SQN_SHIFT);
2422                         io_request->IoFlags |=
2423                                 cpu_to_le16(MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH);
2424                 }
2425                 if (fusion->load_balance_info &&
2426                         (fusion->load_balance_info[device_id].loadBalanceFlag) &&
2427                         (io_info.isRead)) {
2428                         io_info.devHandle =
2429                                 get_updated_dev_handle(instance,
2430                                         &fusion->load_balance_info[device_id],
2431                                         &io_info, local_map_ptr);
2432                         scp->SCp.Status |= MEGASAS_LOAD_BALANCE_FLAG;
2433                         cmd->pd_r1_lb = io_info.pd_after_lb;
2434                         if (instance->adapter_type == VENTURA_SERIES)
2435                                 io_request->RaidContext.raid_context_g35.span_arm
2436                                         = io_info.span_arm;
2437                         else
2438                                 io_request->RaidContext.raid_context.span_arm
2439                                         = io_info.span_arm;
2440
2441                 } else
2442                         scp->SCp.Status &= ~MEGASAS_LOAD_BALANCE_FLAG;
2443
2444                 if (instance->adapter_type == VENTURA_SERIES)
2445                         cmd->r1_alt_dev_handle = io_info.r1_alt_dev_handle;
2446                 else
2447                         cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
2448
2449                 if ((raidLUN[0] == 1) &&
2450                         (local_map_ptr->raidMap.devHndlInfo[io_info.pd_after_lb].validHandles > 1)) {
2451                         instance->dev_handle = !(instance->dev_handle);
2452                         io_info.devHandle =
2453                                 local_map_ptr->raidMap.devHndlInfo[io_info.pd_after_lb].devHandle[instance->dev_handle];
2454                 }
2455
2456                 cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
2457                 io_request->DevHandle = io_info.devHandle;
2458                 cmd->pd_interface = io_info.pd_interface;
2459                 /* populate the LUN field */
2460                 memcpy(io_request->LUN, raidLUN, 8);
2461         } else {
2462                 io_request->RaidContext.raid_context.timeout_value =
2463                         cpu_to_le16(local_map_ptr->raidMap.fpPdIoTimeoutSec);
2464                 cmd->request_desc->SCSIIO.RequestFlags =
2465                         (MEGASAS_REQ_DESCRIPT_FLAGS_LD_IO
2466                          << MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2467                 if (instance->adapter_type == INVADER_SERIES) {
2468                         if (io_info.do_fp_rlbypass ||
2469                         (io_request->RaidContext.raid_context.reg_lock_flags
2470                                         == REGION_TYPE_UNUSED))
2471                                 cmd->request_desc->SCSIIO.RequestFlags =
2472                                         (MEGASAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
2473                                         MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2474                         io_request->RaidContext.raid_context.type
2475                                 = MPI2_TYPE_CUDA;
2476                         io_request->RaidContext.raid_context.reg_lock_flags |=
2477                                 (MR_RL_FLAGS_GRANT_DESTINATION_CPU0 |
2478                                  MR_RL_FLAGS_SEQ_NUM_ENABLE);
2479                         io_request->RaidContext.raid_context.nseg = 0x1;
2480                 } else if (instance->adapter_type == VENTURA_SERIES) {
2481                         io_request->RaidContext.raid_context_g35.routing_flags |=
2482                                         (1 << MR_RAID_CTX_ROUTINGFLAGS_SQN_SHIFT);
2483                         io_request->RaidContext.raid_context_g35.nseg_type |=
2484                                         (1 << RAID_CONTEXT_NSEG_SHIFT);
2485                         io_request->RaidContext.raid_context_g35.nseg_type |=
2486                                         (MPI2_TYPE_CUDA << RAID_CONTEXT_TYPE_SHIFT);
2487                 }
2488                 io_request->Function = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
2489                 io_request->DevHandle = cpu_to_le16(device_id);
2490
2491         } /* Not FP */
2492 }
2493
2494 /**
2495  * megasas_build_ld_nonrw_fusion - prepares non rw ios for virtual disk
2496  * @instance:           Adapter soft state
2497  * @scp:                SCSI command
2498  * @cmd:                Command to be prepared
2499  *
2500  * Prepares the io_request frame for non-rw io cmds for vd.
2501  */
2502 static void megasas_build_ld_nonrw_fusion(struct megasas_instance *instance,
2503                           struct scsi_cmnd *scmd, struct megasas_cmd_fusion *cmd)
2504 {
2505         u32 device_id;
2506         struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
2507         u16 ld;
2508         struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
2509         struct fusion_context *fusion = instance->ctrl_context;
2510         u8                          span, physArm;
2511         __le16                      devHandle;
2512         u32                         arRef, pd;
2513         struct MR_LD_RAID                  *raid;
2514         struct RAID_CONTEXT                *pRAID_Context;
2515         u8 fp_possible = 1;
2516
2517         io_request = cmd->io_request;
2518         device_id = MEGASAS_DEV_INDEX(scmd);
2519         local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
2520         io_request->DataLength = cpu_to_le32(scsi_bufflen(scmd));
2521         /* get RAID_Context pointer */
2522         pRAID_Context = &io_request->RaidContext.raid_context;
2523         /* Check with FW team */
2524         pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
2525         pRAID_Context->reg_lock_row_lba    = 0;
2526         pRAID_Context->reg_lock_length    = 0;
2527
2528         if (fusion->fast_path_io && (
2529                 device_id < instance->fw_supported_vd_count)) {
2530
2531                 ld = MR_TargetIdToLdGet(device_id, local_map_ptr);
2532                 if (ld >= instance->fw_supported_vd_count - 1)
2533                         fp_possible = 0;
2534                 else {
2535                         raid = MR_LdRaidGet(ld, local_map_ptr);
2536                         if (!(raid->capability.fpNonRWCapable))
2537                                 fp_possible = 0;
2538                 }
2539         } else
2540                 fp_possible = 0;
2541
2542         if (!fp_possible) {
2543                 io_request->Function  = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
2544                 io_request->DevHandle = cpu_to_le16(device_id);
2545                 io_request->LUN[1] = scmd->device->lun;
2546                 pRAID_Context->timeout_value =
2547                         cpu_to_le16 (scmd->request->timeout / HZ);
2548                 cmd->request_desc->SCSIIO.RequestFlags =
2549                         (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
2550                         MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2551         } else {
2552
2553                 /* set RAID context values */
2554                 pRAID_Context->config_seq_num = raid->seqNum;
2555                 if (instance->adapter_type != VENTURA_SERIES)
2556                         pRAID_Context->reg_lock_flags = REGION_TYPE_SHARED_READ;
2557                 pRAID_Context->timeout_value =
2558                         cpu_to_le16(raid->fpIoTimeoutForLd);
2559
2560                 /* get the DevHandle for the PD (since this is
2561                    fpNonRWCapable, this is a single disk RAID0) */
2562                 span = physArm = 0;
2563                 arRef = MR_LdSpanArrayGet(ld, span, local_map_ptr);
2564                 pd = MR_ArPdGet(arRef, physArm, local_map_ptr);
2565                 devHandle = MR_PdDevHandleGet(pd, local_map_ptr);
2566
2567                 /* build request descriptor */
2568                 cmd->request_desc->SCSIIO.RequestFlags =
2569                         (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
2570                         MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2571                 cmd->request_desc->SCSIIO.DevHandle = devHandle;
2572
2573                 /* populate the LUN field */
2574                 memcpy(io_request->LUN, raid->LUN, 8);
2575
2576                 /* build the raidScsiIO structure */
2577                 io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
2578                 io_request->DevHandle = devHandle;
2579         }
2580 }
2581
2582 /**
2583  * megasas_build_syspd_fusion - prepares rw/non-rw ios for syspd
2584  * @instance:           Adapter soft state
2585  * @scp:                SCSI command
2586  * @cmd:                Command to be prepared
2587  * @fp_possible:        parameter to detect fast path or firmware path io.
2588  *
2589  * Prepares the io_request frame for rw/non-rw io cmds for syspds
2590  */
2591 static void
2592 megasas_build_syspd_fusion(struct megasas_instance *instance,
2593         struct scsi_cmnd *scmd, struct megasas_cmd_fusion *cmd,
2594         bool fp_possible)
2595 {
2596         u32 device_id;
2597         struct MPI2_RAID_SCSI_IO_REQUEST *io_request;
2598         u16 pd_index = 0;
2599         u16 os_timeout_value;
2600         u16 timeout_limit;
2601         struct MR_DRV_RAID_MAP_ALL *local_map_ptr;
2602         struct RAID_CONTEXT     *pRAID_Context;
2603         struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
2604         struct MR_PRIV_DEVICE *mr_device_priv_data;
2605         struct fusion_context *fusion = instance->ctrl_context;
2606         pd_sync = (void *)fusion->pd_seq_sync[(instance->pd_seq_map_id - 1) & 1];
2607
2608         device_id = MEGASAS_DEV_INDEX(scmd);
2609         pd_index = MEGASAS_PD_INDEX(scmd);
2610         os_timeout_value = scmd->request->timeout / HZ;
2611         mr_device_priv_data = scmd->device->hostdata;
2612         cmd->pd_interface = mr_device_priv_data->interface_type;
2613
2614         io_request = cmd->io_request;
2615         /* get RAID_Context pointer */
2616         pRAID_Context = &io_request->RaidContext.raid_context;
2617         pRAID_Context->reg_lock_flags = 0;
2618         pRAID_Context->reg_lock_row_lba = 0;
2619         pRAID_Context->reg_lock_length = 0;
2620         io_request->DataLength = cpu_to_le32(scsi_bufflen(scmd));
2621         io_request->LUN[1] = scmd->device->lun;
2622         pRAID_Context->raid_flags = MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD
2623                 << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
2624
2625         /* If FW supports PD sequence number */
2626         if (instance->use_seqnum_jbod_fp &&
2627                 instance->pd_list[pd_index].driveType == TYPE_DISK) {
2628                 /* TgtId must be incremented by 255 as jbod seq number is index
2629                  * below raid map
2630                  */
2631                  /* More than 256 PD/JBOD support for Ventura */
2632                 if (instance->support_morethan256jbod)
2633                         pRAID_Context->virtual_disk_tgt_id =
2634                                 pd_sync->seq[pd_index].pd_target_id;
2635                 else
2636                         pRAID_Context->virtual_disk_tgt_id =
2637                                 cpu_to_le16(device_id + (MAX_PHYSICAL_DEVICES - 1));
2638                 pRAID_Context->config_seq_num = pd_sync->seq[pd_index].seqNum;
2639                 io_request->DevHandle = pd_sync->seq[pd_index].devHandle;
2640                 if (instance->adapter_type == VENTURA_SERIES) {
2641                         io_request->RaidContext.raid_context_g35.routing_flags |=
2642                                 (1 << MR_RAID_CTX_ROUTINGFLAGS_SQN_SHIFT);
2643                         io_request->RaidContext.raid_context_g35.nseg_type |=
2644                                                         (1 << RAID_CONTEXT_NSEG_SHIFT);
2645                         io_request->RaidContext.raid_context_g35.nseg_type |=
2646                                                         (MPI2_TYPE_CUDA << RAID_CONTEXT_TYPE_SHIFT);
2647                 } else {
2648                         pRAID_Context->type = MPI2_TYPE_CUDA;
2649                         pRAID_Context->nseg = 0x1;
2650                         pRAID_Context->reg_lock_flags |=
2651                                 (MR_RL_FLAGS_SEQ_NUM_ENABLE|MR_RL_FLAGS_GRANT_DESTINATION_CUDA);
2652                 }
2653         } else if (fusion->fast_path_io) {
2654                 pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
2655                 pRAID_Context->config_seq_num = 0;
2656                 local_map_ptr = fusion->ld_drv_map[(instance->map_id & 1)];
2657                 io_request->DevHandle =
2658                         local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
2659         } else {
2660                 /* Want to send all IO via FW path */
2661                 pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
2662                 pRAID_Context->config_seq_num = 0;
2663                 io_request->DevHandle = cpu_to_le16(0xFFFF);
2664         }
2665
2666         cmd->request_desc->SCSIIO.DevHandle = io_request->DevHandle;
2667
2668         cmd->request_desc->SCSIIO.MSIxIndex =
2669                 instance->reply_map[raw_smp_processor_id()];
2670
2671         if (!fp_possible) {
2672                 /* system pd firmware path */
2673                 io_request->Function  = MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST;
2674                 cmd->request_desc->SCSIIO.RequestFlags =
2675                         (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
2676                                 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2677                 pRAID_Context->timeout_value = cpu_to_le16(os_timeout_value);
2678                 pRAID_Context->virtual_disk_tgt_id = cpu_to_le16(device_id);
2679         } else {
2680                 if (os_timeout_value)
2681                         os_timeout_value++;
2682
2683                 /* system pd Fast Path */
2684                 io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
2685                 timeout_limit = (scmd->device->type == TYPE_DISK) ?
2686                                 255 : 0xFFFF;
2687                 pRAID_Context->timeout_value =
2688                         cpu_to_le16((os_timeout_value > timeout_limit) ?
2689                         timeout_limit : os_timeout_value);
2690                 if (instance->adapter_type >= INVADER_SERIES)
2691                         io_request->IoFlags |=
2692                                 cpu_to_le16(MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH);
2693
2694                 cmd->request_desc->SCSIIO.RequestFlags =
2695                         (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
2696                                 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2697         }
2698 }
2699
2700 /**
2701  * megasas_build_io_fusion -    Prepares IOs to devices
2702  * @instance:           Adapter soft state
2703  * @scp:                SCSI command
2704  * @cmd:                Command to be prepared
2705  *
2706  * Invokes helper functions to prepare request frames
2707  * and sets flags appropriate for IO/Non-IO cmd
2708  */
2709 int
2710 megasas_build_io_fusion(struct megasas_instance *instance,
2711                         struct scsi_cmnd *scp,
2712                         struct megasas_cmd_fusion *cmd)
2713 {
2714         int sge_count;
2715         u8  cmd_type;
2716         struct MPI2_RAID_SCSI_IO_REQUEST *io_request = cmd->io_request;
2717         struct MR_PRIV_DEVICE *mr_device_priv_data;
2718         mr_device_priv_data = scp->device->hostdata;
2719
2720         /* Zero out some fields so they don't get reused */
2721         memset(io_request->LUN, 0x0, 8);
2722         io_request->CDB.EEDP32.PrimaryReferenceTag = 0;
2723         io_request->CDB.EEDP32.PrimaryApplicationTagMask = 0;
2724         io_request->EEDPFlags = 0;
2725         io_request->Control = 0;
2726         io_request->EEDPBlockSize = 0;
2727         io_request->ChainOffset = 0;
2728         io_request->RaidContext.raid_context.raid_flags = 0;
2729         io_request->RaidContext.raid_context.type = 0;
2730         io_request->RaidContext.raid_context.nseg = 0;
2731
2732         memcpy(io_request->CDB.CDB32, scp->cmnd, scp->cmd_len);
2733         /*
2734          * Just the CDB length,rest of the Flags are zero
2735          * This will be modified for FP in build_ldio_fusion
2736          */
2737         io_request->IoFlags = cpu_to_le16(scp->cmd_len);
2738
2739         switch (cmd_type = megasas_cmd_type(scp)) {
2740         case READ_WRITE_LDIO:
2741                 megasas_build_ldio_fusion(instance, scp, cmd);
2742                 break;
2743         case NON_READ_WRITE_LDIO:
2744                 megasas_build_ld_nonrw_fusion(instance, scp, cmd);
2745                 break;
2746         case READ_WRITE_SYSPDIO:
2747                 megasas_build_syspd_fusion(instance, scp, cmd, true);
2748                 break;
2749         case NON_READ_WRITE_SYSPDIO:
2750                 if (instance->secure_jbod_support ||
2751                     mr_device_priv_data->is_tm_capable)
2752                         megasas_build_syspd_fusion(instance, scp, cmd, false);
2753                 else
2754                         megasas_build_syspd_fusion(instance, scp, cmd, true);
2755                 break;
2756         default:
2757                 break;
2758         }
2759
2760         /*
2761          * Construct SGL
2762          */
2763
2764         sge_count = megasas_make_sgl(instance, scp, cmd);
2765
2766         if (sge_count > instance->max_num_sge || (sge_count < 0)) {
2767                 dev_err(&instance->pdev->dev,
2768                         "%s %d sge_count (%d) is out of range. Range is:  0-%d\n",
2769                         __func__, __LINE__, sge_count, instance->max_num_sge);
2770                 return 1;
2771         }
2772
2773         if (instance->adapter_type == VENTURA_SERIES) {
2774                 set_num_sge(&io_request->RaidContext.raid_context_g35, sge_count);
2775                 cpu_to_le16s(&io_request->RaidContext.raid_context_g35.routing_flags);
2776                 cpu_to_le16s(&io_request->RaidContext.raid_context_g35.nseg_type);
2777         } else {
2778                 /* numSGE store lower 8 bit of sge_count.
2779                  * numSGEExt store higher 8 bit of sge_count
2780                  */
2781                 io_request->RaidContext.raid_context.num_sge = sge_count;
2782                 io_request->RaidContext.raid_context.num_sge_ext =
2783                         (u8)(sge_count >> 8);
2784         }
2785
2786         io_request->SGLFlags = cpu_to_le16(MPI2_SGE_FLAGS_64_BIT_ADDRESSING);
2787
2788         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
2789                 io_request->Control |= cpu_to_le32(MPI2_SCSIIO_CONTROL_WRITE);
2790         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
2791                 io_request->Control |= cpu_to_le32(MPI2_SCSIIO_CONTROL_READ);
2792
2793         io_request->SGLOffset0 =
2794                 offsetof(struct MPI2_RAID_SCSI_IO_REQUEST, SGL) / 4;
2795
2796         io_request->SenseBufferLowAddress = cpu_to_le32(cmd->sense_phys_addr);
2797         io_request->SenseBufferLength = SCSI_SENSE_BUFFERSIZE;
2798
2799         cmd->scmd = scp;
2800         scp->SCp.ptr = (char *)cmd;
2801
2802         return 0;
2803 }
2804
2805 static union MEGASAS_REQUEST_DESCRIPTOR_UNION *
2806 megasas_get_request_descriptor(struct megasas_instance *instance, u16 index)
2807 {
2808         u8 *p;
2809         struct fusion_context *fusion;
2810
2811         fusion = instance->ctrl_context;
2812         p = fusion->req_frames_desc +
2813                 sizeof(union MEGASAS_REQUEST_DESCRIPTOR_UNION) * index;
2814
2815         return (union MEGASAS_REQUEST_DESCRIPTOR_UNION *)p;
2816 }
2817
2818
2819 /* megasas_prepate_secondRaid1_IO
2820  *  It prepares the raid 1 second IO
2821  */
2822 void megasas_prepare_secondRaid1_IO(struct megasas_instance *instance,
2823                             struct megasas_cmd_fusion *cmd,
2824                             struct megasas_cmd_fusion *r1_cmd)
2825 {
2826         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc, *req_desc2 = NULL;
2827         struct fusion_context *fusion;
2828         fusion = instance->ctrl_context;
2829         req_desc = cmd->request_desc;
2830         /* copy the io request frame as well as 8 SGEs data for r1 command*/
2831         memcpy(r1_cmd->io_request, cmd->io_request,
2832                (sizeof(struct MPI2_RAID_SCSI_IO_REQUEST)));
2833         memcpy(&r1_cmd->io_request->SGL, &cmd->io_request->SGL,
2834                (fusion->max_sge_in_main_msg * sizeof(union MPI2_SGE_IO_UNION)));
2835         /*sense buffer is different for r1 command*/
2836         r1_cmd->io_request->SenseBufferLowAddress =
2837                         cpu_to_le32(r1_cmd->sense_phys_addr);
2838         r1_cmd->scmd = cmd->scmd;
2839         req_desc2 = megasas_get_request_descriptor(instance,
2840                                                    (r1_cmd->index - 1));
2841         req_desc2->Words = 0;
2842         r1_cmd->request_desc = req_desc2;
2843         req_desc2->SCSIIO.SMID = cpu_to_le16(r1_cmd->index);
2844         req_desc2->SCSIIO.RequestFlags = req_desc->SCSIIO.RequestFlags;
2845         r1_cmd->request_desc->SCSIIO.DevHandle = cmd->r1_alt_dev_handle;
2846         r1_cmd->io_request->DevHandle = cmd->r1_alt_dev_handle;
2847         r1_cmd->r1_alt_dev_handle = cmd->io_request->DevHandle;
2848         cmd->io_request->RaidContext.raid_context_g35.smid.peer_smid =
2849                         cpu_to_le16(r1_cmd->index);
2850         r1_cmd->io_request->RaidContext.raid_context_g35.smid.peer_smid =
2851                         cpu_to_le16(cmd->index);
2852         /*MSIxIndex of both commands request descriptors should be same*/
2853         r1_cmd->request_desc->SCSIIO.MSIxIndex =
2854                         cmd->request_desc->SCSIIO.MSIxIndex;
2855         /*span arm is different for r1 cmd*/
2856         r1_cmd->io_request->RaidContext.raid_context_g35.span_arm =
2857                         cmd->io_request->RaidContext.raid_context_g35.span_arm + 1;
2858 }
2859
2860 /**
2861  * megasas_build_and_issue_cmd_fusion -Main routine for building and
2862  *                                     issuing non IOCTL cmd
2863  * @instance:                   Adapter soft state
2864  * @scmd:                       pointer to scsi cmd from OS
2865  */
2866 static u32
2867 megasas_build_and_issue_cmd_fusion(struct megasas_instance *instance,
2868                                    struct scsi_cmnd *scmd)
2869 {
2870         struct megasas_cmd_fusion *cmd, *r1_cmd = NULL;
2871         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2872         u32 index;
2873         struct fusion_context *fusion;
2874
2875         fusion = instance->ctrl_context;
2876
2877         if ((megasas_cmd_type(scmd) == READ_WRITE_LDIO) &&
2878                 instance->ldio_threshold &&
2879                 (atomic_inc_return(&instance->ldio_outstanding) >
2880                 instance->ldio_threshold)) {
2881                 atomic_dec(&instance->ldio_outstanding);
2882                 return SCSI_MLQUEUE_DEVICE_BUSY;
2883         }
2884
2885         if (atomic_inc_return(&instance->fw_outstanding) >
2886                         instance->host->can_queue) {
2887                 atomic_dec(&instance->fw_outstanding);
2888                 return SCSI_MLQUEUE_HOST_BUSY;
2889         }
2890
2891         cmd = megasas_get_cmd_fusion(instance, scmd->request->tag);
2892
2893         if (!cmd) {
2894                 atomic_dec(&instance->fw_outstanding);
2895                 return SCSI_MLQUEUE_HOST_BUSY;
2896         }
2897
2898         index = cmd->index;
2899
2900         req_desc = megasas_get_request_descriptor(instance, index-1);
2901
2902         req_desc->Words = 0;
2903         cmd->request_desc = req_desc;
2904
2905         if (megasas_build_io_fusion(instance, scmd, cmd)) {
2906                 megasas_return_cmd_fusion(instance, cmd);
2907                 dev_err(&instance->pdev->dev, "Error building command\n");
2908                 cmd->request_desc = NULL;
2909                 atomic_dec(&instance->fw_outstanding);
2910                 return SCSI_MLQUEUE_HOST_BUSY;
2911         }
2912
2913         req_desc = cmd->request_desc;
2914         req_desc->SCSIIO.SMID = cpu_to_le16(index);
2915
2916         if (cmd->io_request->ChainOffset != 0 &&
2917             cmd->io_request->ChainOffset != 0xF)
2918                 dev_err(&instance->pdev->dev, "The chain offset value is not "
2919                        "correct : %x\n", cmd->io_request->ChainOffset);
2920         /*
2921          *      if it is raid 1/10 fp write capable.
2922          *      try to get second command from pool and construct it.
2923          *      From FW, it has confirmed that lba values of two PDs
2924          *      corresponds to single R1/10 LD are always same
2925          *
2926          */
2927         /*      driver side count always should be less than max_fw_cmds
2928          *      to get new command
2929          */
2930         if (cmd->r1_alt_dev_handle != MR_DEVHANDLE_INVALID) {
2931                 r1_cmd = megasas_get_cmd_fusion(instance,
2932                                 (scmd->request->tag + instance->max_fw_cmds));
2933                 megasas_prepare_secondRaid1_IO(instance, cmd, r1_cmd);
2934         }
2935
2936
2937         /*
2938          * Issue the command to the FW
2939          */
2940
2941         megasas_fire_cmd_fusion(instance, req_desc);
2942
2943         if (r1_cmd)
2944                 megasas_fire_cmd_fusion(instance, r1_cmd->request_desc);
2945
2946
2947         return 0;
2948 }
2949
2950 /**
2951  * megasas_complete_r1_command -
2952  * completes R1 FP write commands which has valid peer smid
2953  * @instance:                   Adapter soft state
2954  * @cmd_fusion:                 MPT command frame
2955  *
2956  */
2957 static inline void
2958 megasas_complete_r1_command(struct megasas_instance *instance,
2959                             struct megasas_cmd_fusion *cmd)
2960 {
2961         u8 *sense, status, ex_status;
2962         u32 data_length;
2963         u16 peer_smid;
2964         struct fusion_context *fusion;
2965         struct megasas_cmd_fusion *r1_cmd = NULL;
2966         struct scsi_cmnd *scmd_local = NULL;
2967         struct RAID_CONTEXT_G35 *rctx_g35;
2968
2969         rctx_g35 = &cmd->io_request->RaidContext.raid_context_g35;
2970         fusion = instance->ctrl_context;
2971         peer_smid = le16_to_cpu(rctx_g35->smid.peer_smid);
2972
2973         r1_cmd = fusion->cmd_list[peer_smid - 1];
2974         scmd_local = cmd->scmd;
2975         status = rctx_g35->status;
2976         ex_status = rctx_g35->ex_status;
2977         data_length = cmd->io_request->DataLength;
2978         sense = cmd->sense;
2979
2980         cmd->cmd_completed = true;
2981
2982         /* Check if peer command is completed or not*/
2983         if (r1_cmd->cmd_completed) {
2984                 rctx_g35 = &r1_cmd->io_request->RaidContext.raid_context_g35;
2985                 if (rctx_g35->status != MFI_STAT_OK) {
2986                         status = rctx_g35->status;
2987                         ex_status = rctx_g35->ex_status;
2988                         data_length = r1_cmd->io_request->DataLength;
2989                         sense = r1_cmd->sense;
2990                 }
2991
2992                 megasas_return_cmd_fusion(instance, r1_cmd);
2993                 map_cmd_status(fusion, scmd_local, status, ex_status,
2994                                le32_to_cpu(data_length), sense);
2995                 if (instance->ldio_threshold &&
2996                     megasas_cmd_type(scmd_local) == READ_WRITE_LDIO)
2997                         atomic_dec(&instance->ldio_outstanding);
2998                 scmd_local->SCp.ptr = NULL;
2999                 megasas_return_cmd_fusion(instance, cmd);
3000                 scsi_dma_unmap(scmd_local);
3001                 scmd_local->scsi_done(scmd_local);
3002         }
3003 }
3004
3005 /**
3006  * complete_cmd_fusion -        Completes command
3007  * @instance:                   Adapter soft state
3008  * Completes all commands that is in reply descriptor queue
3009  */
3010 int
3011 complete_cmd_fusion(struct megasas_instance *instance, u32 MSIxIndex)
3012 {
3013         union MPI2_REPLY_DESCRIPTORS_UNION *desc;
3014         struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *reply_desc;
3015         struct MPI2_RAID_SCSI_IO_REQUEST *scsi_io_req;
3016         struct fusion_context *fusion;
3017         struct megasas_cmd *cmd_mfi;
3018         struct megasas_cmd_fusion *cmd_fusion;
3019         u16 smid, num_completed;
3020         u8 reply_descript_type, *sense, status, extStatus;
3021         u32 device_id, data_length;
3022         union desc_value d_val;
3023         struct LD_LOAD_BALANCE_INFO *lbinfo;
3024         int threshold_reply_count = 0;
3025         struct scsi_cmnd *scmd_local = NULL;
3026         struct MR_TASK_MANAGE_REQUEST *mr_tm_req;
3027         struct MPI2_SCSI_TASK_MANAGE_REQUEST *mpi_tm_req;
3028
3029         fusion = instance->ctrl_context;
3030
3031         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR)
3032                 return IRQ_HANDLED;
3033
3034         desc = fusion->reply_frames_desc[MSIxIndex] +
3035                                 fusion->last_reply_idx[MSIxIndex];
3036
3037         reply_desc = (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;
3038
3039         d_val.word = desc->Words;
3040
3041         reply_descript_type = reply_desc->ReplyFlags &
3042                 MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
3043
3044         if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
3045                 return IRQ_NONE;
3046
3047         num_completed = 0;
3048
3049         while (d_val.u.low != cpu_to_le32(UINT_MAX) &&
3050                d_val.u.high != cpu_to_le32(UINT_MAX)) {
3051
3052                 smid = le16_to_cpu(reply_desc->SMID);
3053                 cmd_fusion = fusion->cmd_list[smid - 1];
3054                 scsi_io_req = (struct MPI2_RAID_SCSI_IO_REQUEST *)
3055                                                 cmd_fusion->io_request;
3056
3057                 scmd_local = cmd_fusion->scmd;
3058                 status = scsi_io_req->RaidContext.raid_context.status;
3059                 extStatus = scsi_io_req->RaidContext.raid_context.ex_status;
3060                 sense = cmd_fusion->sense;
3061                 data_length = scsi_io_req->DataLength;
3062
3063                 switch (scsi_io_req->Function) {
3064                 case MPI2_FUNCTION_SCSI_TASK_MGMT:
3065                         mr_tm_req = (struct MR_TASK_MANAGE_REQUEST *)
3066                                                 cmd_fusion->io_request;
3067                         mpi_tm_req = (struct MPI2_SCSI_TASK_MANAGE_REQUEST *)
3068                                                 &mr_tm_req->TmRequest;
3069                         dev_dbg(&instance->pdev->dev, "TM completion:"
3070                                 "type: 0x%x TaskMID: 0x%x\n",
3071                                 mpi_tm_req->TaskType, mpi_tm_req->TaskMID);
3072                         complete(&cmd_fusion->done);
3073                         break;
3074                 case MPI2_FUNCTION_SCSI_IO_REQUEST:  /*Fast Path IO.*/
3075                         /* Update load balancing info */
3076                         if (fusion->load_balance_info &&
3077                             (cmd_fusion->scmd->SCp.Status &
3078                             MEGASAS_LOAD_BALANCE_FLAG)) {
3079                                 device_id = MEGASAS_DEV_INDEX(scmd_local);
3080                                 lbinfo = &fusion->load_balance_info[device_id];
3081                                 atomic_dec(&lbinfo->scsi_pending_cmds[cmd_fusion->pd_r1_lb]);
3082                                 cmd_fusion->scmd->SCp.Status &= ~MEGASAS_LOAD_BALANCE_FLAG;
3083                         }
3084                         //Fall thru and complete IO
3085                 case MEGASAS_MPI2_FUNCTION_LD_IO_REQUEST: /* LD-IO Path */
3086                         atomic_dec(&instance->fw_outstanding);
3087                         if (cmd_fusion->r1_alt_dev_handle == MR_DEVHANDLE_INVALID) {
3088                                 map_cmd_status(fusion, scmd_local, status,
3089                                                extStatus, le32_to_cpu(data_length),
3090                                                sense);
3091                                 if (instance->ldio_threshold &&
3092                                     (megasas_cmd_type(scmd_local) == READ_WRITE_LDIO))
3093                                         atomic_dec(&instance->ldio_outstanding);
3094                                 scmd_local->SCp.ptr = NULL;
3095                                 megasas_return_cmd_fusion(instance, cmd_fusion);
3096                                 scsi_dma_unmap(scmd_local);
3097                                 scmd_local->scsi_done(scmd_local);
3098                         } else  /* Optimal VD - R1 FP command completion. */
3099                                 megasas_complete_r1_command(instance, cmd_fusion);
3100                         break;
3101                 case MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST: /*MFI command */
3102                         cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
3103                         /* Poll mode. Dummy free.
3104                          * In case of Interrupt mode, caller has reverse check.
3105                          */
3106                         if (cmd_mfi->flags & DRV_DCMD_POLLED_MODE) {
3107                                 cmd_mfi->flags &= ~DRV_DCMD_POLLED_MODE;
3108                                 megasas_return_cmd(instance, cmd_mfi);
3109                         } else
3110                                 megasas_complete_cmd(instance, cmd_mfi, DID_OK);
3111                         break;
3112                 }
3113
3114                 fusion->last_reply_idx[MSIxIndex]++;
3115                 if (fusion->last_reply_idx[MSIxIndex] >=
3116                     fusion->reply_q_depth)
3117                         fusion->last_reply_idx[MSIxIndex] = 0;
3118
3119                 desc->Words = cpu_to_le64(ULLONG_MAX);
3120                 num_completed++;
3121                 threshold_reply_count++;
3122
3123                 /* Get the next reply descriptor */
3124                 if (!fusion->last_reply_idx[MSIxIndex])
3125                         desc = fusion->reply_frames_desc[MSIxIndex];
3126                 else
3127                         desc++;
3128
3129                 reply_desc =
3130                   (struct MPI2_SCSI_IO_SUCCESS_REPLY_DESCRIPTOR *)desc;
3131
3132                 d_val.word = desc->Words;
3133
3134                 reply_descript_type = reply_desc->ReplyFlags &
3135                         MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
3136
3137                 if (reply_descript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
3138                         break;
3139                 /*
3140                  * Write to reply post host index register after completing threshold
3141                  * number of reply counts and still there are more replies in reply queue
3142                  * pending to be completed
3143                  */
3144                 if (threshold_reply_count >= THRESHOLD_REPLY_COUNT) {
3145                         if (instance->msix_combined)
3146                                 writel(((MSIxIndex & 0x7) << 24) |
3147                                         fusion->last_reply_idx[MSIxIndex],
3148                                         instance->reply_post_host_index_addr[MSIxIndex/8]);
3149                         else
3150                                 writel((MSIxIndex << 24) |
3151                                         fusion->last_reply_idx[MSIxIndex],
3152                                         instance->reply_post_host_index_addr[0]);
3153                         threshold_reply_count = 0;
3154                 }
3155         }
3156
3157         if (!num_completed)
3158                 return IRQ_NONE;
3159
3160         wmb();
3161         if (instance->msix_combined)
3162                 writel(((MSIxIndex & 0x7) << 24) |
3163                         fusion->last_reply_idx[MSIxIndex],
3164                         instance->reply_post_host_index_addr[MSIxIndex/8]);
3165         else
3166                 writel((MSIxIndex << 24) |
3167                         fusion->last_reply_idx[MSIxIndex],
3168                         instance->reply_post_host_index_addr[0]);
3169         megasas_check_and_restore_queue_depth(instance);
3170         return IRQ_HANDLED;
3171 }
3172
3173 /**
3174  * megasas_sync_irqs -  Synchronizes all IRQs owned by adapter
3175  * @instance:                   Adapter soft state
3176  */
3177 void megasas_sync_irqs(unsigned long instance_addr)
3178 {
3179         u32 count, i;
3180         struct megasas_instance *instance =
3181                 (struct megasas_instance *)instance_addr;
3182
3183         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
3184
3185         for (i = 0; i < count; i++)
3186                 synchronize_irq(pci_irq_vector(instance->pdev, i));
3187 }
3188
3189 /**
3190  * megasas_complete_cmd_dpc_fusion -    Completes command
3191  * @instance:                   Adapter soft state
3192  *
3193  * Tasklet to complete cmds
3194  */
3195 void
3196 megasas_complete_cmd_dpc_fusion(unsigned long instance_addr)
3197 {
3198         struct megasas_instance *instance =
3199                 (struct megasas_instance *)instance_addr;
3200         unsigned long flags;
3201         u32 count, MSIxIndex;
3202
3203         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
3204
3205         /* If we have already declared adapter dead, donot complete cmds */
3206         spin_lock_irqsave(&instance->hba_lock, flags);
3207         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
3208                 spin_unlock_irqrestore(&instance->hba_lock, flags);
3209                 return;
3210         }
3211         spin_unlock_irqrestore(&instance->hba_lock, flags);
3212
3213         for (MSIxIndex = 0 ; MSIxIndex < count; MSIxIndex++)
3214                 complete_cmd_fusion(instance, MSIxIndex);
3215 }
3216
3217 /**
3218  * megasas_isr_fusion - isr entry point
3219  */
3220 irqreturn_t megasas_isr_fusion(int irq, void *devp)
3221 {
3222         struct megasas_irq_context *irq_context = devp;
3223         struct megasas_instance *instance = irq_context->instance;
3224         u32 mfiStatus, fw_state, dma_state;
3225
3226         if (instance->mask_interrupts)
3227                 return IRQ_NONE;
3228
3229         if (!instance->msix_vectors) {
3230                 mfiStatus = instance->instancet->clear_intr(instance->reg_set);
3231                 if (!mfiStatus)
3232                         return IRQ_NONE;
3233         }
3234
3235         /* If we are resetting, bail */
3236         if (test_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags)) {
3237                 instance->instancet->clear_intr(instance->reg_set);
3238                 return IRQ_HANDLED;
3239         }
3240
3241         if (!complete_cmd_fusion(instance, irq_context->MSIxIndex)) {
3242                 instance->instancet->clear_intr(instance->reg_set);
3243                 /* If we didn't complete any commands, check for FW fault */
3244                 fw_state = instance->instancet->read_fw_status_reg(
3245                         instance->reg_set) & MFI_STATE_MASK;
3246                 dma_state = instance->instancet->read_fw_status_reg
3247                         (instance->reg_set) & MFI_STATE_DMADONE;
3248                 if (instance->crash_dump_drv_support &&
3249                         instance->crash_dump_app_support) {
3250                         /* Start collecting crash, if DMA bit is done */
3251                         if ((fw_state == MFI_STATE_FAULT) && dma_state)
3252                                 schedule_work(&instance->crash_init);
3253                         else if (fw_state == MFI_STATE_FAULT) {
3254                                 if (instance->unload == 0)
3255                                         schedule_work(&instance->work_init);
3256                         }
3257                 } else if (fw_state == MFI_STATE_FAULT) {
3258                         dev_warn(&instance->pdev->dev, "Iop2SysDoorbellInt"
3259                                "for scsi%d\n", instance->host->host_no);
3260                         if (instance->unload == 0)
3261                                 schedule_work(&instance->work_init);
3262                 }
3263         }
3264
3265         return IRQ_HANDLED;
3266 }
3267
3268 /**
3269  * build_mpt_mfi_pass_thru - builds a cmd fo MFI Pass thru
3270  * @instance:                   Adapter soft state
3271  * mfi_cmd:                     megasas_cmd pointer
3272  *
3273  */
3274 void
3275 build_mpt_mfi_pass_thru(struct megasas_instance *instance,
3276                         struct megasas_cmd *mfi_cmd)
3277 {
3278         struct MPI25_IEEE_SGE_CHAIN64 *mpi25_ieee_chain;
3279         struct MPI2_RAID_SCSI_IO_REQUEST *io_req;
3280         struct megasas_cmd_fusion *cmd;
3281         struct fusion_context *fusion;
3282         struct megasas_header *frame_hdr = &mfi_cmd->frame->hdr;
3283
3284         fusion = instance->ctrl_context;
3285
3286         cmd = megasas_get_cmd_fusion(instance,
3287                         instance->max_scsi_cmds + mfi_cmd->index);
3288
3289         /*  Save the smid. To be used for returning the cmd */
3290         mfi_cmd->context.smid = cmd->index;
3291
3292         /*
3293          * For cmds where the flag is set, store the flag and check
3294          * on completion. For cmds with this flag, don't call
3295          * megasas_complete_cmd
3296          */
3297
3298         if (frame_hdr->flags & cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE))
3299                 mfi_cmd->flags |= DRV_DCMD_POLLED_MODE;
3300
3301         io_req = cmd->io_request;
3302
3303         if (instance->adapter_type >= INVADER_SERIES) {
3304                 struct MPI25_IEEE_SGE_CHAIN64 *sgl_ptr_end =
3305                         (struct MPI25_IEEE_SGE_CHAIN64 *)&io_req->SGL;
3306                 sgl_ptr_end += fusion->max_sge_in_main_msg - 1;
3307                 sgl_ptr_end->Flags = 0;
3308         }
3309
3310         mpi25_ieee_chain =
3311           (struct MPI25_IEEE_SGE_CHAIN64 *)&io_req->SGL.IeeeChain;
3312
3313         io_req->Function    = MEGASAS_MPI2_FUNCTION_PASSTHRU_IO_REQUEST;
3314         io_req->SGLOffset0  = offsetof(struct MPI2_RAID_SCSI_IO_REQUEST,
3315                                        SGL) / 4;
3316         io_req->ChainOffset = fusion->chain_offset_mfi_pthru;
3317
3318         mpi25_ieee_chain->Address = cpu_to_le64(mfi_cmd->frame_phys_addr);
3319
3320         mpi25_ieee_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3321                 MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR;
3322
3323         mpi25_ieee_chain->Length = cpu_to_le32(instance->mfi_frame_size);
3324 }
3325
3326 /**
3327  * build_mpt_cmd - Calls helper function to build a cmd MFI Pass thru cmd
3328  * @instance:                   Adapter soft state
3329  * @cmd:                        mfi cmd to build
3330  *
3331  */
3332 union MEGASAS_REQUEST_DESCRIPTOR_UNION *
3333 build_mpt_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
3334 {
3335         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc = NULL;
3336         u16 index;
3337
3338         build_mpt_mfi_pass_thru(instance, cmd);
3339         index = cmd->context.smid;
3340
3341         req_desc = megasas_get_request_descriptor(instance, index - 1);
3342
3343         req_desc->Words = 0;
3344         req_desc->SCSIIO.RequestFlags = (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
3345                                          MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3346
3347         req_desc->SCSIIO.SMID = cpu_to_le16(index);
3348
3349         return req_desc;
3350 }
3351
3352 /**
3353  * megasas_issue_dcmd_fusion - Issues a MFI Pass thru cmd
3354  * @instance:                   Adapter soft state
3355  * @cmd:                        mfi cmd pointer
3356  *
3357  */
3358 void
3359 megasas_issue_dcmd_fusion(struct megasas_instance *instance,
3360                           struct megasas_cmd *cmd)
3361 {
3362         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
3363
3364         req_desc = build_mpt_cmd(instance, cmd);
3365
3366         megasas_fire_cmd_fusion(instance, req_desc);
3367         return;
3368 }
3369
3370 /**
3371  * megasas_release_fusion -     Reverses the FW initialization
3372  * @instance:                   Adapter soft state
3373  */
3374 void
3375 megasas_release_fusion(struct megasas_instance *instance)
3376 {
3377         megasas_free_cmds(instance);
3378         megasas_free_cmds_fusion(instance);
3379
3380         iounmap(instance->reg_set);
3381
3382         pci_release_selected_regions(instance->pdev, 1<<instance->bar);
3383 }
3384
3385 /**
3386  * megasas_read_fw_status_reg_fusion - returns the current FW status value
3387  * @regs:                       MFI register set
3388  */
3389 static u32
3390 megasas_read_fw_status_reg_fusion(struct megasas_register_set __iomem *regs)
3391 {
3392         return readl(&(regs)->outbound_scratch_pad);
3393 }
3394
3395 /**
3396  * megasas_alloc_host_crash_buffer -    Host buffers for Crash dump collection from Firmware
3397  * @instance:                           Controller's soft instance
3398  * return:                              Number of allocated host crash buffers
3399  */
3400 static void
3401 megasas_alloc_host_crash_buffer(struct megasas_instance *instance)
3402 {
3403         unsigned int i;
3404
3405         for (i = 0; i < MAX_CRASH_DUMP_SIZE; i++) {
3406                 instance->crash_buf[i] = vzalloc(CRASH_DMA_BUF_SIZE);
3407                 if (!instance->crash_buf[i]) {
3408                         dev_info(&instance->pdev->dev, "Firmware crash dump "
3409                                 "memory allocation failed at index %d\n", i);
3410                         break;
3411                 }
3412         }
3413         instance->drv_buf_alloc = i;
3414 }
3415
3416 /**
3417  * megasas_free_host_crash_buffer -     Host buffers for Crash dump collection from Firmware
3418  * @instance:                           Controller's soft instance
3419  */
3420 void
3421 megasas_free_host_crash_buffer(struct megasas_instance *instance)
3422 {
3423         unsigned int i;
3424         for (i = 0; i < instance->drv_buf_alloc; i++) {
3425                 if (instance->crash_buf[i])
3426                         vfree(instance->crash_buf[i]);
3427         }
3428         instance->drv_buf_index = 0;
3429         instance->drv_buf_alloc = 0;
3430         instance->fw_crash_state = UNAVAILABLE;
3431         instance->fw_crash_buffer_size = 0;
3432 }
3433
3434 /**
3435  * megasas_adp_reset_fusion -   For controller reset
3436  * @regs:                               MFI register set
3437  */
3438 static int
3439 megasas_adp_reset_fusion(struct megasas_instance *instance,
3440                          struct megasas_register_set __iomem *regs)
3441 {
3442         u32 host_diag, abs_state, retry;
3443
3444         /* Now try to reset the chip */
3445         writel(MPI2_WRSEQ_FLUSH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3446         writel(MPI2_WRSEQ_1ST_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3447         writel(MPI2_WRSEQ_2ND_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3448         writel(MPI2_WRSEQ_3RD_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3449         writel(MPI2_WRSEQ_4TH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3450         writel(MPI2_WRSEQ_5TH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3451         writel(MPI2_WRSEQ_6TH_KEY_VALUE, &instance->reg_set->fusion_seq_offset);
3452
3453         /* Check that the diag write enable (DRWE) bit is on */
3454         host_diag = readl(&instance->reg_set->fusion_host_diag);
3455         retry = 0;
3456         while (!(host_diag & HOST_DIAG_WRITE_ENABLE)) {
3457                 msleep(100);
3458                 host_diag = readl(&instance->reg_set->fusion_host_diag);
3459                 if (retry++ == 100) {
3460                         dev_warn(&instance->pdev->dev,
3461                                 "Host diag unlock failed from %s %d\n",
3462                                 __func__, __LINE__);
3463                         break;
3464                 }
3465         }
3466         if (!(host_diag & HOST_DIAG_WRITE_ENABLE))
3467                 return -1;
3468
3469         /* Send chip reset command */
3470         writel(host_diag | HOST_DIAG_RESET_ADAPTER,
3471                 &instance->reg_set->fusion_host_diag);
3472         msleep(3000);
3473
3474         /* Make sure reset adapter bit is cleared */
3475         host_diag = readl(&instance->reg_set->fusion_host_diag);
3476         retry = 0;
3477         while (host_diag & HOST_DIAG_RESET_ADAPTER) {
3478                 msleep(100);
3479                 host_diag = readl(&instance->reg_set->fusion_host_diag);
3480                 if (retry++ == 1000) {
3481                         dev_warn(&instance->pdev->dev,
3482                                 "Diag reset adapter never cleared %s %d\n",
3483                                 __func__, __LINE__);
3484                         break;
3485                 }
3486         }
3487         if (host_diag & HOST_DIAG_RESET_ADAPTER)
3488                 return -1;
3489
3490         abs_state = instance->instancet->read_fw_status_reg(instance->reg_set)
3491                         & MFI_STATE_MASK;
3492         retry = 0;
3493
3494         while ((abs_state <= MFI_STATE_FW_INIT) && (retry++ < 1000)) {
3495                 msleep(100);
3496                 abs_state = instance->instancet->
3497                         read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
3498         }
3499         if (abs_state <= MFI_STATE_FW_INIT) {
3500                 dev_warn(&instance->pdev->dev,
3501                         "fw state < MFI_STATE_FW_INIT, state = 0x%x %s %d\n",
3502                         abs_state, __func__, __LINE__);
3503                 return -1;
3504         }
3505
3506         return 0;
3507 }
3508
3509 /**
3510  * megasas_check_reset_fusion - For controller reset check
3511  * @regs:                               MFI register set
3512  */
3513 static int
3514 megasas_check_reset_fusion(struct megasas_instance *instance,
3515                            struct megasas_register_set __iomem *regs)
3516 {
3517         return 0;
3518 }
3519
3520 /* This function waits for outstanding commands on fusion to complete */
3521 int megasas_wait_for_outstanding_fusion(struct megasas_instance *instance,
3522                                         int reason, int *convert)
3523 {
3524         int i, outstanding, retval = 0, hb_seconds_missed = 0;
3525         u32 fw_state;
3526
3527         for (i = 0; i < resetwaittime; i++) {
3528                 /* Check if firmware is in fault state */
3529                 fw_state = instance->instancet->read_fw_status_reg(
3530                         instance->reg_set) & MFI_STATE_MASK;
3531                 if (fw_state == MFI_STATE_FAULT) {
3532                         dev_warn(&instance->pdev->dev, "Found FW in FAULT state,"
3533                                " will reset adapter scsi%d.\n",
3534                                 instance->host->host_no);
3535                         megasas_complete_cmd_dpc_fusion((unsigned long)instance);
3536                         if (instance->requestorId && reason) {
3537                                 dev_warn(&instance->pdev->dev, "SR-IOV Found FW in FAULT"
3538                                 " state while polling during"
3539                                 " I/O timeout handling for %d\n",
3540                                 instance->host->host_no);
3541                                 *convert = 1;
3542                         }
3543
3544                         retval = 1;
3545                         goto out;
3546                 }
3547
3548                 if (reason == MFI_IO_TIMEOUT_OCR) {
3549                         dev_info(&instance->pdev->dev,
3550                                 "MFI IO is timed out, initiating OCR\n");
3551                         megasas_complete_cmd_dpc_fusion((unsigned long)instance);
3552                         retval = 1;
3553                         goto out;
3554                 }
3555
3556                 /* If SR-IOV VF mode & heartbeat timeout, don't wait */
3557                 if (instance->requestorId && !reason) {
3558                         retval = 1;
3559                         goto out;
3560                 }
3561
3562                 /* If SR-IOV VF mode & I/O timeout, check for HB timeout */
3563                 if (instance->requestorId && (reason == SCSIIO_TIMEOUT_OCR)) {
3564                         if (instance->hb_host_mem->HB.fwCounter !=
3565                             instance->hb_host_mem->HB.driverCounter) {
3566                                 instance->hb_host_mem->HB.driverCounter =
3567                                         instance->hb_host_mem->HB.fwCounter;
3568                                 hb_seconds_missed = 0;
3569                         } else {
3570                                 hb_seconds_missed++;
3571                                 if (hb_seconds_missed ==
3572                                     (MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF/HZ)) {
3573                                         dev_warn(&instance->pdev->dev, "SR-IOV:"
3574                                                " Heartbeat never completed "
3575                                                " while polling during I/O "
3576                                                " timeout handling for "
3577                                                "scsi%d.\n",
3578                                                instance->host->host_no);
3579                                                *convert = 1;
3580                                                retval = 1;
3581                                                goto out;
3582                                 }
3583                         }
3584                 }
3585
3586                 megasas_complete_cmd_dpc_fusion((unsigned long)instance);
3587                 outstanding = atomic_read(&instance->fw_outstanding);
3588                 if (!outstanding)
3589                         goto out;
3590
3591                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
3592                         dev_notice(&instance->pdev->dev, "[%2d]waiting for %d "
3593                                "commands to complete for scsi%d\n", i,
3594                                outstanding, instance->host->host_no);
3595                 }
3596                 msleep(1000);
3597         }
3598
3599         if (atomic_read(&instance->fw_outstanding)) {
3600                 dev_err(&instance->pdev->dev, "pending commands remain after waiting, "
3601                        "will reset adapter scsi%d.\n",
3602                        instance->host->host_no);
3603                 *convert = 1;
3604                 retval = 1;
3605         }
3606 out:
3607         return retval;
3608 }
3609
3610 void  megasas_reset_reply_desc(struct megasas_instance *instance)
3611 {
3612         int i, j, count;
3613         struct fusion_context *fusion;
3614         union MPI2_REPLY_DESCRIPTORS_UNION *reply_desc;
3615
3616         fusion = instance->ctrl_context;
3617         count = instance->msix_vectors > 0 ? instance->msix_vectors : 1;
3618         for (i = 0 ; i < count ; i++) {
3619                 fusion->last_reply_idx[i] = 0;
3620                 reply_desc = fusion->reply_frames_desc[i];
3621                 for (j = 0 ; j < fusion->reply_q_depth; j++, reply_desc++)
3622                         reply_desc->Words = cpu_to_le64(ULLONG_MAX);
3623         }
3624 }
3625
3626 /*
3627  * megasas_refire_mgmt_cmd :    Re-fire management commands
3628  * @instance:                           Controller's soft instance
3629 */
3630 void megasas_refire_mgmt_cmd(struct megasas_instance *instance)
3631 {
3632         int j;
3633         struct megasas_cmd_fusion *cmd_fusion;
3634         struct fusion_context *fusion;
3635         struct megasas_cmd *cmd_mfi;
3636         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
3637         u16 smid;
3638         bool refire_cmd = 0;
3639
3640         fusion = instance->ctrl_context;
3641
3642         /* Re-fire management commands.
3643          * Do not traverse complet MPT frame pool. Start from max_scsi_cmds.
3644          */
3645         for (j = instance->max_scsi_cmds ; j < instance->max_fw_cmds; j++) {
3646                 cmd_fusion = fusion->cmd_list[j];
3647                 cmd_mfi = instance->cmd_list[cmd_fusion->sync_cmd_idx];
3648                 smid = le16_to_cpu(cmd_mfi->context.smid);
3649
3650                 if (!smid)
3651                         continue;
3652
3653                 /* Do not refire shutdown command */
3654                 if (le32_to_cpu(cmd_mfi->frame->dcmd.opcode) ==
3655                         MR_DCMD_CTRL_SHUTDOWN) {
3656                         cmd_mfi->frame->dcmd.cmd_status = MFI_STAT_OK;
3657                         megasas_complete_cmd(instance, cmd_mfi, DID_OK);
3658                         continue;
3659                 }
3660
3661                 req_desc = megasas_get_request_descriptor
3662                                         (instance, smid - 1);
3663                 refire_cmd = req_desc && ((cmd_mfi->frame->dcmd.opcode !=
3664                                 cpu_to_le32(MR_DCMD_LD_MAP_GET_INFO)) &&
3665                                  (cmd_mfi->frame->dcmd.opcode !=
3666                                 cpu_to_le32(MR_DCMD_SYSTEM_PD_MAP_GET_INFO)))
3667                                 && !(cmd_mfi->flags & DRV_DCMD_SKIP_REFIRE);
3668                 if (refire_cmd)
3669                         megasas_fire_cmd_fusion(instance, req_desc);
3670                 else
3671                         megasas_return_cmd(instance, cmd_mfi);
3672         }
3673 }
3674
3675 /*
3676  * megasas_track_scsiio : Track SCSI IOs outstanding to a SCSI device
3677  * @instance: per adapter struct
3678  * @channel: the channel assigned by the OS
3679  * @id: the id assigned by the OS
3680  *
3681  * Returns SUCCESS if no IOs pending to SCSI device, else return FAILED
3682  */
3683
3684 static int megasas_track_scsiio(struct megasas_instance *instance,
3685                 int id, int channel)
3686 {
3687         int i, found = 0;
3688         struct megasas_cmd_fusion *cmd_fusion;
3689         struct fusion_context *fusion;
3690         fusion = instance->ctrl_context;
3691
3692         for (i = 0 ; i < instance->max_scsi_cmds; i++) {
3693                 cmd_fusion = fusion->cmd_list[i];
3694                 if (cmd_fusion->scmd &&
3695                         (cmd_fusion->scmd->device->id == id &&
3696                         cmd_fusion->scmd->device->channel == channel)) {
3697                         dev_info(&instance->pdev->dev,
3698                                 "SCSI commands pending to target"
3699                                 "channel %d id %d \tSMID: 0x%x\n",
3700                                 channel, id, cmd_fusion->index);
3701                         scsi_print_command(cmd_fusion->scmd);
3702                         found = 1;
3703                         break;
3704                 }
3705         }
3706
3707         return found ? FAILED : SUCCESS;
3708 }
3709
3710 /**
3711  * megasas_tm_response_code - translation of device response code
3712  * @ioc: per adapter object
3713  * @mpi_reply: MPI reply returned by firmware
3714  *
3715  * Return nothing.
3716  */
3717 static void
3718 megasas_tm_response_code(struct megasas_instance *instance,
3719                 struct MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply)
3720 {
3721         char *desc;
3722
3723         switch (mpi_reply->ResponseCode) {
3724         case MPI2_SCSITASKMGMT_RSP_TM_COMPLETE:
3725                 desc = "task management request completed";
3726                 break;
3727         case MPI2_SCSITASKMGMT_RSP_INVALID_FRAME:
3728                 desc = "invalid frame";
3729                 break;
3730         case MPI2_SCSITASKMGMT_RSP_TM_NOT_SUPPORTED:
3731                 desc = "task management request not supported";
3732                 break;
3733         case MPI2_SCSITASKMGMT_RSP_TM_FAILED:
3734                 desc = "task management request failed";
3735                 break;
3736         case MPI2_SCSITASKMGMT_RSP_TM_SUCCEEDED:
3737                 desc = "task management request succeeded";
3738                 break;
3739         case MPI2_SCSITASKMGMT_RSP_TM_INVALID_LUN:
3740                 desc = "invalid lun";
3741                 break;
3742         case 0xA:
3743                 desc = "overlapped tag attempted";
3744                 break;
3745         case MPI2_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC:
3746                 desc = "task queued, however not sent to target";
3747                 break;
3748         default:
3749                 desc = "unknown";
3750                 break;
3751         }
3752         dev_dbg(&instance->pdev->dev, "response_code(%01x): %s\n",
3753                 mpi_reply->ResponseCode, desc);
3754         dev_dbg(&instance->pdev->dev,
3755                 "TerminationCount/DevHandle/Function/TaskType/IOCStat/IOCLoginfo"
3756                 " 0x%x/0x%x/0x%x/0x%x/0x%x/0x%x\n",
3757                 mpi_reply->TerminationCount, mpi_reply->DevHandle,
3758                 mpi_reply->Function, mpi_reply->TaskType,
3759                 mpi_reply->IOCStatus, mpi_reply->IOCLogInfo);
3760 }
3761
3762 /**
3763  * megasas_issue_tm - main routine for sending tm requests
3764  * @instance: per adapter struct
3765  * @device_handle: device handle
3766  * @channel: the channel assigned by the OS
3767  * @id: the id assigned by the OS
3768  * @type: MPI2_SCSITASKMGMT_TASKTYPE__XXX (defined in megaraid_sas_fusion.c)
3769  * @smid_task: smid assigned to the task
3770  * @m_type: TM_MUTEX_ON or TM_MUTEX_OFF
3771  * Context: user
3772  *
3773  * MegaRaid use MPT interface for Task Magement request.
3774  * A generic API for sending task management requests to firmware.
3775  *
3776  * Return SUCCESS or FAILED.
3777  */
3778 static int
3779 megasas_issue_tm(struct megasas_instance *instance, u16 device_handle,
3780         uint channel, uint id, u16 smid_task, u8 type)
3781 {
3782         struct MR_TASK_MANAGE_REQUEST *mr_request;
3783         struct MPI2_SCSI_TASK_MANAGE_REQUEST *mpi_request;
3784         unsigned long timeleft;
3785         struct megasas_cmd_fusion *cmd_fusion;
3786         struct megasas_cmd *cmd_mfi;
3787         union MEGASAS_REQUEST_DESCRIPTOR_UNION *req_desc;
3788         struct fusion_context *fusion = NULL;
3789         struct megasas_cmd_fusion *scsi_lookup;
3790         int rc;
3791         struct MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply;
3792
3793         fusion = instance->ctrl_context;
3794
3795         cmd_mfi = megasas_get_cmd(instance);
3796
3797         if (!cmd_mfi) {
3798                 dev_err(&instance->pdev->dev, "Failed from %s %d\n",
3799                         __func__, __LINE__);
3800                 return -ENOMEM;
3801         }
3802
3803         cmd_fusion = megasas_get_cmd_fusion(instance,
3804                         instance->max_scsi_cmds + cmd_mfi->index);
3805
3806         /*  Save the smid. To be used for returning the cmd */
3807         cmd_mfi->context.smid = cmd_fusion->index;
3808
3809         req_desc = megasas_get_request_descriptor(instance,
3810                         (cmd_fusion->index - 1));
3811
3812         cmd_fusion->request_desc = req_desc;
3813         req_desc->Words = 0;
3814
3815         mr_request = (struct MR_TASK_MANAGE_REQUEST *) cmd_fusion->io_request;
3816         memset(mr_request, 0, sizeof(struct MR_TASK_MANAGE_REQUEST));
3817         mpi_request = (struct MPI2_SCSI_TASK_MANAGE_REQUEST *) &mr_request->TmRequest;
3818         mpi_request->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
3819         mpi_request->DevHandle = cpu_to_le16(device_handle);
3820         mpi_request->TaskType = type;
3821         mpi_request->TaskMID = cpu_to_le16(smid_task);
3822         mpi_request->LUN[1] = 0;
3823
3824
3825         req_desc = cmd_fusion->request_desc;
3826         req_desc->HighPriority.SMID = cpu_to_le16(cmd_fusion->index);
3827         req_desc->HighPriority.RequestFlags =
3828                 (MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
3829                 MEGASAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
3830         req_desc->HighPriority.MSIxIndex =  0;
3831         req_desc->HighPriority.LMID = 0;
3832         req_desc->HighPriority.Reserved1 = 0;
3833
3834         if (channel < MEGASAS_MAX_PD_CHANNELS)
3835                 mr_request->tmReqFlags.isTMForPD = 1;
3836         else
3837                 mr_request->tmReqFlags.isTMForLD = 1;
3838
3839         init_completion(&cmd_fusion->done);
3840         megasas_fire_cmd_fusion(instance, req_desc);
3841
3842         timeleft = wait_for_completion_timeout(&cmd_fusion->done, 50 * HZ);
3843
3844         if (!timeleft) {
3845                 dev_err(&instance->pdev->dev,
3846                         "task mgmt type 0x%x timed out\n", type);
3847                 cmd_mfi->flags |= DRV_DCMD_SKIP_REFIRE;
3848                 mutex_unlock(&instance->reset_mutex);
3849                 rc = megasas_reset_fusion(instance->host, MFI_IO_TIMEOUT_OCR);
3850                 mutex_lock(&instance->reset_mutex);
3851                 return rc;
3852         }
3853
3854         mpi_reply = (struct MPI2_SCSI_TASK_MANAGE_REPLY *) &mr_request->TMReply;
3855         megasas_tm_response_code(instance, mpi_reply);
3856
3857         megasas_return_cmd(instance, cmd_mfi);
3858         rc = SUCCESS;
3859         switch (type) {
3860         case MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK:
3861                 scsi_lookup = fusion->cmd_list[smid_task - 1];
3862
3863                 if (scsi_lookup->scmd == NULL)
3864                         break;
3865                 else {
3866                         instance->instancet->disable_intr(instance);
3867                         megasas_sync_irqs((unsigned long)instance);
3868                         instance->instancet->enable_intr(instance);
3869                         if (scsi_lookup->scmd == NULL)
3870                                 break;
3871                 }
3872                 rc = FAILED;
3873                 break;
3874
3875         case MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET:
3876                 if ((channel == 0xFFFFFFFF) && (id == 0xFFFFFFFF))
3877                         break;
3878                 instance->instancet->disable_intr(instance);
3879                 megasas_sync_irqs((unsigned long)instance);
3880                 rc = megasas_track_scsiio(instance, id, channel);
3881                 instance->instancet->enable_intr(instance);
3882
3883                 break;
3884         case MPI2_SCSITASKMGMT_TASKTYPE_ABRT_TASK_SET:
3885         case MPI2_SCSITASKMGMT_TASKTYPE_QUERY_TASK:
3886                 break;
3887         default:
3888                 rc = FAILED;
3889                 break;
3890         }
3891
3892         return rc;
3893
3894 }
3895
3896 /*
3897  * megasas_fusion_smid_lookup : Look for fusion command correpspodning to SCSI
3898  * @instance: per adapter struct
3899  *
3900  * Return Non Zero index, if SMID found in outstanding commands
3901  */
3902 static u16 megasas_fusion_smid_lookup(struct scsi_cmnd *scmd)
3903 {
3904         int i, ret = 0;
3905         struct megasas_instance *instance;
3906         struct megasas_cmd_fusion *cmd_fusion;
3907         struct fusion_context *fusion;
3908
3909         instance = (struct megasas_instance *)scmd->device->host->hostdata;
3910
3911         fusion = instance->ctrl_context;
3912
3913         for (i = 0; i < instance->max_scsi_cmds; i++) {
3914                 cmd_fusion = fusion->cmd_list[i];
3915                 if (cmd_fusion->scmd && (cmd_fusion->scmd == scmd)) {
3916                         scmd_printk(KERN_NOTICE, scmd, "Abort request is for"
3917                                 " SMID: %d\n", cmd_fusion->index);
3918                         ret = cmd_fusion->index;
3919                         break;
3920                 }
3921         }
3922
3923         return ret;
3924 }
3925
3926 /*
3927 * megasas_get_tm_devhandle - Get devhandle for TM request
3928 * @sdev-                     OS provided scsi device
3929 *
3930 * Returns-                   devhandle/targetID of SCSI device
3931 */
3932 static u16 megasas_get_tm_devhandle(struct scsi_device *sdev)
3933 {
3934         u16 pd_index = 0;
3935         u32 device_id;
3936         struct megasas_instance *instance;
3937         struct fusion_context *fusion;
3938         struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
3939         u16 devhandle = (u16)ULONG_MAX;
3940
3941         instance = (struct megasas_instance *)sdev->host->hostdata;
3942         fusion = instance->ctrl_context;
3943
3944         if (!MEGASAS_IS_LOGICAL(sdev)) {
3945                 if (instance->use_seqnum_jbod_fp) {
3946                         pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL)
3947                                     + sdev->id;
3948                         pd_sync = (void *)fusion->pd_seq_sync
3949                                         [(instance->pd_seq_map_id - 1) & 1];
3950                         devhandle = pd_sync->seq[pd_index].devHandle;
3951                 } else
3952                         sdev_printk(KERN_ERR, sdev, "Firmware expose tmCapable"
3953                                 " without JBOD MAP support from %s %d\n", __func__, __LINE__);
3954         } else {
3955                 device_id = ((sdev->channel % 2) * MEGASAS_MAX_DEV_PER_CHANNEL)
3956                                 + sdev->id;
3957                 devhandle = device_id;
3958         }
3959
3960         return devhandle;
3961 }
3962
3963 /*
3964  * megasas_task_abort_fusion : SCSI task abort function for fusion adapters
3965  * @scmd : pointer to scsi command object
3966  *
3967  * Return SUCCESS, if command aborted else FAILED
3968  */
3969
3970 int megasas_task_abort_fusion(struct scsi_cmnd *scmd)
3971 {
3972         struct megasas_instance *instance;
3973         u16 smid, devhandle;
3974         struct fusion_context *fusion;
3975         int ret;
3976         struct MR_PRIV_DEVICE *mr_device_priv_data;
3977         mr_device_priv_data = scmd->device->hostdata;
3978
3979
3980         instance = (struct megasas_instance *)scmd->device->host->hostdata;
3981         fusion = instance->ctrl_context;
3982
3983         scmd_printk(KERN_INFO, scmd, "task abort called for scmd(%p)\n", scmd);
3984         scsi_print_command(scmd);
3985
3986         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
3987                 dev_err(&instance->pdev->dev, "Controller is not OPERATIONAL,"
3988                 "SCSI host:%d\n", instance->host->host_no);
3989                 ret = FAILED;
3990                 return ret;
3991         }
3992
3993         if (!mr_device_priv_data) {
3994                 sdev_printk(KERN_INFO, scmd->device, "device been deleted! "
3995                         "scmd(%p)\n", scmd);
3996                 scmd->result = DID_NO_CONNECT << 16;
3997                 ret = SUCCESS;
3998                 goto out;
3999         }
4000
4001
4002         if (!mr_device_priv_data->is_tm_capable) {
4003                 ret = FAILED;
4004                 goto out;
4005         }
4006
4007         mutex_lock(&instance->reset_mutex);
4008
4009         smid = megasas_fusion_smid_lookup(scmd);
4010
4011         if (!smid) {
4012                 ret = SUCCESS;
4013                 scmd_printk(KERN_NOTICE, scmd, "Command for which abort is"
4014                         " issued is not found in oustanding commands\n");
4015                 mutex_unlock(&instance->reset_mutex);
4016                 goto out;
4017         }
4018
4019         devhandle = megasas_get_tm_devhandle(scmd->device);
4020
4021         if (devhandle == (u16)ULONG_MAX) {
4022                 ret = SUCCESS;
4023                 sdev_printk(KERN_INFO, scmd->device,
4024                         "task abort issued for invalid devhandle\n");
4025                 mutex_unlock(&instance->reset_mutex);
4026                 goto out;
4027         }
4028         sdev_printk(KERN_INFO, scmd->device,
4029                 "attempting task abort! scmd(%p) tm_dev_handle 0x%x\n",
4030                 scmd, devhandle);
4031
4032         mr_device_priv_data->tm_busy = 1;
4033         ret = megasas_issue_tm(instance, devhandle,
4034                         scmd->device->channel, scmd->device->id, smid,
4035                         MPI2_SCSITASKMGMT_TASKTYPE_ABORT_TASK);
4036         mr_device_priv_data->tm_busy = 0;
4037
4038         mutex_unlock(&instance->reset_mutex);
4039 out:
4040         sdev_printk(KERN_INFO, scmd->device, "task abort: %s scmd(%p)\n",
4041                         ((ret == SUCCESS) ? "SUCCESS" : "FAILED"), scmd);
4042
4043         return ret;
4044 }
4045
4046 /*
4047  * megasas_reset_target_fusion : target reset function for fusion adapters
4048  * scmd: SCSI command pointer
4049  *
4050  * Returns SUCCESS if all commands associated with target aborted else FAILED
4051  */
4052
4053 int megasas_reset_target_fusion(struct scsi_cmnd *scmd)
4054 {
4055
4056         struct megasas_instance *instance;
4057         int ret = FAILED;
4058         u16 devhandle;
4059         struct fusion_context *fusion;
4060         struct MR_PRIV_DEVICE *mr_device_priv_data;
4061         mr_device_priv_data = scmd->device->hostdata;
4062
4063         instance = (struct megasas_instance *)scmd->device->host->hostdata;
4064         fusion = instance->ctrl_context;
4065
4066         sdev_printk(KERN_INFO, scmd->device,
4067                     "target reset called for scmd(%p)\n", scmd);
4068
4069         if (atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) {
4070                 dev_err(&instance->pdev->dev, "Controller is not OPERATIONAL,"
4071                 "SCSI host:%d\n", instance->host->host_no);
4072                 ret = FAILED;
4073                 return ret;
4074         }
4075
4076         if (!mr_device_priv_data) {
4077                 sdev_printk(KERN_INFO, scmd->device, "device been deleted! "
4078                         "scmd(%p)\n", scmd);
4079                 scmd->result = DID_NO_CONNECT << 16;
4080                 ret = SUCCESS;
4081                 goto out;
4082         }
4083
4084
4085         if (!mr_device_priv_data->is_tm_capable) {
4086                 ret = FAILED;
4087                 goto out;
4088         }
4089
4090         mutex_lock(&instance->reset_mutex);
4091         devhandle = megasas_get_tm_devhandle(scmd->device);
4092
4093         if (devhandle == (u16)ULONG_MAX) {
4094                 ret = SUCCESS;
4095                 sdev_printk(KERN_INFO, scmd->device,
4096                         "target reset issued for invalid devhandle\n");
4097                 mutex_unlock(&instance->reset_mutex);
4098                 goto out;
4099         }
4100
4101         sdev_printk(KERN_INFO, scmd->device,
4102                 "attempting target reset! scmd(%p) tm_dev_handle 0x%x\n",
4103                 scmd, devhandle);
4104         mr_device_priv_data->tm_busy = 1;
4105         ret = megasas_issue_tm(instance, devhandle,
4106                         scmd->device->channel, scmd->device->id, 0,
4107                         MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET);
4108         mr_device_priv_data->tm_busy = 0;
4109         mutex_unlock(&instance->reset_mutex);
4110 out:
4111         scmd_printk(KERN_NOTICE, scmd, "megasas: target reset %s!!\n",
4112                 (ret == SUCCESS) ? "SUCCESS" : "FAILED");
4113
4114         return ret;
4115 }
4116
4117 /*SRIOV get other instance in cluster if any*/
4118 struct megasas_instance *megasas_get_peer_instance(struct megasas_instance *instance)
4119 {
4120         int i;
4121
4122         for (i = 0; i < MAX_MGMT_ADAPTERS; i++) {
4123                 if (megasas_mgmt_info.instance[i] &&
4124                         (megasas_mgmt_info.instance[i] != instance) &&
4125                          megasas_mgmt_info.instance[i]->requestorId &&
4126                          megasas_mgmt_info.instance[i]->peerIsPresent &&
4127                         (memcmp((megasas_mgmt_info.instance[i]->clusterId),
4128                         instance->clusterId, MEGASAS_CLUSTER_ID_SIZE) == 0))
4129                         return megasas_mgmt_info.instance[i];
4130         }
4131         return NULL;
4132 }
4133
4134 /* Check for a second path that is currently UP */
4135 int megasas_check_mpio_paths(struct megasas_instance *instance,
4136         struct scsi_cmnd *scmd)
4137 {
4138         struct megasas_instance *peer_instance = NULL;
4139         int retval = (DID_REQUEUE << 16);
4140
4141         if (instance->peerIsPresent) {
4142                 peer_instance = megasas_get_peer_instance(instance);
4143                 if ((peer_instance) &&
4144                         (atomic_read(&peer_instance->adprecovery) ==
4145                         MEGASAS_HBA_OPERATIONAL))
4146                         retval = (DID_NO_CONNECT << 16);
4147         }
4148         return retval;
4149 }
4150
4151 /* Core fusion reset function */
4152 int megasas_reset_fusion(struct Scsi_Host *shost, int reason)
4153 {
4154         int retval = SUCCESS, i, j, convert = 0;
4155         struct megasas_instance *instance;
4156         struct megasas_cmd_fusion *cmd_fusion, *r1_cmd;
4157         struct fusion_context *fusion;
4158         u32 abs_state, status_reg, reset_adapter;
4159         u32 io_timeout_in_crash_mode = 0;
4160         struct scsi_cmnd *scmd_local = NULL;
4161         struct scsi_device *sdev;
4162
4163         instance = (struct megasas_instance *)shost->hostdata;
4164         fusion = instance->ctrl_context;
4165
4166         mutex_lock(&instance->reset_mutex);
4167
4168         if (atomic_read(&instance->adprecovery) == MEGASAS_HW_CRITICAL_ERROR) {
4169                 dev_warn(&instance->pdev->dev, "Hardware critical error, "
4170                        "returning FAILED for scsi%d.\n",
4171                         instance->host->host_no);
4172                 mutex_unlock(&instance->reset_mutex);
4173                 return FAILED;
4174         }
4175         status_reg = instance->instancet->read_fw_status_reg(instance->reg_set);
4176         abs_state = status_reg & MFI_STATE_MASK;
4177
4178         /* IO timeout detected, forcibly put FW in FAULT state */
4179         if (abs_state != MFI_STATE_FAULT && instance->crash_dump_buf &&
4180                 instance->crash_dump_app_support && reason) {
4181                 dev_info(&instance->pdev->dev, "IO/DCMD timeout is detected, "
4182                         "forcibly FAULT Firmware\n");
4183                 atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4184                 status_reg = readl(&instance->reg_set->doorbell);
4185                 writel(status_reg | MFI_STATE_FORCE_OCR,
4186                         &instance->reg_set->doorbell);
4187                 readl(&instance->reg_set->doorbell);
4188                 mutex_unlock(&instance->reset_mutex);
4189                 do {
4190                         ssleep(3);
4191                         io_timeout_in_crash_mode++;
4192                         dev_dbg(&instance->pdev->dev, "waiting for [%d] "
4193                                 "seconds for crash dump collection and OCR "
4194                                 "to be done\n", (io_timeout_in_crash_mode * 3));
4195                 } while ((atomic_read(&instance->adprecovery) != MEGASAS_HBA_OPERATIONAL) &&
4196                         (io_timeout_in_crash_mode < 80));
4197
4198                 if (atomic_read(&instance->adprecovery) == MEGASAS_HBA_OPERATIONAL) {
4199                         dev_info(&instance->pdev->dev, "OCR done for IO "
4200                                 "timeout case\n");
4201                         retval = SUCCESS;
4202                 } else {
4203                         dev_info(&instance->pdev->dev, "Controller is not "
4204                                 "operational after 240 seconds wait for IO "
4205                                 "timeout case in FW crash dump mode\n do "
4206                                 "OCR/kill adapter\n");
4207                         retval = megasas_reset_fusion(shost, 0);
4208                 }
4209                 return retval;
4210         }
4211
4212         if (instance->requestorId && !instance->skip_heartbeat_timer_del)
4213                 del_timer_sync(&instance->sriov_heartbeat_timer);
4214         set_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
4215         set_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE, &instance->reset_flags);
4216         atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_POLLING);
4217         instance->instancet->disable_intr(instance);
4218         megasas_sync_irqs((unsigned long)instance);
4219
4220         /* First try waiting for commands to complete */
4221         if (megasas_wait_for_outstanding_fusion(instance, reason,
4222                                                 &convert)) {
4223                 atomic_set(&instance->adprecovery, MEGASAS_ADPRESET_SM_INFAULT);
4224                 dev_warn(&instance->pdev->dev, "resetting fusion "
4225                        "adapter scsi%d.\n", instance->host->host_no);
4226                 if (convert)
4227                         reason = 0;
4228
4229                 if (megasas_dbg_lvl & OCR_LOGS)
4230                         dev_info(&instance->pdev->dev, "\nPending SCSI commands:\n");
4231
4232                 /* Now return commands back to the OS */
4233                 for (i = 0 ; i < instance->max_scsi_cmds; i++) {
4234                         cmd_fusion = fusion->cmd_list[i];
4235                         /*check for extra commands issued by driver*/
4236                         if (instance->adapter_type == VENTURA_SERIES) {
4237                                 r1_cmd = fusion->cmd_list[i + instance->max_fw_cmds];
4238                                 megasas_return_cmd_fusion(instance, r1_cmd);
4239                         }
4240                         scmd_local = cmd_fusion->scmd;
4241                         if (cmd_fusion->scmd) {
4242                                 if (megasas_dbg_lvl & OCR_LOGS) {
4243                                         sdev_printk(KERN_INFO,
4244                                                 cmd_fusion->scmd->device, "SMID: 0x%x\n",
4245                                                 cmd_fusion->index);
4246                                         scsi_print_command(cmd_fusion->scmd);
4247                                 }
4248
4249                                 scmd_local->result =
4250                                         megasas_check_mpio_paths(instance,
4251                                                         scmd_local);
4252                                 if (instance->ldio_threshold &&
4253                                         megasas_cmd_type(scmd_local) == READ_WRITE_LDIO)
4254                                         atomic_dec(&instance->ldio_outstanding);
4255                                 megasas_return_cmd_fusion(instance, cmd_fusion);
4256                                 scsi_dma_unmap(scmd_local);
4257                                 scmd_local->scsi_done(scmd_local);
4258                         }
4259                 }
4260
4261                 atomic_set(&instance->fw_outstanding, 0);
4262
4263                 status_reg = instance->instancet->read_fw_status_reg(
4264                         instance->reg_set);
4265                 abs_state = status_reg & MFI_STATE_MASK;
4266                 reset_adapter = status_reg & MFI_RESET_ADAPTER;
4267                 if (instance->disableOnlineCtrlReset ||
4268                     (abs_state == MFI_STATE_FAULT && !reset_adapter)) {
4269                         /* Reset not supported, kill adapter */
4270                         dev_warn(&instance->pdev->dev, "Reset not supported"
4271                                ", killing adapter scsi%d.\n",
4272                                 instance->host->host_no);
4273                         megaraid_sas_kill_hba(instance);
4274                         instance->skip_heartbeat_timer_del = 1;
4275                         retval = FAILED;
4276                         goto out;
4277                 }
4278
4279                 /* Let SR-IOV VF & PF sync up if there was a HB failure */
4280                 if (instance->requestorId && !reason) {
4281                         msleep(MEGASAS_OCR_SETTLE_TIME_VF);
4282                         goto transition_to_ready;
4283                 }
4284
4285                 /* Now try to reset the chip */
4286                 for (i = 0; i < MEGASAS_FUSION_MAX_RESET_TRIES; i++) {
4287
4288                         if (instance->instancet->adp_reset
4289                                 (instance, instance->reg_set))
4290                                 continue;
4291 transition_to_ready:
4292                         /* Wait for FW to become ready */
4293                         if (megasas_transition_to_ready(instance, 1)) {
4294                                 dev_warn(&instance->pdev->dev,
4295                                         "Failed to transition controller to ready for "
4296                                         "scsi%d.\n", instance->host->host_no);
4297                                 if (instance->requestorId && !reason)
4298                                         goto fail_kill_adapter;
4299                                 else
4300                                         continue;
4301                         }
4302                         megasas_reset_reply_desc(instance);
4303                         megasas_fusion_update_can_queue(instance, OCR_CONTEXT);
4304
4305                         if (megasas_ioc_init_fusion(instance)) {
4306                                 if (instance->requestorId && !reason)
4307                                         goto fail_kill_adapter;
4308                                 else
4309                                         continue;
4310                         }
4311
4312                         megasas_refire_mgmt_cmd(instance);
4313
4314                         if (megasas_get_ctrl_info(instance)) {
4315                                 dev_info(&instance->pdev->dev,
4316                                         "Failed from %s %d\n",
4317                                         __func__, __LINE__);
4318                                 megaraid_sas_kill_hba(instance);
4319                                 retval = FAILED;
4320                                 goto out;
4321                         }
4322                         /* Reset load balance info */
4323                         if (fusion->load_balance_info)
4324                                 memset(fusion->load_balance_info, 0,
4325                                        (sizeof(struct LD_LOAD_BALANCE_INFO) *
4326                                        MAX_LOGICAL_DRIVES_EXT));
4327
4328                         if (!megasas_get_map_info(instance))
4329                                 megasas_sync_map_info(instance);
4330
4331                         megasas_setup_jbod_map(instance);
4332
4333                         shost_for_each_device(sdev, shost)
4334                                 megasas_set_dynamic_target_properties(sdev);
4335
4336                         /* reset stream detection array */
4337                         if (instance->adapter_type == VENTURA_SERIES) {
4338                                 for (j = 0; j < MAX_LOGICAL_DRIVES_EXT; ++j) {
4339                                         memset(fusion->stream_detect_by_ld[j],
4340                                         0, sizeof(struct LD_STREAM_DETECT));
4341                                  fusion->stream_detect_by_ld[j]->mru_bit_map
4342                                                 = MR_STREAM_BITMAP;
4343                                 }
4344                         }
4345
4346                         clear_bit(MEGASAS_FUSION_IN_RESET,
4347                                   &instance->reset_flags);
4348                         instance->instancet->enable_intr(instance);
4349                         atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
4350
4351                         dev_info(&instance->pdev->dev, "Interrupts are enabled and"
4352                                 " controller is OPERATIONAL for scsi:%d\n",
4353                                 instance->host->host_no);
4354
4355                         /* Restart SR-IOV heartbeat */
4356                         if (instance->requestorId) {
4357                                 if (!megasas_sriov_start_heartbeat(instance, 0))
4358                                         megasas_start_timer(instance,
4359                                                             &instance->sriov_heartbeat_timer,
4360                                                             megasas_sriov_heartbeat_handler,
4361                                                             MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
4362                                 else
4363                                         instance->skip_heartbeat_timer_del = 1;
4364                         }
4365
4366                         if (instance->crash_dump_drv_support &&
4367                                 instance->crash_dump_app_support)
4368                                 megasas_set_crash_dump_params(instance,
4369                                         MR_CRASH_BUF_TURN_ON);
4370                         else
4371                                 megasas_set_crash_dump_params(instance,
4372                                         MR_CRASH_BUF_TURN_OFF);
4373
4374                         retval = SUCCESS;
4375
4376                         /* Adapter reset completed successfully */
4377                         dev_warn(&instance->pdev->dev,
4378                                  "Reset successful for scsi%d.\n",
4379                                  instance->host->host_no);
4380
4381                         goto out;
4382                 }
4383 fail_kill_adapter:
4384                 /* Reset failed, kill the adapter */
4385                 dev_warn(&instance->pdev->dev, "Reset failed, killing "
4386                        "adapter scsi%d.\n", instance->host->host_no);
4387                 megaraid_sas_kill_hba(instance);
4388                 instance->skip_heartbeat_timer_del = 1;
4389                 retval = FAILED;
4390         } else {
4391                 /* For VF: Restart HB timer if we didn't OCR */
4392                 if (instance->requestorId) {
4393                         megasas_start_timer(instance,
4394                                             &instance->sriov_heartbeat_timer,
4395                                             megasas_sriov_heartbeat_handler,
4396                                             MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
4397                 }
4398                 clear_bit(MEGASAS_FUSION_IN_RESET, &instance->reset_flags);
4399                 instance->instancet->enable_intr(instance);
4400                 atomic_set(&instance->adprecovery, MEGASAS_HBA_OPERATIONAL);
4401         }
4402 out:
4403         clear_bit(MEGASAS_FUSION_OCR_NOT_POSSIBLE, &instance->reset_flags);
4404         mutex_unlock(&instance->reset_mutex);
4405         return retval;
4406 }
4407
4408 /* Fusion Crash dump collection work queue */
4409 void  megasas_fusion_crash_dump_wq(struct work_struct *work)
4410 {
4411         struct megasas_instance *instance =
4412                 container_of(work, struct megasas_instance, crash_init);
4413         u32 status_reg;
4414         u8 partial_copy = 0;
4415
4416
4417         status_reg = instance->instancet->read_fw_status_reg(instance->reg_set);
4418
4419         /*
4420          * Allocate host crash buffers to copy data from 1 MB DMA crash buffer
4421          * to host crash buffers
4422          */
4423         if (instance->drv_buf_index == 0) {
4424                 /* Buffer is already allocated for old Crash dump.
4425                  * Do OCR and do not wait for crash dump collection
4426                  */
4427                 if (instance->drv_buf_alloc) {
4428                         dev_info(&instance->pdev->dev, "earlier crash dump is "
4429                                 "not yet copied by application, ignoring this "
4430                                 "crash dump and initiating OCR\n");
4431                         status_reg |= MFI_STATE_CRASH_DUMP_DONE;
4432                         writel(status_reg,
4433                                 &instance->reg_set->outbound_scratch_pad);
4434                         readl(&instance->reg_set->outbound_scratch_pad);
4435                         return;
4436                 }
4437                 megasas_alloc_host_crash_buffer(instance);
4438                 dev_info(&instance->pdev->dev, "Number of host crash buffers "
4439                         "allocated: %d\n", instance->drv_buf_alloc);
4440         }
4441
4442         /*
4443          * Driver has allocated max buffers, which can be allocated
4444          * and FW has more crash dump data, then driver will
4445          * ignore the data.
4446          */
4447         if (instance->drv_buf_index >= (instance->drv_buf_alloc)) {
4448                 dev_info(&instance->pdev->dev, "Driver is done copying "
4449                         "the buffer: %d\n", instance->drv_buf_alloc);
4450                 status_reg |= MFI_STATE_CRASH_DUMP_DONE;
4451                 partial_copy = 1;
4452         } else {
4453                 memcpy(instance->crash_buf[instance->drv_buf_index],
4454                         instance->crash_dump_buf, CRASH_DMA_BUF_SIZE);
4455                 instance->drv_buf_index++;
4456                 status_reg &= ~MFI_STATE_DMADONE;
4457         }
4458
4459         if (status_reg & MFI_STATE_CRASH_DUMP_DONE) {
4460                 dev_info(&instance->pdev->dev, "Crash Dump is available,number "
4461                         "of copied buffers: %d\n", instance->drv_buf_index);
4462                 instance->fw_crash_buffer_size =  instance->drv_buf_index;
4463                 instance->fw_crash_state = AVAILABLE;
4464                 instance->drv_buf_index = 0;
4465                 writel(status_reg, &instance->reg_set->outbound_scratch_pad);
4466                 readl(&instance->reg_set->outbound_scratch_pad);
4467                 if (!partial_copy)
4468                         megasas_reset_fusion(instance->host, 0);
4469         } else {
4470                 writel(status_reg, &instance->reg_set->outbound_scratch_pad);
4471                 readl(&instance->reg_set->outbound_scratch_pad);
4472         }
4473 }
4474
4475
4476 /* Fusion OCR work queue */
4477 void megasas_fusion_ocr_wq(struct work_struct *work)
4478 {
4479         struct megasas_instance *instance =
4480                 container_of(work, struct megasas_instance, work_init);
4481
4482         megasas_reset_fusion(instance->host, 0);
4483 }
4484
4485 /* Allocate fusion context */
4486 int
4487 megasas_alloc_fusion_context(struct megasas_instance *instance)
4488 {
4489         struct fusion_context *fusion;
4490
4491         instance->ctrl_context_pages = get_order(sizeof(struct fusion_context));
4492         instance->ctrl_context = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
4493                 instance->ctrl_context_pages);
4494         if (!instance->ctrl_context) {
4495                 /* fall back to using vmalloc for fusion_context */
4496                 instance->ctrl_context = vzalloc(sizeof(struct fusion_context));
4497                 if (!instance->ctrl_context) {
4498                         dev_err(&instance->pdev->dev, "Failed from %s %d\n", __func__, __LINE__);
4499                         return -ENOMEM;
4500                 }
4501         }
4502
4503         fusion = instance->ctrl_context;
4504
4505         fusion->load_balance_info_pages = get_order(MAX_LOGICAL_DRIVES_EXT *
4506                 sizeof(struct LD_LOAD_BALANCE_INFO));
4507         fusion->load_balance_info =
4508                 (struct LD_LOAD_BALANCE_INFO *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
4509                 fusion->load_balance_info_pages);
4510         if (!fusion->load_balance_info) {
4511                 fusion->load_balance_info = vzalloc(MAX_LOGICAL_DRIVES_EXT *
4512                         sizeof(struct LD_LOAD_BALANCE_INFO));
4513                 if (!fusion->load_balance_info)
4514                         dev_err(&instance->pdev->dev, "Failed to allocate load_balance_info, "
4515                                 "continuing without Load Balance support\n");
4516         }
4517
4518         return 0;
4519 }
4520
4521 void
4522 megasas_free_fusion_context(struct megasas_instance *instance)
4523 {
4524         struct fusion_context *fusion = instance->ctrl_context;
4525
4526         if (fusion) {
4527                 if (fusion->load_balance_info) {
4528                         if (is_vmalloc_addr(fusion->load_balance_info))
4529                                 vfree(fusion->load_balance_info);
4530                         else
4531                                 free_pages((ulong)fusion->load_balance_info,
4532                                         fusion->load_balance_info_pages);
4533                 }
4534
4535                 if (is_vmalloc_addr(fusion))
4536                         vfree(fusion);
4537                 else
4538                         free_pages((ulong)fusion,
4539                                 instance->ctrl_context_pages);
4540         }
4541 }
4542
4543 struct megasas_instance_template megasas_instance_template_fusion = {
4544         .enable_intr = megasas_enable_intr_fusion,
4545         .disable_intr = megasas_disable_intr_fusion,
4546         .clear_intr = megasas_clear_intr_fusion,
4547         .read_fw_status_reg = megasas_read_fw_status_reg_fusion,
4548         .adp_reset = megasas_adp_reset_fusion,
4549         .check_reset = megasas_check_reset_fusion,
4550         .service_isr = megasas_isr_fusion,
4551         .tasklet = megasas_complete_cmd_dpc_fusion,
4552         .init_adapter = megasas_init_adapter_fusion,
4553         .build_and_issue_cmd = megasas_build_and_issue_cmd_fusion,
4554         .issue_dcmd = megasas_issue_dcmd_fusion,
4555 };