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