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