OSDN Git Service

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