[SCSI] megaraid_sas: frame count optimization
[pandora-kernel.git] / drivers / scsi / megaraid / megaraid_sas.c
1 /*
2  *
3  *              Linux MegaRAID driver for SAS based RAID controllers
4  *
5  * Copyright (c) 2003-2005  LSI Logic Corporation.
6  *
7  *         This program is free software; you can redistribute it and/or
8  *         modify it under the terms of the GNU General Public License
9  *         as published by the Free Software Foundation; either version
10  *         2 of the License, or (at your option) any later version.
11  *
12  * FILE         : megaraid_sas.c
13  * Version      : v00.00.03.01
14  *
15  * Authors:
16  *      Sreenivas Bagalkote     <Sreenivas.Bagalkote@lsil.com>
17  *      Sumant Patro            <Sumant.Patro@lsil.com>
18  *
19  * List of supported controllers
20  *
21  * OEM  Product Name                    VID     DID     SSVID   SSID
22  * ---  ------------                    ---     ---     ----    ----
23  */
24
25 #include <linux/kernel.h>
26 #include <linux/types.h>
27 #include <linux/pci.h>
28 #include <linux/list.h>
29 #include <linux/moduleparam.h>
30 #include <linux/module.h>
31 #include <linux/spinlock.h>
32 #include <linux/interrupt.h>
33 #include <linux/delay.h>
34 #include <linux/uio.h>
35 #include <asm/uaccess.h>
36 #include <linux/fs.h>
37 #include <linux/compat.h>
38 #include <linux/mutex.h>
39
40 #include <scsi/scsi.h>
41 #include <scsi/scsi_cmnd.h>
42 #include <scsi/scsi_device.h>
43 #include <scsi/scsi_host.h>
44 #include "megaraid_sas.h"
45
46 MODULE_LICENSE("GPL");
47 MODULE_VERSION(MEGASAS_VERSION);
48 MODULE_AUTHOR("sreenivas.bagalkote@lsil.com");
49 MODULE_DESCRIPTION("LSI Logic MegaRAID SAS Driver");
50
51 /*
52  * PCI ID table for all supported controllers
53  */
54 static struct pci_device_id megasas_pci_table[] = {
55
56         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
57         /* xscale IOP */
58         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
59         /* ppc IOP */
60         {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
61         /* xscale IOP, vega */
62         {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
63         /* xscale IOP */
64         {}
65 };
66
67 MODULE_DEVICE_TABLE(pci, megasas_pci_table);
68
69 static int megasas_mgmt_majorno;
70 static struct megasas_mgmt_info megasas_mgmt_info;
71 static struct fasync_struct *megasas_async_queue;
72 static DEFINE_MUTEX(megasas_async_queue_mutex);
73
74 /**
75  * megasas_get_cmd -    Get a command from the free pool
76  * @instance:           Adapter soft state
77  *
78  * Returns a free command from the pool
79  */
80 static struct megasas_cmd *megasas_get_cmd(struct megasas_instance
81                                                   *instance)
82 {
83         unsigned long flags;
84         struct megasas_cmd *cmd = NULL;
85
86         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
87
88         if (!list_empty(&instance->cmd_pool)) {
89                 cmd = list_entry((&instance->cmd_pool)->next,
90                                  struct megasas_cmd, list);
91                 list_del_init(&cmd->list);
92         } else {
93                 printk(KERN_ERR "megasas: Command pool empty!\n");
94         }
95
96         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
97         return cmd;
98 }
99
100 /**
101  * megasas_return_cmd - Return a cmd to free command pool
102  * @instance:           Adapter soft state
103  * @cmd:                Command packet to be returned to free command pool
104  */
105 static inline void
106 megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
107 {
108         unsigned long flags;
109
110         spin_lock_irqsave(&instance->cmd_pool_lock, flags);
111
112         cmd->scmd = NULL;
113         list_add_tail(&cmd->list, &instance->cmd_pool);
114
115         spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
116 }
117
118
119 /**
120 *       The following functions are defined for xscale 
121 *       (deviceid : 1064R, PERC5) controllers
122 */
123
124 /**
125  * megasas_enable_intr_xscale - Enables interrupts
126  * @regs:                       MFI register set
127  */
128 static inline void
129 megasas_enable_intr_xscale(struct megasas_register_set __iomem * regs)
130 {
131         writel(1, &(regs)->outbound_intr_mask);
132
133         /* Dummy readl to force pci flush */
134         readl(&regs->outbound_intr_mask);
135 }
136
137 /**
138  * megasas_read_fw_status_reg_xscale - returns the current FW status value
139  * @regs:                       MFI register set
140  */
141 static u32
142 megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
143 {
144         return readl(&(regs)->outbound_msg_0);
145 }
146 /**
147  * megasas_clear_interrupt_xscale -     Check & clear interrupt
148  * @regs:                               MFI register set
149  */
150 static int 
151 megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
152 {
153         u32 status;
154         /*
155          * Check if it is our interrupt
156          */
157         status = readl(&regs->outbound_intr_status);
158
159         if (!(status & MFI_OB_INTR_STATUS_MASK)) {
160                 return 1;
161         }
162
163         /*
164          * Clear the interrupt by writing back the same value
165          */
166         writel(status, &regs->outbound_intr_status);
167
168         return 0;
169 }
170
171 /**
172  * megasas_fire_cmd_xscale -    Sends command to the FW
173  * @frame_phys_addr :           Physical address of cmd
174  * @frame_count :               Number of frames for the command
175  * @regs :                      MFI register set
176  */
177 static inline void 
178 megasas_fire_cmd_xscale(dma_addr_t frame_phys_addr,u32 frame_count, struct megasas_register_set __iomem *regs)
179 {
180         writel((frame_phys_addr >> 3)|(frame_count),
181                &(regs)->inbound_queue_port);
182 }
183
184 static struct megasas_instance_template megasas_instance_template_xscale = {
185
186         .fire_cmd = megasas_fire_cmd_xscale,
187         .enable_intr = megasas_enable_intr_xscale,
188         .clear_intr = megasas_clear_intr_xscale,
189         .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
190 };
191
192 /**
193 *       This is the end of set of functions & definitions specific 
194 *       to xscale (deviceid : 1064R, PERC5) controllers
195 */
196
197 /**
198 *       The following functions are defined for ppc (deviceid : 0x60) 
199 *       controllers
200 */
201
202 /**
203  * megasas_enable_intr_ppc -    Enables interrupts
204  * @regs:                       MFI register set
205  */
206 static inline void
207 megasas_enable_intr_ppc(struct megasas_register_set __iomem * regs)
208 {
209         writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
210     
211         writel(~0x80000004, &(regs)->outbound_intr_mask);
212
213         /* Dummy readl to force pci flush */
214         readl(&regs->outbound_intr_mask);
215 }
216
217 /**
218  * megasas_read_fw_status_reg_ppc - returns the current FW status value
219  * @regs:                       MFI register set
220  */
221 static u32
222 megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
223 {
224         return readl(&(regs)->outbound_scratch_pad);
225 }
226
227 /**
228  * megasas_clear_interrupt_ppc -        Check & clear interrupt
229  * @regs:                               MFI register set
230  */
231 static int 
232 megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
233 {
234         u32 status;
235         /*
236          * Check if it is our interrupt
237          */
238         status = readl(&regs->outbound_intr_status);
239
240         if (!(status & MFI_REPLY_1078_MESSAGE_INTERRUPT)) {
241                 return 1;
242         }
243
244         /*
245          * Clear the interrupt by writing back the same value
246          */
247         writel(status, &regs->outbound_doorbell_clear);
248
249         return 0;
250 }
251 /**
252  * megasas_fire_cmd_ppc -       Sends command to the FW
253  * @frame_phys_addr :           Physical address of cmd
254  * @frame_count :               Number of frames for the command
255  * @regs :                      MFI register set
256  */
257 static inline void 
258 megasas_fire_cmd_ppc(dma_addr_t frame_phys_addr, u32 frame_count, struct megasas_register_set __iomem *regs)
259 {
260         writel((frame_phys_addr | (frame_count<<1))|1, 
261                         &(regs)->inbound_queue_port);
262 }
263
264 static struct megasas_instance_template megasas_instance_template_ppc = {
265         
266         .fire_cmd = megasas_fire_cmd_ppc,
267         .enable_intr = megasas_enable_intr_ppc,
268         .clear_intr = megasas_clear_intr_ppc,
269         .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
270 };
271
272 /**
273 *       This is the end of set of functions & definitions
274 *       specific to ppc (deviceid : 0x60) controllers
275 */
276
277 /**
278  * megasas_disable_intr -       Disables interrupts
279  * @regs:                       MFI register set
280  */
281 static inline void
282 megasas_disable_intr(struct megasas_instance *instance)
283 {
284         u32 mask = 0x1f; 
285         struct megasas_register_set __iomem *regs = instance->reg_set;
286
287         if(instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1078R)
288                 mask = 0xffffffff;
289
290         writel(mask, &regs->outbound_intr_mask);
291
292         /* Dummy readl to force pci flush */
293         readl(&regs->outbound_intr_mask);
294 }
295
296 /**
297  * megasas_issue_polled -       Issues a polling command
298  * @instance:                   Adapter soft state
299  * @cmd:                        Command packet to be issued 
300  *
301  * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
302  */
303 static int
304 megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
305 {
306         int i;
307         u32 msecs = MFI_POLL_TIMEOUT_SECS * 1000;
308
309         struct megasas_header *frame_hdr = &cmd->frame->hdr;
310
311         frame_hdr->cmd_status = 0xFF;
312         frame_hdr->flags |= MFI_FRAME_DONT_POST_IN_REPLY_QUEUE;
313
314         /*
315          * Issue the frame using inbound queue port
316          */
317         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
318
319         /*
320          * Wait for cmd_status to change
321          */
322         for (i = 0; (i < msecs) && (frame_hdr->cmd_status == 0xff); i++) {
323                 rmb();
324                 msleep(1);
325         }
326
327         if (frame_hdr->cmd_status == 0xff)
328                 return -ETIME;
329
330         return 0;
331 }
332
333 /**
334  * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
335  * @instance:                   Adapter soft state
336  * @cmd:                        Command to be issued
337  *
338  * This function waits on an event for the command to be returned from ISR.
339  * Used to issue ioctl commands.
340  */
341 static int
342 megasas_issue_blocked_cmd(struct megasas_instance *instance,
343                           struct megasas_cmd *cmd)
344 {
345         cmd->cmd_status = ENODATA;
346
347         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
348
349         wait_event(instance->int_cmd_wait_q, (cmd->cmd_status != ENODATA));
350
351         return 0;
352 }
353
354 /**
355  * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
356  * @instance:                           Adapter soft state
357  * @cmd_to_abort:                       Previously issued cmd to be aborted
358  *
359  * MFI firmware can abort previously issued AEN comamnd (automatic event
360  * notification). The megasas_issue_blocked_abort_cmd() issues such abort
361  * cmd and blocks till it is completed.
362  */
363 static int
364 megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
365                                 struct megasas_cmd *cmd_to_abort)
366 {
367         struct megasas_cmd *cmd;
368         struct megasas_abort_frame *abort_fr;
369
370         cmd = megasas_get_cmd(instance);
371
372         if (!cmd)
373                 return -1;
374
375         abort_fr = &cmd->frame->abort;
376
377         /*
378          * Prepare and issue the abort frame
379          */
380         abort_fr->cmd = MFI_CMD_ABORT;
381         abort_fr->cmd_status = 0xFF;
382         abort_fr->flags = 0;
383         abort_fr->abort_context = cmd_to_abort->index;
384         abort_fr->abort_mfi_phys_addr_lo = cmd_to_abort->frame_phys_addr;
385         abort_fr->abort_mfi_phys_addr_hi = 0;
386
387         cmd->sync_cmd = 1;
388         cmd->cmd_status = 0xFF;
389
390         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
391
392         /*
393          * Wait for this cmd to complete
394          */
395         wait_event(instance->abort_cmd_wait_q, (cmd->cmd_status != 0xFF));
396
397         megasas_return_cmd(instance, cmd);
398         return 0;
399 }
400
401 /**
402  * megasas_make_sgl32 - Prepares 32-bit SGL
403  * @instance:           Adapter soft state
404  * @scp:                SCSI command from the mid-layer
405  * @mfi_sgl:            SGL to be filled in
406  *
407  * If successful, this function returns the number of SG elements. Otherwise,
408  * it returnes -1.
409  */
410 static int
411 megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
412                    union megasas_sgl *mfi_sgl)
413 {
414         int i;
415         int sge_count;
416         struct scatterlist *os_sgl;
417
418         /*
419          * Return 0 if there is no data transfer
420          */
421         if (!scp->request_buffer || !scp->request_bufflen)
422                 return 0;
423
424         if (!scp->use_sg) {
425                 mfi_sgl->sge32[0].phys_addr = pci_map_single(instance->pdev,
426                                                              scp->
427                                                              request_buffer,
428                                                              scp->
429                                                              request_bufflen,
430                                                              scp->
431                                                              sc_data_direction);
432                 mfi_sgl->sge32[0].length = scp->request_bufflen;
433
434                 return 1;
435         }
436
437         os_sgl = (struct scatterlist *)scp->request_buffer;
438         sge_count = pci_map_sg(instance->pdev, os_sgl, scp->use_sg,
439                                scp->sc_data_direction);
440
441         for (i = 0; i < sge_count; i++, os_sgl++) {
442                 mfi_sgl->sge32[i].length = sg_dma_len(os_sgl);
443                 mfi_sgl->sge32[i].phys_addr = sg_dma_address(os_sgl);
444         }
445
446         return sge_count;
447 }
448
449 /**
450  * megasas_make_sgl64 - Prepares 64-bit SGL
451  * @instance:           Adapter soft state
452  * @scp:                SCSI command from the mid-layer
453  * @mfi_sgl:            SGL to be filled in
454  *
455  * If successful, this function returns the number of SG elements. Otherwise,
456  * it returnes -1.
457  */
458 static int
459 megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
460                    union megasas_sgl *mfi_sgl)
461 {
462         int i;
463         int sge_count;
464         struct scatterlist *os_sgl;
465
466         /*
467          * Return 0 if there is no data transfer
468          */
469         if (!scp->request_buffer || !scp->request_bufflen)
470                 return 0;
471
472         if (!scp->use_sg) {
473                 mfi_sgl->sge64[0].phys_addr = pci_map_single(instance->pdev,
474                                                              scp->
475                                                              request_buffer,
476                                                              scp->
477                                                              request_bufflen,
478                                                              scp->
479                                                              sc_data_direction);
480
481                 mfi_sgl->sge64[0].length = scp->request_bufflen;
482
483                 return 1;
484         }
485
486         os_sgl = (struct scatterlist *)scp->request_buffer;
487         sge_count = pci_map_sg(instance->pdev, os_sgl, scp->use_sg,
488                                scp->sc_data_direction);
489
490         for (i = 0; i < sge_count; i++, os_sgl++) {
491                 mfi_sgl->sge64[i].length = sg_dma_len(os_sgl);
492                 mfi_sgl->sge64[i].phys_addr = sg_dma_address(os_sgl);
493         }
494
495         return sge_count;
496 }
497
498  /**
499  * megasas_get_frame_count - Computes the number of frames
500  * @sge_count           : number of sg elements
501  *
502  * Returns the number of frames required for numnber of sge's (sge_count)
503  */
504
505 u32 megasas_get_frame_count(u8 sge_count)
506 {
507         int num_cnt;
508         int sge_bytes;
509         u32 sge_sz;
510         u32 frame_count=0;
511
512         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
513             sizeof(struct megasas_sge32);
514
515         /*
516         * Main frame can contain 2 SGEs for 64-bit SGLs and
517         * 3 SGEs for 32-bit SGLs
518         */
519         if (IS_DMA64)
520                 num_cnt = sge_count - 2;
521         else
522                 num_cnt = sge_count - 3;
523
524         if(num_cnt>0){
525                 sge_bytes = sge_sz * num_cnt;
526
527                 frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
528                     ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
529         }
530         /* Main frame */
531         frame_count +=1;
532
533         if (frame_count > 7)
534                 frame_count = 8;
535         return frame_count;
536 }
537
538 /**
539  * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
540  * @instance:           Adapter soft state
541  * @scp:                SCSI command
542  * @cmd:                Command to be prepared in
543  *
544  * This function prepares CDB commands. These are typcially pass-through
545  * commands to the devices.
546  */
547 static int
548 megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
549                    struct megasas_cmd *cmd)
550 {
551         u32 is_logical;
552         u32 device_id;
553         u16 flags = 0;
554         struct megasas_pthru_frame *pthru;
555
556         is_logical = MEGASAS_IS_LOGICAL(scp);
557         device_id = MEGASAS_DEV_INDEX(instance, scp);
558         pthru = (struct megasas_pthru_frame *)cmd->frame;
559
560         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
561                 flags = MFI_FRAME_DIR_WRITE;
562         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
563                 flags = MFI_FRAME_DIR_READ;
564         else if (scp->sc_data_direction == PCI_DMA_NONE)
565                 flags = MFI_FRAME_DIR_NONE;
566
567         /*
568          * Prepare the DCDB frame
569          */
570         pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
571         pthru->cmd_status = 0x0;
572         pthru->scsi_status = 0x0;
573         pthru->target_id = device_id;
574         pthru->lun = scp->device->lun;
575         pthru->cdb_len = scp->cmd_len;
576         pthru->timeout = 0;
577         pthru->flags = flags;
578         pthru->data_xfer_len = scp->request_bufflen;
579
580         memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
581
582         /*
583          * Construct SGL
584          */
585         if (IS_DMA64) {
586                 pthru->flags |= MFI_FRAME_SGL64;
587                 pthru->sge_count = megasas_make_sgl64(instance, scp,
588                                                       &pthru->sgl);
589         } else
590                 pthru->sge_count = megasas_make_sgl32(instance, scp,
591                                                       &pthru->sgl);
592
593         /*
594          * Sense info specific
595          */
596         pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
597         pthru->sense_buf_phys_addr_hi = 0;
598         pthru->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
599
600         /*
601          * Compute the total number of frames this command consumes. FW uses
602          * this number to pull sufficient number of frames from host memory.
603          */
604         cmd->frame_count = megasas_get_frame_count(pthru->sge_count);
605
606         return cmd->frame_count;
607 }
608
609 /**
610  * megasas_build_ldio - Prepares IOs to logical devices
611  * @instance:           Adapter soft state
612  * @scp:                SCSI command
613  * @cmd:                Command to to be prepared
614  *
615  * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
616  */
617 static int
618 megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
619                    struct megasas_cmd *cmd)
620 {
621         u32 device_id;
622         u8 sc = scp->cmnd[0];
623         u16 flags = 0;
624         struct megasas_io_frame *ldio;
625
626         device_id = MEGASAS_DEV_INDEX(instance, scp);
627         ldio = (struct megasas_io_frame *)cmd->frame;
628
629         if (scp->sc_data_direction == PCI_DMA_TODEVICE)
630                 flags = MFI_FRAME_DIR_WRITE;
631         else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
632                 flags = MFI_FRAME_DIR_READ;
633
634         /*
635          * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
636          */
637         ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
638         ldio->cmd_status = 0x0;
639         ldio->scsi_status = 0x0;
640         ldio->target_id = device_id;
641         ldio->timeout = 0;
642         ldio->reserved_0 = 0;
643         ldio->pad_0 = 0;
644         ldio->flags = flags;
645         ldio->start_lba_hi = 0;
646         ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
647
648         /*
649          * 6-byte READ(0x08) or WRITE(0x0A) cdb
650          */
651         if (scp->cmd_len == 6) {
652                 ldio->lba_count = (u32) scp->cmnd[4];
653                 ldio->start_lba_lo = ((u32) scp->cmnd[1] << 16) |
654                     ((u32) scp->cmnd[2] << 8) | (u32) scp->cmnd[3];
655
656                 ldio->start_lba_lo &= 0x1FFFFF;
657         }
658
659         /*
660          * 10-byte READ(0x28) or WRITE(0x2A) cdb
661          */
662         else if (scp->cmd_len == 10) {
663                 ldio->lba_count = (u32) scp->cmnd[8] |
664                     ((u32) scp->cmnd[7] << 8);
665                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
666                     ((u32) scp->cmnd[3] << 16) |
667                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
668         }
669
670         /*
671          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
672          */
673         else if (scp->cmd_len == 12) {
674                 ldio->lba_count = ((u32) scp->cmnd[6] << 24) |
675                     ((u32) scp->cmnd[7] << 16) |
676                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
677
678                 ldio->start_lba_lo = ((u32) scp->cmnd[2] << 24) |
679                     ((u32) scp->cmnd[3] << 16) |
680                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
681         }
682
683         /*
684          * 16-byte READ(0x88) or WRITE(0x8A) cdb
685          */
686         else if (scp->cmd_len == 16) {
687                 ldio->lba_count = ((u32) scp->cmnd[10] << 24) |
688                     ((u32) scp->cmnd[11] << 16) |
689                     ((u32) scp->cmnd[12] << 8) | (u32) scp->cmnd[13];
690
691                 ldio->start_lba_lo = ((u32) scp->cmnd[6] << 24) |
692                     ((u32) scp->cmnd[7] << 16) |
693                     ((u32) scp->cmnd[8] << 8) | (u32) scp->cmnd[9];
694
695                 ldio->start_lba_hi = ((u32) scp->cmnd[2] << 24) |
696                     ((u32) scp->cmnd[3] << 16) |
697                     ((u32) scp->cmnd[4] << 8) | (u32) scp->cmnd[5];
698
699         }
700
701         /*
702          * Construct SGL
703          */
704         if (IS_DMA64) {
705                 ldio->flags |= MFI_FRAME_SGL64;
706                 ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
707         } else
708                 ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
709
710         /*
711          * Sense info specific
712          */
713         ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
714         ldio->sense_buf_phys_addr_hi = 0;
715         ldio->sense_buf_phys_addr_lo = cmd->sense_phys_addr;
716
717         /*
718          * Compute the total number of frames this command consumes. FW uses
719          * this number to pull sufficient number of frames from host memory.
720          */
721         cmd->frame_count = megasas_get_frame_count(ldio->sge_count);
722
723         return cmd->frame_count;
724 }
725
726 /**
727  * megasas_is_ldio -            Checks if the cmd is for logical drive
728  * @scmd:                       SCSI command
729  *      
730  * Called by megasas_queue_command to find out if the command to be queued
731  * is a logical drive command   
732  */
733 static inline int megasas_is_ldio(struct scsi_cmnd *cmd)
734 {
735         if (!MEGASAS_IS_LOGICAL(cmd))
736                 return 0;
737         switch (cmd->cmnd[0]) {
738         case READ_10:
739         case WRITE_10:
740         case READ_12:
741         case WRITE_12:
742         case READ_6:
743         case WRITE_6:
744         case READ_16:
745         case WRITE_16:
746                 return 1;
747         default:
748                 return 0;
749         }
750 }
751
752 /**
753  * megasas_queue_command -      Queue entry point
754  * @scmd:                       SCSI command to be queued
755  * @done:                       Callback entry point
756  */
757 static int
758 megasas_queue_command(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
759 {
760         u32 frame_count;
761         struct megasas_cmd *cmd;
762         struct megasas_instance *instance;
763
764         instance = (struct megasas_instance *)
765             scmd->device->host->hostdata;
766         scmd->scsi_done = done;
767         scmd->result = 0;
768
769         if (MEGASAS_IS_LOGICAL(scmd) &&
770             (scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
771                 scmd->result = DID_BAD_TARGET << 16;
772                 goto out_done;
773         }
774
775         cmd = megasas_get_cmd(instance);
776         if (!cmd)
777                 return SCSI_MLQUEUE_HOST_BUSY;
778
779         /*
780          * Logical drive command
781          */
782         if (megasas_is_ldio(scmd))
783                 frame_count = megasas_build_ldio(instance, scmd, cmd);
784         else
785                 frame_count = megasas_build_dcdb(instance, scmd, cmd);
786
787         if (!frame_count)
788                 goto out_return_cmd;
789
790         cmd->scmd = scmd;
791
792         /*
793          * Issue the command to the FW
794          */
795         atomic_inc(&instance->fw_outstanding);
796
797         instance->instancet->fire_cmd(cmd->frame_phys_addr ,cmd->frame_count-1,instance->reg_set);
798
799         return 0;
800
801  out_return_cmd:
802         megasas_return_cmd(instance, cmd);
803  out_done:
804         done(scmd);
805         return 0;
806 }
807
808 static int megasas_slave_configure(struct scsi_device *sdev)
809 {
810         /*
811          * Don't export physical disk devices to the disk driver.
812          *
813          * FIXME: Currently we don't export them to the midlayer at all.
814          *        That will be fixed once LSI engineers have audited the
815          *        firmware for possible issues.
816          */
817         if (sdev->channel < MEGASAS_MAX_PD_CHANNELS && sdev->type == TYPE_DISK)
818                 return -ENXIO;
819
820         /*
821          * The RAID firmware may require extended timeouts.
822          */
823         if (sdev->channel >= MEGASAS_MAX_PD_CHANNELS)
824                 sdev->timeout = 90 * HZ;
825         return 0;
826 }
827
828 /**
829  * megasas_wait_for_outstanding -       Wait for all outstanding cmds
830  * @instance:                           Adapter soft state
831  *
832  * This function waits for upto MEGASAS_RESET_WAIT_TIME seconds for FW to
833  * complete all its outstanding commands. Returns error if one or more IOs
834  * are pending after this time period. It also marks the controller dead.
835  */
836 static int megasas_wait_for_outstanding(struct megasas_instance *instance)
837 {
838         int i;
839         u32 wait_time = MEGASAS_RESET_WAIT_TIME;
840
841         for (i = 0; i < wait_time; i++) {
842
843                 int outstanding = atomic_read(&instance->fw_outstanding);
844
845                 if (!outstanding)
846                         break;
847
848                 if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
849                         printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
850                                "commands to complete\n",i,outstanding);
851                 }
852
853                 msleep(1000);
854         }
855
856         if (atomic_read(&instance->fw_outstanding)) {
857                 /*
858                 * Send signal to FW to stop processing any pending cmds.
859                 * The controller will be taken offline by the OS now.
860                 */
861                 writel(MFI_STOP_ADP,
862                                 &instance->reg_set->inbound_doorbell);
863                 instance->hw_crit_error = 1;
864                 return FAILED;
865         }
866
867         return SUCCESS;
868 }
869
870 /**
871  * megasas_generic_reset -      Generic reset routine
872  * @scmd:                       Mid-layer SCSI command
873  *
874  * This routine implements a generic reset handler for device, bus and host
875  * reset requests. Device, bus and host specific reset handlers can use this
876  * function after they do their specific tasks.
877  */
878 static int megasas_generic_reset(struct scsi_cmnd *scmd)
879 {
880         int ret_val;
881         struct megasas_instance *instance;
882
883         instance = (struct megasas_instance *)scmd->device->host->hostdata;
884
885         scmd_printk(KERN_NOTICE, scmd, "megasas: RESET -%ld cmd=%x\n",
886                scmd->serial_number, scmd->cmnd[0]);
887
888         if (instance->hw_crit_error) {
889                 printk(KERN_ERR "megasas: cannot recover from previous reset "
890                        "failures\n");
891                 return FAILED;
892         }
893
894         ret_val = megasas_wait_for_outstanding(instance);
895         if (ret_val == SUCCESS)
896                 printk(KERN_NOTICE "megasas: reset successful \n");
897         else
898                 printk(KERN_ERR "megasas: failed to do reset\n");
899
900         return ret_val;
901 }
902
903 /**
904  * megasas_reset_device -       Device reset handler entry point
905  */
906 static int megasas_reset_device(struct scsi_cmnd *scmd)
907 {
908         int ret;
909
910         /*
911          * First wait for all commands to complete
912          */
913         ret = megasas_generic_reset(scmd);
914
915         return ret;
916 }
917
918 /**
919  * megasas_reset_bus_host -     Bus & host reset handler entry point
920  */
921 static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
922 {
923         int ret;
924
925         /*
926          * First wait for all commands to complete
927          */
928         ret = megasas_generic_reset(scmd);
929
930         return ret;
931 }
932
933 /**
934  * megasas_service_aen -        Processes an event notification
935  * @instance:                   Adapter soft state
936  * @cmd:                        AEN command completed by the ISR
937  *
938  * For AEN, driver sends a command down to FW that is held by the FW till an
939  * event occurs. When an event of interest occurs, FW completes the command
940  * that it was previously holding.
941  *
942  * This routines sends SIGIO signal to processes that have registered with the
943  * driver for AEN.
944  */
945 static void
946 megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
947 {
948         /*
949          * Don't signal app if it is just an aborted previously registered aen
950          */
951         if (!cmd->abort_aen)
952                 kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
953         else
954                 cmd->abort_aen = 0;
955
956         instance->aen_cmd = NULL;
957         megasas_return_cmd(instance, cmd);
958 }
959
960 /*
961  * Scsi host template for megaraid_sas driver
962  */
963 static struct scsi_host_template megasas_template = {
964
965         .module = THIS_MODULE,
966         .name = "LSI Logic SAS based MegaRAID driver",
967         .proc_name = "megaraid_sas",
968         .slave_configure = megasas_slave_configure,
969         .queuecommand = megasas_queue_command,
970         .eh_device_reset_handler = megasas_reset_device,
971         .eh_bus_reset_handler = megasas_reset_bus_host,
972         .eh_host_reset_handler = megasas_reset_bus_host,
973         .use_clustering = ENABLE_CLUSTERING,
974 };
975
976 /**
977  * megasas_complete_int_cmd -   Completes an internal command
978  * @instance:                   Adapter soft state
979  * @cmd:                        Command to be completed
980  *
981  * The megasas_issue_blocked_cmd() function waits for a command to complete
982  * after it issues a command. This function wakes up that waiting routine by
983  * calling wake_up() on the wait queue.
984  */
985 static void
986 megasas_complete_int_cmd(struct megasas_instance *instance,
987                          struct megasas_cmd *cmd)
988 {
989         cmd->cmd_status = cmd->frame->io.cmd_status;
990
991         if (cmd->cmd_status == ENODATA) {
992                 cmd->cmd_status = 0;
993         }
994         wake_up(&instance->int_cmd_wait_q);
995 }
996
997 /**
998  * megasas_complete_abort -     Completes aborting a command
999  * @instance:                   Adapter soft state
1000  * @cmd:                        Cmd that was issued to abort another cmd
1001  *
1002  * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q 
1003  * after it issues an abort on a previously issued command. This function 
1004  * wakes up all functions waiting on the same wait queue.
1005  */
1006 static void
1007 megasas_complete_abort(struct megasas_instance *instance,
1008                        struct megasas_cmd *cmd)
1009 {
1010         if (cmd->sync_cmd) {
1011                 cmd->sync_cmd = 0;
1012                 cmd->cmd_status = 0;
1013                 wake_up(&instance->abort_cmd_wait_q);
1014         }
1015
1016         return;
1017 }
1018
1019 /**
1020  * megasas_unmap_sgbuf -        Unmap SG buffers
1021  * @instance:                   Adapter soft state
1022  * @cmd:                        Completed command
1023  */
1024 static void
1025 megasas_unmap_sgbuf(struct megasas_instance *instance, struct megasas_cmd *cmd)
1026 {
1027         dma_addr_t buf_h;
1028         u8 opcode;
1029
1030         if (cmd->scmd->use_sg) {
1031                 pci_unmap_sg(instance->pdev, cmd->scmd->request_buffer,
1032                              cmd->scmd->use_sg, cmd->scmd->sc_data_direction);
1033                 return;
1034         }
1035
1036         if (!cmd->scmd->request_bufflen)
1037                 return;
1038
1039         opcode = cmd->frame->hdr.cmd;
1040
1041         if ((opcode == MFI_CMD_LD_READ) || (opcode == MFI_CMD_LD_WRITE)) {
1042                 if (IS_DMA64)
1043                         buf_h = cmd->frame->io.sgl.sge64[0].phys_addr;
1044                 else
1045                         buf_h = cmd->frame->io.sgl.sge32[0].phys_addr;
1046         } else {
1047                 if (IS_DMA64)
1048                         buf_h = cmd->frame->pthru.sgl.sge64[0].phys_addr;
1049                 else
1050                         buf_h = cmd->frame->pthru.sgl.sge32[0].phys_addr;
1051         }
1052
1053         pci_unmap_single(instance->pdev, buf_h, cmd->scmd->request_bufflen,
1054                          cmd->scmd->sc_data_direction);
1055         return;
1056 }
1057
1058 /**
1059  * megasas_complete_cmd -       Completes a command
1060  * @instance:                   Adapter soft state
1061  * @cmd:                        Command to be completed
1062  * @alt_status:                 If non-zero, use this value as status to 
1063  *                              SCSI mid-layer instead of the value returned
1064  *                              by the FW. This should be used if caller wants
1065  *                              an alternate status (as in the case of aborted
1066  *                              commands)
1067  */
1068 static void
1069 megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
1070                      u8 alt_status)
1071 {
1072         int exception = 0;
1073         struct megasas_header *hdr = &cmd->frame->hdr;
1074
1075         if (cmd->scmd) {
1076                 cmd->scmd->SCp.ptr = (char *)0;
1077         }
1078
1079         switch (hdr->cmd) {
1080
1081         case MFI_CMD_PD_SCSI_IO:
1082         case MFI_CMD_LD_SCSI_IO:
1083
1084                 /*
1085                  * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
1086                  * issued either through an IO path or an IOCTL path. If it
1087                  * was via IOCTL, we will send it to internal completion.
1088                  */
1089                 if (cmd->sync_cmd) {
1090                         cmd->sync_cmd = 0;
1091                         megasas_complete_int_cmd(instance, cmd);
1092                         break;
1093                 }
1094
1095         case MFI_CMD_LD_READ:
1096         case MFI_CMD_LD_WRITE:
1097
1098                 if (alt_status) {
1099                         cmd->scmd->result = alt_status << 16;
1100                         exception = 1;
1101                 }
1102
1103                 if (exception) {
1104
1105                         atomic_dec(&instance->fw_outstanding);
1106
1107                         megasas_unmap_sgbuf(instance, cmd);
1108                         cmd->scmd->scsi_done(cmd->scmd);
1109                         megasas_return_cmd(instance, cmd);
1110
1111                         break;
1112                 }
1113
1114                 switch (hdr->cmd_status) {
1115
1116                 case MFI_STAT_OK:
1117                         cmd->scmd->result = DID_OK << 16;
1118                         break;
1119
1120                 case MFI_STAT_SCSI_IO_FAILED:
1121                 case MFI_STAT_LD_INIT_IN_PROGRESS:
1122                         cmd->scmd->result =
1123                             (DID_ERROR << 16) | hdr->scsi_status;
1124                         break;
1125
1126                 case MFI_STAT_SCSI_DONE_WITH_ERROR:
1127
1128                         cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
1129
1130                         if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
1131                                 memset(cmd->scmd->sense_buffer, 0,
1132                                        SCSI_SENSE_BUFFERSIZE);
1133                                 memcpy(cmd->scmd->sense_buffer, cmd->sense,
1134                                        hdr->sense_len);
1135
1136                                 cmd->scmd->result |= DRIVER_SENSE << 24;
1137                         }
1138
1139                         break;
1140
1141                 case MFI_STAT_LD_OFFLINE:
1142                 case MFI_STAT_DEVICE_NOT_FOUND:
1143                         cmd->scmd->result = DID_BAD_TARGET << 16;
1144                         break;
1145
1146                 default:
1147                         printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
1148                                hdr->cmd_status);
1149                         cmd->scmd->result = DID_ERROR << 16;
1150                         break;
1151                 }
1152
1153                 atomic_dec(&instance->fw_outstanding);
1154
1155                 megasas_unmap_sgbuf(instance, cmd);
1156                 cmd->scmd->scsi_done(cmd->scmd);
1157                 megasas_return_cmd(instance, cmd);
1158
1159                 break;
1160
1161         case MFI_CMD_SMP:
1162         case MFI_CMD_STP:
1163         case MFI_CMD_DCMD:
1164
1165                 /*
1166                  * See if got an event notification
1167                  */
1168                 if (cmd->frame->dcmd.opcode == MR_DCMD_CTRL_EVENT_WAIT)
1169                         megasas_service_aen(instance, cmd);
1170                 else
1171                         megasas_complete_int_cmd(instance, cmd);
1172
1173                 break;
1174
1175         case MFI_CMD_ABORT:
1176                 /*
1177                  * Cmd issued to abort another cmd returned
1178                  */
1179                 megasas_complete_abort(instance, cmd);
1180                 break;
1181
1182         default:
1183                 printk("megasas: Unknown command completed! [0x%X]\n",
1184                        hdr->cmd);
1185                 break;
1186         }
1187 }
1188
1189 /**
1190  * megasas_deplete_reply_queue -        Processes all completed commands
1191  * @instance:                           Adapter soft state
1192  * @alt_status:                         Alternate status to be returned to
1193  *                                      SCSI mid-layer instead of the status
1194  *                                      returned by the FW
1195  */
1196 static int
1197 megasas_deplete_reply_queue(struct megasas_instance *instance, u8 alt_status)
1198 {
1199         u32 producer;
1200         u32 consumer;
1201         u32 context;
1202         struct megasas_cmd *cmd;
1203
1204         /*
1205          * Check if it is our interrupt
1206          * Clear the interrupt 
1207          */
1208         if(instance->instancet->clear_intr(instance->reg_set))
1209                 return IRQ_NONE;
1210
1211         producer = *instance->producer;
1212         consumer = *instance->consumer;
1213
1214         while (consumer != producer) {
1215                 context = instance->reply_queue[consumer];
1216
1217                 cmd = instance->cmd_list[context];
1218
1219                 megasas_complete_cmd(instance, cmd, alt_status);
1220
1221                 consumer++;
1222                 if (consumer == (instance->max_fw_cmds + 1)) {
1223                         consumer = 0;
1224                 }
1225         }
1226
1227         *instance->consumer = producer;
1228
1229         return IRQ_HANDLED;
1230 }
1231
1232 /**
1233  * megasas_isr - isr entry point
1234  */
1235 static irqreturn_t megasas_isr(int irq, void *devp, struct pt_regs *regs)
1236 {
1237         return megasas_deplete_reply_queue((struct megasas_instance *)devp,
1238                                            DID_OK);
1239 }
1240
1241 /**
1242  * megasas_transition_to_ready -        Move the FW to READY state
1243  * @instance:                           Adapter soft state
1244  *
1245  * During the initialization, FW passes can potentially be in any one of
1246  * several possible states. If the FW in operational, waiting-for-handshake
1247  * states, driver must take steps to bring it to ready state. Otherwise, it
1248  * has to wait for the ready state.
1249  */
1250 static int
1251 megasas_transition_to_ready(struct megasas_instance* instance)
1252 {
1253         int i;
1254         u8 max_wait;
1255         u32 fw_state;
1256         u32 cur_state;
1257
1258         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
1259
1260         if (fw_state != MFI_STATE_READY)
1261                 printk(KERN_INFO "megasas: Waiting for FW to come to ready"
1262                        " state\n");
1263
1264         while (fw_state != MFI_STATE_READY) {
1265
1266                 switch (fw_state) {
1267
1268                 case MFI_STATE_FAULT:
1269
1270                         printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
1271                         return -ENODEV;
1272
1273                 case MFI_STATE_WAIT_HANDSHAKE:
1274                         /*
1275                          * Set the CLR bit in inbound doorbell
1276                          */
1277                         writel(MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
1278                                 &instance->reg_set->inbound_doorbell);
1279
1280                         max_wait = 2;
1281                         cur_state = MFI_STATE_WAIT_HANDSHAKE;
1282                         break;
1283
1284                 case MFI_STATE_BOOT_MESSAGE_PENDING:
1285                         writel(MFI_INIT_HOTPLUG,
1286                                 &instance->reg_set->inbound_doorbell);
1287
1288                         max_wait = 10;
1289                         cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
1290                         break;
1291
1292                 case MFI_STATE_OPERATIONAL:
1293                         /*
1294                          * Bring it to READY state; assuming max wait 10 secs
1295                          */
1296                         megasas_disable_intr(instance);
1297                         writel(MFI_RESET_FLAGS, &instance->reg_set->inbound_doorbell);
1298
1299                         max_wait = 10;
1300                         cur_state = MFI_STATE_OPERATIONAL;
1301                         break;
1302
1303                 case MFI_STATE_UNDEFINED:
1304                         /*
1305                          * This state should not last for more than 2 seconds
1306                          */
1307                         max_wait = 2;
1308                         cur_state = MFI_STATE_UNDEFINED;
1309                         break;
1310
1311                 case MFI_STATE_BB_INIT:
1312                         max_wait = 2;
1313                         cur_state = MFI_STATE_BB_INIT;
1314                         break;
1315
1316                 case MFI_STATE_FW_INIT:
1317                         max_wait = 20;
1318                         cur_state = MFI_STATE_FW_INIT;
1319                         break;
1320
1321                 case MFI_STATE_FW_INIT_2:
1322                         max_wait = 20;
1323                         cur_state = MFI_STATE_FW_INIT_2;
1324                         break;
1325
1326                 case MFI_STATE_DEVICE_SCAN:
1327                         max_wait = 20;
1328                         cur_state = MFI_STATE_DEVICE_SCAN;
1329                         break;
1330
1331                 case MFI_STATE_FLUSH_CACHE:
1332                         max_wait = 20;
1333                         cur_state = MFI_STATE_FLUSH_CACHE;
1334                         break;
1335
1336                 default:
1337                         printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
1338                                fw_state);
1339                         return -ENODEV;
1340                 }
1341
1342                 /*
1343                  * The cur_state should not last for more than max_wait secs
1344                  */
1345                 for (i = 0; i < (max_wait * 1000); i++) {
1346                         fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &  
1347                                         MFI_STATE_MASK ;
1348
1349                         if (fw_state == cur_state) {
1350                                 msleep(1);
1351                         } else
1352                                 break;
1353                 }
1354
1355                 /*
1356                  * Return error if fw_state hasn't changed after max_wait
1357                  */
1358                 if (fw_state == cur_state) {
1359                         printk(KERN_DEBUG "FW state [%d] hasn't changed "
1360                                "in %d secs\n", fw_state, max_wait);
1361                         return -ENODEV;
1362                 }
1363         };
1364         printk(KERN_INFO "megasas: FW now in Ready state\n");
1365
1366         return 0;
1367 }
1368
1369 /**
1370  * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
1371  * @instance:                           Adapter soft state
1372  */
1373 static void megasas_teardown_frame_pool(struct megasas_instance *instance)
1374 {
1375         int i;
1376         u32 max_cmd = instance->max_fw_cmds;
1377         struct megasas_cmd *cmd;
1378
1379         if (!instance->frame_dma_pool)
1380                 return;
1381
1382         /*
1383          * Return all frames to pool
1384          */
1385         for (i = 0; i < max_cmd; i++) {
1386
1387                 cmd = instance->cmd_list[i];
1388
1389                 if (cmd->frame)
1390                         pci_pool_free(instance->frame_dma_pool, cmd->frame,
1391                                       cmd->frame_phys_addr);
1392
1393                 if (cmd->sense)
1394                         pci_pool_free(instance->sense_dma_pool, cmd->sense,
1395                                       cmd->sense_phys_addr);
1396         }
1397
1398         /*
1399          * Now destroy the pool itself
1400          */
1401         pci_pool_destroy(instance->frame_dma_pool);
1402         pci_pool_destroy(instance->sense_dma_pool);
1403
1404         instance->frame_dma_pool = NULL;
1405         instance->sense_dma_pool = NULL;
1406 }
1407
1408 /**
1409  * megasas_create_frame_pool -  Creates DMA pool for cmd frames
1410  * @instance:                   Adapter soft state
1411  *
1412  * Each command packet has an embedded DMA memory buffer that is used for
1413  * filling MFI frame and the SG list that immediately follows the frame. This
1414  * function creates those DMA memory buffers for each command packet by using
1415  * PCI pool facility.
1416  */
1417 static int megasas_create_frame_pool(struct megasas_instance *instance)
1418 {
1419         int i;
1420         u32 max_cmd;
1421         u32 sge_sz;
1422         u32 sgl_sz;
1423         u32 total_sz;
1424         u32 frame_count;
1425         struct megasas_cmd *cmd;
1426
1427         max_cmd = instance->max_fw_cmds;
1428
1429         /*
1430          * Size of our frame is 64 bytes for MFI frame, followed by max SG
1431          * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
1432          */
1433         sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1434             sizeof(struct megasas_sge32);
1435
1436         /*
1437          * Calculated the number of 64byte frames required for SGL
1438          */
1439         sgl_sz = sge_sz * instance->max_num_sge;
1440         frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
1441
1442         /*
1443          * We need one extra frame for the MFI command
1444          */
1445         frame_count++;
1446
1447         total_sz = MEGAMFI_FRAME_SIZE * frame_count;
1448         /*
1449          * Use DMA pool facility provided by PCI layer
1450          */
1451         instance->frame_dma_pool = pci_pool_create("megasas frame pool",
1452                                                    instance->pdev, total_sz, 64,
1453                                                    0);
1454
1455         if (!instance->frame_dma_pool) {
1456                 printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
1457                 return -ENOMEM;
1458         }
1459
1460         instance->sense_dma_pool = pci_pool_create("megasas sense pool",
1461                                                    instance->pdev, 128, 4, 0);
1462
1463         if (!instance->sense_dma_pool) {
1464                 printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
1465
1466                 pci_pool_destroy(instance->frame_dma_pool);
1467                 instance->frame_dma_pool = NULL;
1468
1469                 return -ENOMEM;
1470         }
1471
1472         /*
1473          * Allocate and attach a frame to each of the commands in cmd_list.
1474          * By making cmd->index as the context instead of the &cmd, we can
1475          * always use 32bit context regardless of the architecture
1476          */
1477         for (i = 0; i < max_cmd; i++) {
1478
1479                 cmd = instance->cmd_list[i];
1480
1481                 cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
1482                                             GFP_KERNEL, &cmd->frame_phys_addr);
1483
1484                 cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
1485                                             GFP_KERNEL, &cmd->sense_phys_addr);
1486
1487                 /*
1488                  * megasas_teardown_frame_pool() takes care of freeing
1489                  * whatever has been allocated
1490                  */
1491                 if (!cmd->frame || !cmd->sense) {
1492                         printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
1493                         megasas_teardown_frame_pool(instance);
1494                         return -ENOMEM;
1495                 }
1496
1497                 cmd->frame->io.context = cmd->index;
1498         }
1499
1500         return 0;
1501 }
1502
1503 /**
1504  * megasas_free_cmds -  Free all the cmds in the free cmd pool
1505  * @instance:           Adapter soft state
1506  */
1507 static void megasas_free_cmds(struct megasas_instance *instance)
1508 {
1509         int i;
1510         /* First free the MFI frame pool */
1511         megasas_teardown_frame_pool(instance);
1512
1513         /* Free all the commands in the cmd_list */
1514         for (i = 0; i < instance->max_fw_cmds; i++)
1515                 kfree(instance->cmd_list[i]);
1516
1517         /* Free the cmd_list buffer itself */
1518         kfree(instance->cmd_list);
1519         instance->cmd_list = NULL;
1520
1521         INIT_LIST_HEAD(&instance->cmd_pool);
1522 }
1523
1524 /**
1525  * megasas_alloc_cmds - Allocates the command packets
1526  * @instance:           Adapter soft state
1527  *
1528  * Each command that is issued to the FW, whether IO commands from the OS or
1529  * internal commands like IOCTLs, are wrapped in local data structure called
1530  * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
1531  * the FW.
1532  *
1533  * Each frame has a 32-bit field called context (tag). This context is used
1534  * to get back the megasas_cmd from the frame when a frame gets completed in
1535  * the ISR. Typically the address of the megasas_cmd itself would be used as
1536  * the context. But we wanted to keep the differences between 32 and 64 bit
1537  * systems to the mininum. We always use 32 bit integers for the context. In
1538  * this driver, the 32 bit values are the indices into an array cmd_list.
1539  * This array is used only to look up the megasas_cmd given the context. The
1540  * free commands themselves are maintained in a linked list called cmd_pool.
1541  */
1542 static int megasas_alloc_cmds(struct megasas_instance *instance)
1543 {
1544         int i;
1545         int j;
1546         u32 max_cmd;
1547         struct megasas_cmd *cmd;
1548
1549         max_cmd = instance->max_fw_cmds;
1550
1551         /*
1552          * instance->cmd_list is an array of struct megasas_cmd pointers.
1553          * Allocate the dynamic array first and then allocate individual
1554          * commands.
1555          */
1556         instance->cmd_list = kmalloc(sizeof(struct megasas_cmd *) * max_cmd,
1557                                      GFP_KERNEL);
1558
1559         if (!instance->cmd_list) {
1560                 printk(KERN_DEBUG "megasas: out of memory\n");
1561                 return -ENOMEM;
1562         }
1563
1564         memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) * max_cmd);
1565
1566         for (i = 0; i < max_cmd; i++) {
1567                 instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
1568                                                 GFP_KERNEL);
1569
1570                 if (!instance->cmd_list[i]) {
1571
1572                         for (j = 0; j < i; j++)
1573                                 kfree(instance->cmd_list[j]);
1574
1575                         kfree(instance->cmd_list);
1576                         instance->cmd_list = NULL;
1577
1578                         return -ENOMEM;
1579                 }
1580         }
1581
1582         /*
1583          * Add all the commands to command pool (instance->cmd_pool)
1584          */
1585         for (i = 0; i < max_cmd; i++) {
1586                 cmd = instance->cmd_list[i];
1587                 memset(cmd, 0, sizeof(struct megasas_cmd));
1588                 cmd->index = i;
1589                 cmd->instance = instance;
1590
1591                 list_add_tail(&cmd->list, &instance->cmd_pool);
1592         }
1593
1594         /*
1595          * Create a frame pool and assign one frame to each cmd
1596          */
1597         if (megasas_create_frame_pool(instance)) {
1598                 printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
1599                 megasas_free_cmds(instance);
1600         }
1601
1602         return 0;
1603 }
1604
1605 /**
1606  * megasas_get_controller_info -        Returns FW's controller structure
1607  * @instance:                           Adapter soft state
1608  * @ctrl_info:                          Controller information structure
1609  *
1610  * Issues an internal command (DCMD) to get the FW's controller structure.
1611  * This information is mainly used to find out the maximum IO transfer per
1612  * command supported by the FW.
1613  */
1614 static int
1615 megasas_get_ctrl_info(struct megasas_instance *instance,
1616                       struct megasas_ctrl_info *ctrl_info)
1617 {
1618         int ret = 0;
1619         struct megasas_cmd *cmd;
1620         struct megasas_dcmd_frame *dcmd;
1621         struct megasas_ctrl_info *ci;
1622         dma_addr_t ci_h = 0;
1623
1624         cmd = megasas_get_cmd(instance);
1625
1626         if (!cmd) {
1627                 printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
1628                 return -ENOMEM;
1629         }
1630
1631         dcmd = &cmd->frame->dcmd;
1632
1633         ci = pci_alloc_consistent(instance->pdev,
1634                                   sizeof(struct megasas_ctrl_info), &ci_h);
1635
1636         if (!ci) {
1637                 printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
1638                 megasas_return_cmd(instance, cmd);
1639                 return -ENOMEM;
1640         }
1641
1642         memset(ci, 0, sizeof(*ci));
1643         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1644
1645         dcmd->cmd = MFI_CMD_DCMD;
1646         dcmd->cmd_status = 0xFF;
1647         dcmd->sge_count = 1;
1648         dcmd->flags = MFI_FRAME_DIR_READ;
1649         dcmd->timeout = 0;
1650         dcmd->data_xfer_len = sizeof(struct megasas_ctrl_info);
1651         dcmd->opcode = MR_DCMD_CTRL_GET_INFO;
1652         dcmd->sgl.sge32[0].phys_addr = ci_h;
1653         dcmd->sgl.sge32[0].length = sizeof(struct megasas_ctrl_info);
1654
1655         if (!megasas_issue_polled(instance, cmd)) {
1656                 ret = 0;
1657                 memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
1658         } else {
1659                 ret = -1;
1660         }
1661
1662         pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
1663                             ci, ci_h);
1664
1665         megasas_return_cmd(instance, cmd);
1666         return ret;
1667 }
1668
1669 /**
1670  * megasas_init_mfi -   Initializes the FW
1671  * @instance:           Adapter soft state
1672  *
1673  * This is the main function for initializing MFI firmware.
1674  */
1675 static int megasas_init_mfi(struct megasas_instance *instance)
1676 {
1677         u32 context_sz;
1678         u32 reply_q_sz;
1679         u32 max_sectors_1;
1680         u32 max_sectors_2;
1681         struct megasas_register_set __iomem *reg_set;
1682
1683         struct megasas_cmd *cmd;
1684         struct megasas_ctrl_info *ctrl_info;
1685
1686         struct megasas_init_frame *init_frame;
1687         struct megasas_init_queue_info *initq_info;
1688         dma_addr_t init_frame_h;
1689         dma_addr_t initq_info_h;
1690
1691         /*
1692          * Map the message registers
1693          */
1694         instance->base_addr = pci_resource_start(instance->pdev, 0);
1695
1696         if (pci_request_regions(instance->pdev, "megasas: LSI Logic")) {
1697                 printk(KERN_DEBUG "megasas: IO memory region busy!\n");
1698                 return -EBUSY;
1699         }
1700
1701         instance->reg_set = ioremap_nocache(instance->base_addr, 8192);
1702
1703         if (!instance->reg_set) {
1704                 printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
1705                 goto fail_ioremap;
1706         }
1707
1708         reg_set = instance->reg_set;
1709
1710         switch(instance->pdev->device)
1711         {
1712                 case PCI_DEVICE_ID_LSI_SAS1078R:        
1713                         instance->instancet = &megasas_instance_template_ppc;
1714                         break;
1715                 case PCI_DEVICE_ID_LSI_SAS1064R:
1716                 case PCI_DEVICE_ID_DELL_PERC5:
1717                 default:
1718                         instance->instancet = &megasas_instance_template_xscale;
1719                         break;
1720         }
1721
1722         /*
1723          * We expect the FW state to be READY
1724          */
1725         if (megasas_transition_to_ready(instance))
1726                 goto fail_ready_state;
1727
1728         /*
1729          * Get various operational parameters from status register
1730          */
1731         instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
1732         /*
1733          * Reduce the max supported cmds by 1. This is to ensure that the
1734          * reply_q_sz (1 more than the max cmd that driver may send)
1735          * does not exceed max cmds that the FW can support
1736          */
1737         instance->max_fw_cmds = instance->max_fw_cmds-1;
1738         instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >> 
1739                                         0x10;
1740         /*
1741          * Create a pool of commands
1742          */
1743         if (megasas_alloc_cmds(instance))
1744                 goto fail_alloc_cmds;
1745
1746         /*
1747          * Allocate memory for reply queue. Length of reply queue should
1748          * be _one_ more than the maximum commands handled by the firmware.
1749          *
1750          * Note: When FW completes commands, it places corresponding contex
1751          * values in this circular reply queue. This circular queue is a fairly
1752          * typical producer-consumer queue. FW is the producer (of completed
1753          * commands) and the driver is the consumer.
1754          */
1755         context_sz = sizeof(u32);
1756         reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
1757
1758         instance->reply_queue = pci_alloc_consistent(instance->pdev,
1759                                                      reply_q_sz,
1760                                                      &instance->reply_queue_h);
1761
1762         if (!instance->reply_queue) {
1763                 printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
1764                 goto fail_reply_queue;
1765         }
1766
1767         /*
1768          * Prepare a init frame. Note the init frame points to queue info
1769          * structure. Each frame has SGL allocated after first 64 bytes. For
1770          * this frame - since we don't need any SGL - we use SGL's space as
1771          * queue info structure
1772          *
1773          * We will not get a NULL command below. We just created the pool.
1774          */
1775         cmd = megasas_get_cmd(instance);
1776
1777         init_frame = (struct megasas_init_frame *)cmd->frame;
1778         initq_info = (struct megasas_init_queue_info *)
1779             ((unsigned long)init_frame + 64);
1780
1781         init_frame_h = cmd->frame_phys_addr;
1782         initq_info_h = init_frame_h + 64;
1783
1784         memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
1785         memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
1786
1787         initq_info->reply_queue_entries = instance->max_fw_cmds + 1;
1788         initq_info->reply_queue_start_phys_addr_lo = instance->reply_queue_h;
1789
1790         initq_info->producer_index_phys_addr_lo = instance->producer_h;
1791         initq_info->consumer_index_phys_addr_lo = instance->consumer_h;
1792
1793         init_frame->cmd = MFI_CMD_INIT;
1794         init_frame->cmd_status = 0xFF;
1795         init_frame->queue_info_new_phys_addr_lo = initq_info_h;
1796
1797         init_frame->data_xfer_len = sizeof(struct megasas_init_queue_info);
1798
1799         /*
1800          * disable the intr before firing the init frame to FW
1801          */
1802         megasas_disable_intr(instance);
1803
1804         /*
1805          * Issue the init frame in polled mode
1806          */
1807         if (megasas_issue_polled(instance, cmd)) {
1808                 printk(KERN_DEBUG "megasas: Failed to init firmware\n");
1809                 goto fail_fw_init;
1810         }
1811
1812         megasas_return_cmd(instance, cmd);
1813
1814         ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
1815
1816         /*
1817          * Compute the max allowed sectors per IO: The controller info has two
1818          * limits on max sectors. Driver should use the minimum of these two.
1819          *
1820          * 1 << stripe_sz_ops.min = max sectors per strip
1821          *
1822          * Note that older firmwares ( < FW ver 30) didn't report information
1823          * to calculate max_sectors_1. So the number ended up as zero always.
1824          */
1825         if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
1826
1827                 max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
1828                     ctrl_info->max_strips_per_io;
1829                 max_sectors_2 = ctrl_info->max_request_size;
1830
1831                 instance->max_sectors_per_req = (max_sectors_1 < max_sectors_2)
1832                     ? max_sectors_1 : max_sectors_2;
1833         } else
1834                 instance->max_sectors_per_req = instance->max_num_sge *
1835                     PAGE_SIZE / 512;
1836
1837         kfree(ctrl_info);
1838
1839         return 0;
1840
1841       fail_fw_init:
1842         megasas_return_cmd(instance, cmd);
1843
1844         pci_free_consistent(instance->pdev, reply_q_sz,
1845                             instance->reply_queue, instance->reply_queue_h);
1846       fail_reply_queue:
1847         megasas_free_cmds(instance);
1848
1849       fail_alloc_cmds:
1850       fail_ready_state:
1851         iounmap(instance->reg_set);
1852
1853       fail_ioremap:
1854         pci_release_regions(instance->pdev);
1855
1856         return -EINVAL;
1857 }
1858
1859 /**
1860  * megasas_release_mfi -        Reverses the FW initialization
1861  * @intance:                    Adapter soft state
1862  */
1863 static void megasas_release_mfi(struct megasas_instance *instance)
1864 {
1865         u32 reply_q_sz = sizeof(u32) * (instance->max_fw_cmds + 1);
1866
1867         pci_free_consistent(instance->pdev, reply_q_sz,
1868                             instance->reply_queue, instance->reply_queue_h);
1869
1870         megasas_free_cmds(instance);
1871
1872         iounmap(instance->reg_set);
1873
1874         pci_release_regions(instance->pdev);
1875 }
1876
1877 /**
1878  * megasas_get_seq_num -        Gets latest event sequence numbers
1879  * @instance:                   Adapter soft state
1880  * @eli:                        FW event log sequence numbers information
1881  *
1882  * FW maintains a log of all events in a non-volatile area. Upper layers would
1883  * usually find out the latest sequence number of the events, the seq number at
1884  * the boot etc. They would "read" all the events below the latest seq number
1885  * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
1886  * number), they would subsribe to AEN (asynchronous event notification) and
1887  * wait for the events to happen.
1888  */
1889 static int
1890 megasas_get_seq_num(struct megasas_instance *instance,
1891                     struct megasas_evt_log_info *eli)
1892 {
1893         struct megasas_cmd *cmd;
1894         struct megasas_dcmd_frame *dcmd;
1895         struct megasas_evt_log_info *el_info;
1896         dma_addr_t el_info_h = 0;
1897
1898         cmd = megasas_get_cmd(instance);
1899
1900         if (!cmd) {
1901                 return -ENOMEM;
1902         }
1903
1904         dcmd = &cmd->frame->dcmd;
1905         el_info = pci_alloc_consistent(instance->pdev,
1906                                        sizeof(struct megasas_evt_log_info),
1907                                        &el_info_h);
1908
1909         if (!el_info) {
1910                 megasas_return_cmd(instance, cmd);
1911                 return -ENOMEM;
1912         }
1913
1914         memset(el_info, 0, sizeof(*el_info));
1915         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1916
1917         dcmd->cmd = MFI_CMD_DCMD;
1918         dcmd->cmd_status = 0x0;
1919         dcmd->sge_count = 1;
1920         dcmd->flags = MFI_FRAME_DIR_READ;
1921         dcmd->timeout = 0;
1922         dcmd->data_xfer_len = sizeof(struct megasas_evt_log_info);
1923         dcmd->opcode = MR_DCMD_CTRL_EVENT_GET_INFO;
1924         dcmd->sgl.sge32[0].phys_addr = el_info_h;
1925         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_log_info);
1926
1927         megasas_issue_blocked_cmd(instance, cmd);
1928
1929         /*
1930          * Copy the data back into callers buffer
1931          */
1932         memcpy(eli, el_info, sizeof(struct megasas_evt_log_info));
1933
1934         pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
1935                             el_info, el_info_h);
1936
1937         megasas_return_cmd(instance, cmd);
1938
1939         return 0;
1940 }
1941
1942 /**
1943  * megasas_register_aen -       Registers for asynchronous event notification
1944  * @instance:                   Adapter soft state
1945  * @seq_num:                    The starting sequence number
1946  * @class_locale:               Class of the event
1947  *
1948  * This function subscribes for AEN for events beyond the @seq_num. It requests
1949  * to be notified if and only if the event is of type @class_locale
1950  */
1951 static int
1952 megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
1953                      u32 class_locale_word)
1954 {
1955         int ret_val;
1956         struct megasas_cmd *cmd;
1957         struct megasas_dcmd_frame *dcmd;
1958         union megasas_evt_class_locale curr_aen;
1959         union megasas_evt_class_locale prev_aen;
1960
1961         /*
1962          * If there an AEN pending already (aen_cmd), check if the
1963          * class_locale of that pending AEN is inclusive of the new
1964          * AEN request we currently have. If it is, then we don't have
1965          * to do anything. In other words, whichever events the current
1966          * AEN request is subscribing to, have already been subscribed
1967          * to.
1968          *
1969          * If the old_cmd is _not_ inclusive, then we have to abort
1970          * that command, form a class_locale that is superset of both
1971          * old and current and re-issue to the FW
1972          */
1973
1974         curr_aen.word = class_locale_word;
1975
1976         if (instance->aen_cmd) {
1977
1978                 prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
1979
1980                 /*
1981                  * A class whose enum value is smaller is inclusive of all
1982                  * higher values. If a PROGRESS (= -1) was previously
1983                  * registered, then a new registration requests for higher
1984                  * classes need not be sent to FW. They are automatically
1985                  * included.
1986                  *
1987                  * Locale numbers don't have such hierarchy. They are bitmap
1988                  * values
1989                  */
1990                 if ((prev_aen.members.class <= curr_aen.members.class) &&
1991                     !((prev_aen.members.locale & curr_aen.members.locale) ^
1992                       curr_aen.members.locale)) {
1993                         /*
1994                          * Previously issued event registration includes
1995                          * current request. Nothing to do.
1996                          */
1997                         return 0;
1998                 } else {
1999                         curr_aen.members.locale |= prev_aen.members.locale;
2000
2001                         if (prev_aen.members.class < curr_aen.members.class)
2002                                 curr_aen.members.class = prev_aen.members.class;
2003
2004                         instance->aen_cmd->abort_aen = 1;
2005                         ret_val = megasas_issue_blocked_abort_cmd(instance,
2006                                                                   instance->
2007                                                                   aen_cmd);
2008
2009                         if (ret_val) {
2010                                 printk(KERN_DEBUG "megasas: Failed to abort "
2011                                        "previous AEN command\n");
2012                                 return ret_val;
2013                         }
2014                 }
2015         }
2016
2017         cmd = megasas_get_cmd(instance);
2018
2019         if (!cmd)
2020                 return -ENOMEM;
2021
2022         dcmd = &cmd->frame->dcmd;
2023
2024         memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
2025
2026         /*
2027          * Prepare DCMD for aen registration
2028          */
2029         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2030
2031         dcmd->cmd = MFI_CMD_DCMD;
2032         dcmd->cmd_status = 0x0;
2033         dcmd->sge_count = 1;
2034         dcmd->flags = MFI_FRAME_DIR_READ;
2035         dcmd->timeout = 0;
2036         dcmd->data_xfer_len = sizeof(struct megasas_evt_detail);
2037         dcmd->opcode = MR_DCMD_CTRL_EVENT_WAIT;
2038         dcmd->mbox.w[0] = seq_num;
2039         dcmd->mbox.w[1] = curr_aen.word;
2040         dcmd->sgl.sge32[0].phys_addr = (u32) instance->evt_detail_h;
2041         dcmd->sgl.sge32[0].length = sizeof(struct megasas_evt_detail);
2042
2043         /*
2044          * Store reference to the cmd used to register for AEN. When an
2045          * application wants us to register for AEN, we have to abort this
2046          * cmd and re-register with a new EVENT LOCALE supplied by that app
2047          */
2048         instance->aen_cmd = cmd;
2049
2050         /*
2051          * Issue the aen registration frame
2052          */
2053         instance->instancet->fire_cmd(cmd->frame_phys_addr ,0,instance->reg_set);
2054
2055         return 0;
2056 }
2057
2058 /**
2059  * megasas_start_aen -  Subscribes to AEN during driver load time
2060  * @instance:           Adapter soft state
2061  */
2062 static int megasas_start_aen(struct megasas_instance *instance)
2063 {
2064         struct megasas_evt_log_info eli;
2065         union megasas_evt_class_locale class_locale;
2066
2067         /*
2068          * Get the latest sequence number from FW
2069          */
2070         memset(&eli, 0, sizeof(eli));
2071
2072         if (megasas_get_seq_num(instance, &eli))
2073                 return -1;
2074
2075         /*
2076          * Register AEN with FW for latest sequence number plus 1
2077          */
2078         class_locale.members.reserved = 0;
2079         class_locale.members.locale = MR_EVT_LOCALE_ALL;
2080         class_locale.members.class = MR_EVT_CLASS_DEBUG;
2081
2082         return megasas_register_aen(instance, eli.newest_seq_num + 1,
2083                                     class_locale.word);
2084 }
2085
2086 /**
2087  * megasas_io_attach -  Attaches this driver to SCSI mid-layer
2088  * @instance:           Adapter soft state
2089  */
2090 static int megasas_io_attach(struct megasas_instance *instance)
2091 {
2092         struct Scsi_Host *host = instance->host;
2093
2094         /*
2095          * Export parameters required by SCSI mid-layer
2096          */
2097         host->irq = instance->pdev->irq;
2098         host->unique_id = instance->unique_id;
2099         host->can_queue = instance->max_fw_cmds - MEGASAS_INT_CMDS;
2100         host->this_id = instance->init_id;
2101         host->sg_tablesize = instance->max_num_sge;
2102         host->max_sectors = instance->max_sectors_per_req;
2103         host->cmd_per_lun = 128;
2104         host->max_channel = MEGASAS_MAX_CHANNELS - 1;
2105         host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
2106         host->max_lun = MEGASAS_MAX_LUN;
2107         host->max_cmd_len = 16;
2108
2109         /*
2110          * Notify the mid-layer about the new controller
2111          */
2112         if (scsi_add_host(host, &instance->pdev->dev)) {
2113                 printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
2114                 return -ENODEV;
2115         }
2116
2117         /*
2118          * Trigger SCSI to scan our drives
2119          */
2120         scsi_scan_host(host);
2121         return 0;
2122 }
2123
2124 /**
2125  * megasas_probe_one -  PCI hotplug entry point
2126  * @pdev:               PCI device structure
2127  * @id:                 PCI ids of supported hotplugged adapter 
2128  */
2129 static int __devinit
2130 megasas_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
2131 {
2132         int rval;
2133         struct Scsi_Host *host;
2134         struct megasas_instance *instance;
2135
2136         /*
2137          * Announce PCI information
2138          */
2139         printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
2140                pdev->vendor, pdev->device, pdev->subsystem_vendor,
2141                pdev->subsystem_device);
2142
2143         printk("bus %d:slot %d:func %d\n",
2144                pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
2145
2146         /*
2147          * PCI prepping: enable device set bus mastering and dma mask
2148          */
2149         rval = pci_enable_device(pdev);
2150
2151         if (rval) {
2152                 return rval;
2153         }
2154
2155         pci_set_master(pdev);
2156
2157         /*
2158          * All our contollers are capable of performing 64-bit DMA
2159          */
2160         if (IS_DMA64) {
2161                 if (pci_set_dma_mask(pdev, DMA_64BIT_MASK) != 0) {
2162
2163                         if (pci_set_dma_mask(pdev, DMA_32BIT_MASK) != 0)
2164                                 goto fail_set_dma_mask;
2165                 }
2166         } else {
2167                 if (pci_set_dma_mask(pdev, DMA_32BIT_MASK) != 0)
2168                         goto fail_set_dma_mask;
2169         }
2170
2171         host = scsi_host_alloc(&megasas_template,
2172                                sizeof(struct megasas_instance));
2173
2174         if (!host) {
2175                 printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
2176                 goto fail_alloc_instance;
2177         }
2178
2179         instance = (struct megasas_instance *)host->hostdata;
2180         memset(instance, 0, sizeof(*instance));
2181
2182         instance->producer = pci_alloc_consistent(pdev, sizeof(u32),
2183                                                   &instance->producer_h);
2184         instance->consumer = pci_alloc_consistent(pdev, sizeof(u32),
2185                                                   &instance->consumer_h);
2186
2187         if (!instance->producer || !instance->consumer) {
2188                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
2189                        "producer, consumer\n");
2190                 goto fail_alloc_dma_buf;
2191         }
2192
2193         *instance->producer = 0;
2194         *instance->consumer = 0;
2195
2196         instance->evt_detail = pci_alloc_consistent(pdev,
2197                                                     sizeof(struct
2198                                                            megasas_evt_detail),
2199                                                     &instance->evt_detail_h);
2200
2201         if (!instance->evt_detail) {
2202                 printk(KERN_DEBUG "megasas: Failed to allocate memory for "
2203                        "event detail structure\n");
2204                 goto fail_alloc_dma_buf;
2205         }
2206
2207         /*
2208          * Initialize locks and queues
2209          */
2210         INIT_LIST_HEAD(&instance->cmd_pool);
2211
2212         atomic_set(&instance->fw_outstanding,0);
2213
2214         init_waitqueue_head(&instance->int_cmd_wait_q);
2215         init_waitqueue_head(&instance->abort_cmd_wait_q);
2216
2217         spin_lock_init(&instance->cmd_pool_lock);
2218
2219         sema_init(&instance->aen_mutex, 1);
2220         sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
2221
2222         /*
2223          * Initialize PCI related and misc parameters
2224          */
2225         instance->pdev = pdev;
2226         instance->host = host;
2227         instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
2228         instance->init_id = MEGASAS_DEFAULT_INIT_ID;
2229
2230         /*
2231          * Initialize MFI Firmware
2232          */
2233         if (megasas_init_mfi(instance))
2234                 goto fail_init_mfi;
2235
2236         /*
2237          * Register IRQ
2238          */
2239         if (request_irq(pdev->irq, megasas_isr, IRQF_SHARED, "megasas", instance)) {
2240                 printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
2241                 goto fail_irq;
2242         }
2243
2244         instance->instancet->enable_intr(instance->reg_set);
2245
2246         /*
2247          * Store instance in PCI softstate
2248          */
2249         pci_set_drvdata(pdev, instance);
2250
2251         /*
2252          * Add this controller to megasas_mgmt_info structure so that it
2253          * can be exported to management applications
2254          */
2255         megasas_mgmt_info.count++;
2256         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
2257         megasas_mgmt_info.max_index++;
2258
2259         /*
2260          * Initiate AEN (Asynchronous Event Notification)
2261          */
2262         if (megasas_start_aen(instance)) {
2263                 printk(KERN_DEBUG "megasas: start aen failed\n");
2264                 goto fail_start_aen;
2265         }
2266
2267         /*
2268          * Register with SCSI mid-layer
2269          */
2270         if (megasas_io_attach(instance))
2271                 goto fail_io_attach;
2272
2273         return 0;
2274
2275       fail_start_aen:
2276       fail_io_attach:
2277         megasas_mgmt_info.count--;
2278         megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
2279         megasas_mgmt_info.max_index--;
2280
2281         pci_set_drvdata(pdev, NULL);
2282         megasas_disable_intr(instance);
2283         free_irq(instance->pdev->irq, instance);
2284
2285         megasas_release_mfi(instance);
2286
2287       fail_irq:
2288       fail_init_mfi:
2289       fail_alloc_dma_buf:
2290         if (instance->evt_detail)
2291                 pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2292                                     instance->evt_detail,
2293                                     instance->evt_detail_h);
2294
2295         if (instance->producer)
2296                 pci_free_consistent(pdev, sizeof(u32), instance->producer,
2297                                     instance->producer_h);
2298         if (instance->consumer)
2299                 pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2300                                     instance->consumer_h);
2301         scsi_host_put(host);
2302
2303       fail_alloc_instance:
2304       fail_set_dma_mask:
2305         pci_disable_device(pdev);
2306
2307         return -ENODEV;
2308 }
2309
2310 /**
2311  * megasas_flush_cache -        Requests FW to flush all its caches
2312  * @instance:                   Adapter soft state
2313  */
2314 static void megasas_flush_cache(struct megasas_instance *instance)
2315 {
2316         struct megasas_cmd *cmd;
2317         struct megasas_dcmd_frame *dcmd;
2318
2319         cmd = megasas_get_cmd(instance);
2320
2321         if (!cmd)
2322                 return;
2323
2324         dcmd = &cmd->frame->dcmd;
2325
2326         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2327
2328         dcmd->cmd = MFI_CMD_DCMD;
2329         dcmd->cmd_status = 0x0;
2330         dcmd->sge_count = 0;
2331         dcmd->flags = MFI_FRAME_DIR_NONE;
2332         dcmd->timeout = 0;
2333         dcmd->data_xfer_len = 0;
2334         dcmd->opcode = MR_DCMD_CTRL_CACHE_FLUSH;
2335         dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
2336
2337         megasas_issue_blocked_cmd(instance, cmd);
2338
2339         megasas_return_cmd(instance, cmd);
2340
2341         return;
2342 }
2343
2344 /**
2345  * megasas_shutdown_controller -        Instructs FW to shutdown the controller
2346  * @instance:                           Adapter soft state
2347  */
2348 static void megasas_shutdown_controller(struct megasas_instance *instance)
2349 {
2350         struct megasas_cmd *cmd;
2351         struct megasas_dcmd_frame *dcmd;
2352
2353         cmd = megasas_get_cmd(instance);
2354
2355         if (!cmd)
2356                 return;
2357
2358         if (instance->aen_cmd)
2359                 megasas_issue_blocked_abort_cmd(instance, instance->aen_cmd);
2360
2361         dcmd = &cmd->frame->dcmd;
2362
2363         memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2364
2365         dcmd->cmd = MFI_CMD_DCMD;
2366         dcmd->cmd_status = 0x0;
2367         dcmd->sge_count = 0;
2368         dcmd->flags = MFI_FRAME_DIR_NONE;
2369         dcmd->timeout = 0;
2370         dcmd->data_xfer_len = 0;
2371         dcmd->opcode = MR_DCMD_CTRL_SHUTDOWN;
2372
2373         megasas_issue_blocked_cmd(instance, cmd);
2374
2375         megasas_return_cmd(instance, cmd);
2376
2377         return;
2378 }
2379
2380 /**
2381  * megasas_detach_one - PCI hot"un"plug entry point
2382  * @pdev:               PCI device structure
2383  */
2384 static void megasas_detach_one(struct pci_dev *pdev)
2385 {
2386         int i;
2387         struct Scsi_Host *host;
2388         struct megasas_instance *instance;
2389
2390         instance = pci_get_drvdata(pdev);
2391         host = instance->host;
2392
2393         scsi_remove_host(instance->host);
2394         megasas_flush_cache(instance);
2395         megasas_shutdown_controller(instance);
2396
2397         /*
2398          * Take the instance off the instance array. Note that we will not
2399          * decrement the max_index. We let this array be sparse array
2400          */
2401         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
2402                 if (megasas_mgmt_info.instance[i] == instance) {
2403                         megasas_mgmt_info.count--;
2404                         megasas_mgmt_info.instance[i] = NULL;
2405
2406                         break;
2407                 }
2408         }
2409
2410         pci_set_drvdata(instance->pdev, NULL);
2411
2412         megasas_disable_intr(instance);
2413
2414         free_irq(instance->pdev->irq, instance);
2415
2416         megasas_release_mfi(instance);
2417
2418         pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
2419                             instance->evt_detail, instance->evt_detail_h);
2420
2421         pci_free_consistent(pdev, sizeof(u32), instance->producer,
2422                             instance->producer_h);
2423
2424         pci_free_consistent(pdev, sizeof(u32), instance->consumer,
2425                             instance->consumer_h);
2426
2427         scsi_host_put(host);
2428
2429         pci_set_drvdata(pdev, NULL);
2430
2431         pci_disable_device(pdev);
2432
2433         return;
2434 }
2435
2436 /**
2437  * megasas_shutdown -   Shutdown entry point
2438  * @device:             Generic device structure
2439  */
2440 static void megasas_shutdown(struct pci_dev *pdev)
2441 {
2442         struct megasas_instance *instance = pci_get_drvdata(pdev);
2443         megasas_flush_cache(instance);
2444 }
2445
2446 /**
2447  * megasas_mgmt_open -  char node "open" entry point
2448  */
2449 static int megasas_mgmt_open(struct inode *inode, struct file *filep)
2450 {
2451         /*
2452          * Allow only those users with admin rights
2453          */
2454         if (!capable(CAP_SYS_ADMIN))
2455                 return -EACCES;
2456
2457         return 0;
2458 }
2459
2460 /**
2461  * megasas_mgmt_release - char node "release" entry point
2462  */
2463 static int megasas_mgmt_release(struct inode *inode, struct file *filep)
2464 {
2465         filep->private_data = NULL;
2466         fasync_helper(-1, filep, 0, &megasas_async_queue);
2467
2468         return 0;
2469 }
2470
2471 /**
2472  * megasas_mgmt_fasync -        Async notifier registration from applications
2473  *
2474  * This function adds the calling process to a driver global queue. When an
2475  * event occurs, SIGIO will be sent to all processes in this queue.
2476  */
2477 static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
2478 {
2479         int rc;
2480
2481         mutex_lock(&megasas_async_queue_mutex);
2482
2483         rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
2484
2485         mutex_unlock(&megasas_async_queue_mutex);
2486
2487         if (rc >= 0) {
2488                 /* For sanity check when we get ioctl */
2489                 filep->private_data = filep;
2490                 return 0;
2491         }
2492
2493         printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
2494
2495         return rc;
2496 }
2497
2498 /**
2499  * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
2500  * @instance:                   Adapter soft state
2501  * @argp:                       User's ioctl packet
2502  */
2503 static int
2504 megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
2505                       struct megasas_iocpacket __user * user_ioc,
2506                       struct megasas_iocpacket *ioc)
2507 {
2508         struct megasas_sge32 *kern_sge32;
2509         struct megasas_cmd *cmd;
2510         void *kbuff_arr[MAX_IOCTL_SGE];
2511         dma_addr_t buf_handle = 0;
2512         int error = 0, i;
2513         void *sense = NULL;
2514         dma_addr_t sense_handle;
2515         u32 *sense_ptr;
2516
2517         memset(kbuff_arr, 0, sizeof(kbuff_arr));
2518
2519         if (ioc->sge_count > MAX_IOCTL_SGE) {
2520                 printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
2521                        ioc->sge_count, MAX_IOCTL_SGE);
2522                 return -EINVAL;
2523         }
2524
2525         cmd = megasas_get_cmd(instance);
2526         if (!cmd) {
2527                 printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
2528                 return -ENOMEM;
2529         }
2530
2531         /*
2532          * User's IOCTL packet has 2 frames (maximum). Copy those two
2533          * frames into our cmd's frames. cmd->frame's context will get
2534          * overwritten when we copy from user's frames. So set that value
2535          * alone separately
2536          */
2537         memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
2538         cmd->frame->hdr.context = cmd->index;
2539
2540         /*
2541          * The management interface between applications and the fw uses
2542          * MFI frames. E.g, RAID configuration changes, LD property changes
2543          * etc are accomplishes through different kinds of MFI frames. The
2544          * driver needs to care only about substituting user buffers with
2545          * kernel buffers in SGLs. The location of SGL is embedded in the
2546          * struct iocpacket itself.
2547          */
2548         kern_sge32 = (struct megasas_sge32 *)
2549             ((unsigned long)cmd->frame + ioc->sgl_off);
2550
2551         /*
2552          * For each user buffer, create a mirror buffer and copy in
2553          */
2554         for (i = 0; i < ioc->sge_count; i++) {
2555                 kbuff_arr[i] = pci_alloc_consistent(instance->pdev,
2556                                                     ioc->sgl[i].iov_len,
2557                                                     &buf_handle);
2558                 if (!kbuff_arr[i]) {
2559                         printk(KERN_DEBUG "megasas: Failed to alloc "
2560                                "kernel SGL buffer for IOCTL \n");
2561                         error = -ENOMEM;
2562                         goto out;
2563                 }
2564
2565                 /*
2566                  * We don't change the dma_coherent_mask, so
2567                  * pci_alloc_consistent only returns 32bit addresses
2568                  */
2569                 kern_sge32[i].phys_addr = (u32) buf_handle;
2570                 kern_sge32[i].length = ioc->sgl[i].iov_len;
2571
2572                 /*
2573                  * We created a kernel buffer corresponding to the
2574                  * user buffer. Now copy in from the user buffer
2575                  */
2576                 if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
2577                                    (u32) (ioc->sgl[i].iov_len))) {
2578                         error = -EFAULT;
2579                         goto out;
2580                 }
2581         }
2582
2583         if (ioc->sense_len) {
2584                 sense = pci_alloc_consistent(instance->pdev, ioc->sense_len,
2585                                              &sense_handle);
2586                 if (!sense) {
2587                         error = -ENOMEM;
2588                         goto out;
2589                 }
2590
2591                 sense_ptr =
2592                     (u32 *) ((unsigned long)cmd->frame + ioc->sense_off);
2593                 *sense_ptr = sense_handle;
2594         }
2595
2596         /*
2597          * Set the sync_cmd flag so that the ISR knows not to complete this
2598          * cmd to the SCSI mid-layer
2599          */
2600         cmd->sync_cmd = 1;
2601         megasas_issue_blocked_cmd(instance, cmd);
2602         cmd->sync_cmd = 0;
2603
2604         /*
2605          * copy out the kernel buffers to user buffers
2606          */
2607         for (i = 0; i < ioc->sge_count; i++) {
2608                 if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
2609                                  ioc->sgl[i].iov_len)) {
2610                         error = -EFAULT;
2611                         goto out;
2612                 }
2613         }
2614
2615         /*
2616          * copy out the sense
2617          */
2618         if (ioc->sense_len) {
2619                 /*
2620                  * sense_ptr points to the location that has the user
2621                  * sense buffer address
2622                  */
2623                 sense_ptr = (u32 *) ((unsigned long)ioc->frame.raw +
2624                                      ioc->sense_off);
2625
2626                 if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
2627                                  sense, ioc->sense_len)) {
2628                         error = -EFAULT;
2629                         goto out;
2630                 }
2631         }
2632
2633         /*
2634          * copy the status codes returned by the fw
2635          */
2636         if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
2637                          &cmd->frame->hdr.cmd_status, sizeof(u8))) {
2638                 printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
2639                 error = -EFAULT;
2640         }
2641
2642       out:
2643         if (sense) {
2644                 pci_free_consistent(instance->pdev, ioc->sense_len,
2645                                     sense, sense_handle);
2646         }
2647
2648         for (i = 0; i < ioc->sge_count && kbuff_arr[i]; i++) {
2649                 pci_free_consistent(instance->pdev,
2650                                     kern_sge32[i].length,
2651                                     kbuff_arr[i], kern_sge32[i].phys_addr);
2652         }
2653
2654         megasas_return_cmd(instance, cmd);
2655         return error;
2656 }
2657
2658 static struct megasas_instance *megasas_lookup_instance(u16 host_no)
2659 {
2660         int i;
2661
2662         for (i = 0; i < megasas_mgmt_info.max_index; i++) {
2663
2664                 if ((megasas_mgmt_info.instance[i]) &&
2665                     (megasas_mgmt_info.instance[i]->host->host_no == host_no))
2666                         return megasas_mgmt_info.instance[i];
2667         }
2668
2669         return NULL;
2670 }
2671
2672 static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
2673 {
2674         struct megasas_iocpacket __user *user_ioc =
2675             (struct megasas_iocpacket __user *)arg;
2676         struct megasas_iocpacket *ioc;
2677         struct megasas_instance *instance;
2678         int error;
2679
2680         ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
2681         if (!ioc)
2682                 return -ENOMEM;
2683
2684         if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
2685                 error = -EFAULT;
2686                 goto out_kfree_ioc;
2687         }
2688
2689         instance = megasas_lookup_instance(ioc->host_no);
2690         if (!instance) {
2691                 error = -ENODEV;
2692                 goto out_kfree_ioc;
2693         }
2694
2695         /*
2696          * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
2697          */
2698         if (down_interruptible(&instance->ioctl_sem)) {
2699                 error = -ERESTARTSYS;
2700                 goto out_kfree_ioc;
2701         }
2702         error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
2703         up(&instance->ioctl_sem);
2704
2705       out_kfree_ioc:
2706         kfree(ioc);
2707         return error;
2708 }
2709
2710 static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
2711 {
2712         struct megasas_instance *instance;
2713         struct megasas_aen aen;
2714         int error;
2715
2716         if (file->private_data != file) {
2717                 printk(KERN_DEBUG "megasas: fasync_helper was not "
2718                        "called first\n");
2719                 return -EINVAL;
2720         }
2721
2722         if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
2723                 return -EFAULT;
2724
2725         instance = megasas_lookup_instance(aen.host_no);
2726
2727         if (!instance)
2728                 return -ENODEV;
2729
2730         down(&instance->aen_mutex);
2731         error = megasas_register_aen(instance, aen.seq_num,
2732                                      aen.class_locale_word);
2733         up(&instance->aen_mutex);
2734         return error;
2735 }
2736
2737 /**
2738  * megasas_mgmt_ioctl - char node ioctl entry point
2739  */
2740 static long
2741 megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2742 {
2743         switch (cmd) {
2744         case MEGASAS_IOC_FIRMWARE:
2745                 return megasas_mgmt_ioctl_fw(file, arg);
2746
2747         case MEGASAS_IOC_GET_AEN:
2748                 return megasas_mgmt_ioctl_aen(file, arg);
2749         }
2750
2751         return -ENOTTY;
2752 }
2753
2754 #ifdef CONFIG_COMPAT
2755 static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
2756 {
2757         struct compat_megasas_iocpacket __user *cioc =
2758             (struct compat_megasas_iocpacket __user *)arg;
2759         struct megasas_iocpacket __user *ioc =
2760             compat_alloc_user_space(sizeof(struct megasas_iocpacket));
2761         int i;
2762         int error = 0;
2763
2764         clear_user(ioc, sizeof(*ioc));
2765
2766         if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
2767             copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
2768             copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
2769             copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
2770             copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
2771             copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
2772                 return -EFAULT;
2773
2774         for (i = 0; i < MAX_IOCTL_SGE; i++) {
2775                 compat_uptr_t ptr;
2776
2777                 if (get_user(ptr, &cioc->sgl[i].iov_base) ||
2778                     put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
2779                     copy_in_user(&ioc->sgl[i].iov_len,
2780                                  &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
2781                         return -EFAULT;
2782         }
2783
2784         error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
2785
2786         if (copy_in_user(&cioc->frame.hdr.cmd_status,
2787                          &ioc->frame.hdr.cmd_status, sizeof(u8))) {
2788                 printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
2789                 return -EFAULT;
2790         }
2791         return error;
2792 }
2793
2794 static long
2795 megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
2796                           unsigned long arg)
2797 {
2798         switch (cmd) {
2799         case MEGASAS_IOC_FIRMWARE32:
2800                 return megasas_mgmt_compat_ioctl_fw(file, arg);
2801         case MEGASAS_IOC_GET_AEN:
2802                 return megasas_mgmt_ioctl_aen(file, arg);
2803         }
2804
2805         return -ENOTTY;
2806 }
2807 #endif
2808
2809 /*
2810  * File operations structure for management interface
2811  */
2812 static struct file_operations megasas_mgmt_fops = {
2813         .owner = THIS_MODULE,
2814         .open = megasas_mgmt_open,
2815         .release = megasas_mgmt_release,
2816         .fasync = megasas_mgmt_fasync,
2817         .unlocked_ioctl = megasas_mgmt_ioctl,
2818 #ifdef CONFIG_COMPAT
2819         .compat_ioctl = megasas_mgmt_compat_ioctl,
2820 #endif
2821 };
2822
2823 /*
2824  * PCI hotplug support registration structure
2825  */
2826 static struct pci_driver megasas_pci_driver = {
2827
2828         .name = "megaraid_sas",
2829         .id_table = megasas_pci_table,
2830         .probe = megasas_probe_one,
2831         .remove = __devexit_p(megasas_detach_one),
2832         .shutdown = megasas_shutdown,
2833 };
2834
2835 /*
2836  * Sysfs driver attributes
2837  */
2838 static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
2839 {
2840         return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
2841                         MEGASAS_VERSION);
2842 }
2843
2844 static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
2845
2846 static ssize_t
2847 megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
2848 {
2849         return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
2850                         MEGASAS_RELDATE);
2851 }
2852
2853 static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
2854                    NULL);
2855
2856 /**
2857  * megasas_init - Driver load entry point
2858  */
2859 static int __init megasas_init(void)
2860 {
2861         int rval;
2862
2863         /*
2864          * Announce driver version and other information
2865          */
2866         printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
2867                MEGASAS_EXT_VERSION);
2868
2869         memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
2870
2871         /*
2872          * Register character device node
2873          */
2874         rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
2875
2876         if (rval < 0) {
2877                 printk(KERN_DEBUG "megasas: failed to open device node\n");
2878                 return rval;
2879         }
2880
2881         megasas_mgmt_majorno = rval;
2882
2883         /*
2884          * Register ourselves as PCI hotplug module
2885          */
2886         rval = pci_register_driver(&megasas_pci_driver);
2887
2888         if (rval) {
2889                 printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
2890                 unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
2891         }
2892
2893         driver_create_file(&megasas_pci_driver.driver, &driver_attr_version);
2894         driver_create_file(&megasas_pci_driver.driver,
2895                            &driver_attr_release_date);
2896
2897         return rval;
2898 }
2899
2900 /**
2901  * megasas_exit - Driver unload entry point
2902  */
2903 static void __exit megasas_exit(void)
2904 {
2905         driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
2906         driver_remove_file(&megasas_pci_driver.driver,
2907                            &driver_attr_release_date);
2908
2909         pci_unregister_driver(&megasas_pci_driver);
2910         unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
2911 }
2912
2913 module_init(megasas_init);
2914 module_exit(megasas_exit);