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