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