GNU Linux-libre 4.14.324-gnu1
[releases.git] / drivers / scsi / megaraid.c
1 /*
2  *
3  *                      Linux MegaRAID device driver
4  *
5  * Copyright (c) 2002  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  * Copyright (c) 2002  Red Hat, Inc. All rights reserved.
13  *        - fixes
14  *        - speed-ups (list handling fixes, issued_list, optimizations.)
15  *        - lots of cleanups.
16  *
17  * Copyright (c) 2003  Christoph Hellwig  <hch@lst.de>
18  *        - new-style, hotplug-aware pci probing and scsi registration
19  *
20  * Version : v2.00.4 Mon Nov 14 14:02:43 EST 2005 - Seokmann Ju
21  *                                              <Seokmann.Ju@lsil.com>
22  *
23  * Description: Linux device driver for LSI Logic MegaRAID controller
24  *
25  * Supported controllers: MegaRAID 418, 428, 438, 466, 762, 467, 471, 490, 493
26  *                                      518, 520, 531, 532
27  *
28  * This driver is supported by LSI Logic, with assistance from Red Hat, Dell,
29  * and others. Please send updates to the mailing list
30  * linux-scsi@vger.kernel.org .
31  *
32  */
33
34 #include <linux/mm.h>
35 #include <linux/fs.h>
36 #include <linux/blkdev.h>
37 #include <linux/uaccess.h>
38 #include <asm/io.h>
39 #include <linux/completion.h>
40 #include <linux/delay.h>
41 #include <linux/proc_fs.h>
42 #include <linux/seq_file.h>
43 #include <linux/reboot.h>
44 #include <linux/module.h>
45 #include <linux/list.h>
46 #include <linux/interrupt.h>
47 #include <linux/pci.h>
48 #include <linux/init.h>
49 #include <linux/dma-mapping.h>
50 #include <linux/mutex.h>
51 #include <linux/slab.h>
52 #include <scsi/scsicam.h>
53
54 #include "scsi.h"
55 #include <scsi/scsi_host.h>
56
57 #include "megaraid.h"
58
59 #define MEGARAID_MODULE_VERSION "2.00.4"
60
61 MODULE_AUTHOR ("sju@lsil.com");
62 MODULE_DESCRIPTION ("LSI Logic MegaRAID legacy driver");
63 MODULE_LICENSE ("GPL");
64 MODULE_VERSION(MEGARAID_MODULE_VERSION);
65
66 static DEFINE_MUTEX(megadev_mutex);
67 static unsigned int max_cmd_per_lun = DEF_CMD_PER_LUN;
68 module_param(max_cmd_per_lun, uint, 0);
69 MODULE_PARM_DESC(max_cmd_per_lun, "Maximum number of commands which can be issued to a single LUN (default=DEF_CMD_PER_LUN=63)");
70
71 static unsigned short int max_sectors_per_io = MAX_SECTORS_PER_IO;
72 module_param(max_sectors_per_io, ushort, 0);
73 MODULE_PARM_DESC(max_sectors_per_io, "Maximum number of sectors per I/O request (default=MAX_SECTORS_PER_IO=128)");
74
75
76 static unsigned short int max_mbox_busy_wait = MBOX_BUSY_WAIT;
77 module_param(max_mbox_busy_wait, ushort, 0);
78 MODULE_PARM_DESC(max_mbox_busy_wait, "Maximum wait for mailbox in microseconds if busy (default=MBOX_BUSY_WAIT=10)");
79
80 #define RDINDOOR(adapter)       readl((adapter)->mmio_base + 0x20)
81 #define RDOUTDOOR(adapter)      readl((adapter)->mmio_base + 0x2C)
82 #define WRINDOOR(adapter,value)  writel(value, (adapter)->mmio_base + 0x20)
83 #define WROUTDOOR(adapter,value) writel(value, (adapter)->mmio_base + 0x2C)
84
85 /*
86  * Global variables
87  */
88
89 static int hba_count;
90 static adapter_t *hba_soft_state[MAX_CONTROLLERS];
91 static struct proc_dir_entry *mega_proc_dir_entry;
92
93 /* For controller re-ordering */
94 static struct mega_hbas mega_hbas[MAX_CONTROLLERS];
95
96 static long
97 megadev_unlocked_ioctl(struct file *filep, unsigned int cmd, unsigned long arg);
98
99 /*
100  * The File Operations structure for the serial/ioctl interface of the driver
101  */
102 static const struct file_operations megadev_fops = {
103         .owner          = THIS_MODULE,
104         .unlocked_ioctl = megadev_unlocked_ioctl,
105         .open           = megadev_open,
106         .llseek         = noop_llseek,
107 };
108
109 /*
110  * Array to structures for storing the information about the controllers. This
111  * information is sent to the user level applications, when they do an ioctl
112  * for this information.
113  */
114 static struct mcontroller mcontroller[MAX_CONTROLLERS];
115
116 /* The current driver version */
117 static u32 driver_ver = 0x02000000;
118
119 /* major number used by the device for character interface */
120 static int major;
121
122 #define IS_RAID_CH(hba, ch)     (((hba)->mega_ch_class >> (ch)) & 0x01)
123
124
125 /*
126  * Debug variable to print some diagnostic messages
127  */
128 static int trace_level;
129
130 /**
131  * mega_setup_mailbox()
132  * @adapter - pointer to our soft state
133  *
134  * Allocates a 8 byte aligned memory for the handshake mailbox.
135  */
136 static int
137 mega_setup_mailbox(adapter_t *adapter)
138 {
139         unsigned long   align;
140
141         adapter->una_mbox64 = pci_alloc_consistent(adapter->dev,
142                         sizeof(mbox64_t), &adapter->una_mbox64_dma);
143
144         if( !adapter->una_mbox64 ) return -1;
145                 
146         adapter->mbox = &adapter->una_mbox64->mbox;
147
148         adapter->mbox = (mbox_t *)((((unsigned long) adapter->mbox) + 15) &
149                         (~0UL ^ 0xFUL));
150
151         adapter->mbox64 = (mbox64_t *)(((unsigned long)adapter->mbox) - 8);
152
153         align = ((void *)adapter->mbox) - ((void *)&adapter->una_mbox64->mbox);
154
155         adapter->mbox_dma = adapter->una_mbox64_dma + 8 + align;
156
157         /*
158          * Register the mailbox if the controller is an io-mapped controller
159          */
160         if( adapter->flag & BOARD_IOMAP ) {
161
162                 outb(adapter->mbox_dma & 0xFF,
163                                 adapter->host->io_port + MBOX_PORT0);
164
165                 outb((adapter->mbox_dma >> 8) & 0xFF,
166                                 adapter->host->io_port + MBOX_PORT1);
167
168                 outb((adapter->mbox_dma >> 16) & 0xFF,
169                                 adapter->host->io_port + MBOX_PORT2);
170
171                 outb((adapter->mbox_dma >> 24) & 0xFF,
172                                 adapter->host->io_port + MBOX_PORT3);
173
174                 outb(ENABLE_MBOX_BYTE,
175                                 adapter->host->io_port + ENABLE_MBOX_REGION);
176
177                 irq_ack(adapter);
178
179                 irq_enable(adapter);
180         }
181
182         return 0;
183 }
184
185
186 /*
187  * mega_query_adapter()
188  * @adapter - pointer to our soft state
189  *
190  * Issue the adapter inquiry commands to the controller and find out
191  * information and parameter about the devices attached
192  */
193 static int
194 mega_query_adapter(adapter_t *adapter)
195 {
196         dma_addr_t      prod_info_dma_handle;
197         mega_inquiry3   *inquiry3;
198         u8      raw_mbox[sizeof(struct mbox_out)];
199         mbox_t  *mbox;
200         int     retval;
201
202         /* Initialize adapter inquiry mailbox */
203
204         mbox = (mbox_t *)raw_mbox;
205
206         memset((void *)adapter->mega_buffer, 0, MEGA_BUFFER_SIZE);
207         memset(&mbox->m_out, 0, sizeof(raw_mbox));
208
209         /*
210          * Try to issue Inquiry3 command
211          * if not succeeded, then issue MEGA_MBOXCMD_ADAPTERINQ command and
212          * update enquiry3 structure
213          */
214         mbox->m_out.xferaddr = (u32)adapter->buf_dma_handle;
215
216         inquiry3 = (mega_inquiry3 *)adapter->mega_buffer;
217
218         raw_mbox[0] = FC_NEW_CONFIG;            /* i.e. mbox->cmd=0xA1 */
219         raw_mbox[2] = NC_SUBOP_ENQUIRY3;        /* i.e. 0x0F */
220         raw_mbox[3] = ENQ3_GET_SOLICITED_FULL;  /* i.e. 0x02 */
221
222         /* Issue a blocking command to the card */
223         if ((retval = issue_scb_block(adapter, raw_mbox))) {
224                 /* the adapter does not support 40ld */
225
226                 mraid_ext_inquiry       *ext_inq;
227                 mraid_inquiry           *inq;
228                 dma_addr_t              dma_handle;
229
230                 ext_inq = pci_alloc_consistent(adapter->dev,
231                                 sizeof(mraid_ext_inquiry), &dma_handle);
232
233                 if( ext_inq == NULL ) return -1;
234
235                 inq = &ext_inq->raid_inq;
236
237                 mbox->m_out.xferaddr = (u32)dma_handle;
238
239                 /*issue old 0x04 command to adapter */
240                 mbox->m_out.cmd = MEGA_MBOXCMD_ADPEXTINQ;
241
242                 issue_scb_block(adapter, raw_mbox);
243
244                 /*
245                  * update Enquiry3 and ProductInfo structures with
246                  * mraid_inquiry structure
247                  */
248                 mega_8_to_40ld(inq, inquiry3,
249                                 (mega_product_info *)&adapter->product_info);
250
251                 pci_free_consistent(adapter->dev, sizeof(mraid_ext_inquiry),
252                                 ext_inq, dma_handle);
253
254         } else {                /*adapter supports 40ld */
255                 adapter->flag |= BOARD_40LD;
256
257                 /*
258                  * get product_info, which is static information and will be
259                  * unchanged
260                  */
261                 prod_info_dma_handle = pci_map_single(adapter->dev, (void *)
262                                 &adapter->product_info,
263                                 sizeof(mega_product_info), PCI_DMA_FROMDEVICE);
264
265                 mbox->m_out.xferaddr = prod_info_dma_handle;
266
267                 raw_mbox[0] = FC_NEW_CONFIG;    /* i.e. mbox->cmd=0xA1 */
268                 raw_mbox[2] = NC_SUBOP_PRODUCT_INFO;    /* i.e. 0x0E */
269
270                 if ((retval = issue_scb_block(adapter, raw_mbox)))
271                         dev_warn(&adapter->dev->dev,
272                                 "Product_info cmd failed with error: %d\n",
273                                 retval);
274
275                 pci_unmap_single(adapter->dev, prod_info_dma_handle,
276                                 sizeof(mega_product_info), PCI_DMA_FROMDEVICE);
277         }
278
279
280         /*
281          * kernel scans the channels from 0 to <= max_channel
282          */
283         adapter->host->max_channel =
284                 adapter->product_info.nchannels + NVIRT_CHAN -1;
285
286         adapter->host->max_id = 16;     /* max targets per channel */
287
288         adapter->host->max_lun = 7;     /* Up to 7 luns for non disk devices */
289
290         adapter->host->cmd_per_lun = max_cmd_per_lun;
291
292         adapter->numldrv = inquiry3->num_ldrv;
293
294         adapter->max_cmds = adapter->product_info.max_commands;
295
296         if(adapter->max_cmds > MAX_COMMANDS)
297                 adapter->max_cmds = MAX_COMMANDS;
298
299         adapter->host->can_queue = adapter->max_cmds - 1;
300
301         /*
302          * Get the maximum number of scatter-gather elements supported by this
303          * firmware
304          */
305         mega_get_max_sgl(adapter);
306
307         adapter->host->sg_tablesize = adapter->sglen;
308
309         /* use HP firmware and bios version encoding
310            Note: fw_version[0|1] and bios_version[0|1] were originally shifted
311            right 8 bits making them zero. This 0 value was hardcoded to fix
312            sparse warnings. */
313         if (adapter->product_info.subsysvid == PCI_VENDOR_ID_HP) {
314                 snprintf(adapter->fw_version, sizeof(adapter->fw_version),
315                          "%c%d%d.%d%d",
316                          adapter->product_info.fw_version[2],
317                          0,
318                          adapter->product_info.fw_version[1] & 0x0f,
319                          0,
320                          adapter->product_info.fw_version[0] & 0x0f);
321                 snprintf(adapter->bios_version, sizeof(adapter->fw_version),
322                          "%c%d%d.%d%d",
323                          adapter->product_info.bios_version[2],
324                          0,
325                          adapter->product_info.bios_version[1] & 0x0f,
326                          0,
327                          adapter->product_info.bios_version[0] & 0x0f);
328         } else {
329                 memcpy(adapter->fw_version,
330                                 (char *)adapter->product_info.fw_version, 4);
331                 adapter->fw_version[4] = 0;
332
333                 memcpy(adapter->bios_version,
334                                 (char *)adapter->product_info.bios_version, 4);
335
336                 adapter->bios_version[4] = 0;
337         }
338
339         dev_notice(&adapter->dev->dev, "[%s:%s] detected %d logical drives\n",
340                 adapter->fw_version, adapter->bios_version, adapter->numldrv);
341
342         /*
343          * Do we support extended (>10 bytes) cdbs
344          */
345         adapter->support_ext_cdb = mega_support_ext_cdb(adapter);
346         if (adapter->support_ext_cdb)
347                 dev_notice(&adapter->dev->dev, "supports extended CDBs\n");
348
349
350         return 0;
351 }
352
353 /**
354  * mega_runpendq()
355  * @adapter - pointer to our soft state
356  *
357  * Runs through the list of pending requests.
358  */
359 static inline void
360 mega_runpendq(adapter_t *adapter)
361 {
362         if(!list_empty(&adapter->pending_list))
363                 __mega_runpendq(adapter);
364 }
365
366 /*
367  * megaraid_queue()
368  * @scmd - Issue this scsi command
369  * @done - the callback hook into the scsi mid-layer
370  *
371  * The command queuing entry point for the mid-layer.
372  */
373 static int
374 megaraid_queue_lck(Scsi_Cmnd *scmd, void (*done)(Scsi_Cmnd *))
375 {
376         adapter_t       *adapter;
377         scb_t   *scb;
378         int     busy=0;
379         unsigned long flags;
380
381         adapter = (adapter_t *)scmd->device->host->hostdata;
382
383         scmd->scsi_done = done;
384
385
386         /*
387          * Allocate and build a SCB request
388          * busy flag will be set if mega_build_cmd() command could not
389          * allocate scb. We will return non-zero status in that case.
390          * NOTE: scb can be null even though certain commands completed
391          * successfully, e.g., MODE_SENSE and TEST_UNIT_READY, we would
392          * return 0 in that case.
393          */
394
395         spin_lock_irqsave(&adapter->lock, flags);
396         scb = mega_build_cmd(adapter, scmd, &busy);
397         if (!scb)
398                 goto out;
399
400         scb->state |= SCB_PENDQ;
401         list_add_tail(&scb->list, &adapter->pending_list);
402
403         /*
404          * Check if the HBA is in quiescent state, e.g., during a
405          * delete logical drive opertion. If it is, don't run
406          * the pending_list.
407          */
408         if (atomic_read(&adapter->quiescent) == 0)
409                 mega_runpendq(adapter);
410
411         busy = 0;
412  out:
413         spin_unlock_irqrestore(&adapter->lock, flags);
414         return busy;
415 }
416
417 static DEF_SCSI_QCMD(megaraid_queue)
418
419 /**
420  * mega_allocate_scb()
421  * @adapter - pointer to our soft state
422  * @cmd - scsi command from the mid-layer
423  *
424  * Allocate a SCB structure. This is the central structure for controller
425  * commands.
426  */
427 static inline scb_t *
428 mega_allocate_scb(adapter_t *adapter, Scsi_Cmnd *cmd)
429 {
430         struct list_head *head = &adapter->free_list;
431         scb_t   *scb;
432
433         /* Unlink command from Free List */
434         if( !list_empty(head) ) {
435
436                 scb = list_entry(head->next, scb_t, list);
437
438                 list_del_init(head->next);
439
440                 scb->state = SCB_ACTIVE;
441                 scb->cmd = cmd;
442                 scb->dma_type = MEGA_DMA_TYPE_NONE;
443
444                 return scb;
445         }
446
447         return NULL;
448 }
449
450 /**
451  * mega_get_ldrv_num()
452  * @adapter - pointer to our soft state
453  * @cmd - scsi mid layer command
454  * @channel - channel on the controller
455  *
456  * Calculate the logical drive number based on the information in scsi command
457  * and the channel number.
458  */
459 static inline int
460 mega_get_ldrv_num(adapter_t *adapter, Scsi_Cmnd *cmd, int channel)
461 {
462         int             tgt;
463         int             ldrv_num;
464
465         tgt = cmd->device->id;
466         
467         if ( tgt > adapter->this_id )
468                 tgt--;  /* we do not get inquires for initiator id */
469
470         ldrv_num = (channel * 15) + tgt;
471
472
473         /*
474          * If we have a logical drive with boot enabled, project it first
475          */
476         if( adapter->boot_ldrv_enabled ) {
477                 if( ldrv_num == 0 ) {
478                         ldrv_num = adapter->boot_ldrv;
479                 }
480                 else {
481                         if( ldrv_num <= adapter->boot_ldrv ) {
482                                 ldrv_num--;
483                         }
484                 }
485         }
486
487         /*
488          * If "delete logical drive" feature is enabled on this controller.
489          * Do only if at least one delete logical drive operation was done.
490          *
491          * Also, after logical drive deletion, instead of logical drive number,
492          * the value returned should be 0x80+logical drive id.
493          *
494          * These is valid only for IO commands.
495          */
496
497         if (adapter->support_random_del && adapter->read_ldidmap )
498                 switch (cmd->cmnd[0]) {
499                 case READ_6:    /* fall through */
500                 case WRITE_6:   /* fall through */
501                 case READ_10:   /* fall through */
502                 case WRITE_10:
503                         ldrv_num += 0x80;
504                 }
505
506         return ldrv_num;
507 }
508
509 /**
510  * mega_build_cmd()
511  * @adapter - pointer to our soft state
512  * @cmd - Prepare using this scsi command
513  * @busy - busy flag if no resources
514  *
515  * Prepares a command and scatter gather list for the controller. This routine
516  * also finds out if the commands is intended for a logical drive or a
517  * physical device and prepares the controller command accordingly.
518  *
519  * We also re-order the logical drives and physical devices based on their
520  * boot settings.
521  */
522 static scb_t *
523 mega_build_cmd(adapter_t *adapter, Scsi_Cmnd *cmd, int *busy)
524 {
525         mega_ext_passthru       *epthru;
526         mega_passthru   *pthru;
527         scb_t   *scb;
528         mbox_t  *mbox;
529         u32     seg;
530         char    islogical;
531         int     max_ldrv_num;
532         int     channel = 0;
533         int     target = 0;
534         int     ldrv_num = 0;   /* logical drive number */
535
536         /*
537          * We know what channels our logical drives are on - mega_find_card()
538          */
539         islogical = adapter->logdrv_chan[cmd->device->channel];
540
541         /*
542          * The theory: If physical drive is chosen for boot, all the physical
543          * devices are exported before the logical drives, otherwise physical
544          * devices are pushed after logical drives, in which case - Kernel sees
545          * the physical devices on virtual channel which is obviously converted
546          * to actual channel on the HBA.
547          */
548         if( adapter->boot_pdrv_enabled ) {
549                 if( islogical ) {
550                         /* logical channel */
551                         channel = cmd->device->channel -
552                                 adapter->product_info.nchannels;
553                 }
554                 else {
555                         /* this is physical channel */
556                         channel = cmd->device->channel; 
557                         target = cmd->device->id;
558
559                         /*
560                          * boot from a physical disk, that disk needs to be
561                          * exposed first IF both the channels are SCSI, then
562                          * booting from the second channel is not allowed.
563                          */
564                         if( target == 0 ) {
565                                 target = adapter->boot_pdrv_tgt;
566                         }
567                         else if( target == adapter->boot_pdrv_tgt ) {
568                                 target = 0;
569                         }
570                 }
571         }
572         else {
573                 if( islogical ) {
574                         /* this is the logical channel */
575                         channel = cmd->device->channel; 
576                 }
577                 else {
578                         /* physical channel */
579                         channel = cmd->device->channel - NVIRT_CHAN;    
580                         target = cmd->device->id;
581                 }
582         }
583
584
585         if(islogical) {
586
587                 /* have just LUN 0 for each target on virtual channels */
588                 if (cmd->device->lun) {
589                         cmd->result = (DID_BAD_TARGET << 16);
590                         cmd->scsi_done(cmd);
591                         return NULL;
592                 }
593
594                 ldrv_num = mega_get_ldrv_num(adapter, cmd, channel);
595
596
597                 max_ldrv_num = (adapter->flag & BOARD_40LD) ?
598                         MAX_LOGICAL_DRIVES_40LD : MAX_LOGICAL_DRIVES_8LD;
599
600                 /*
601                  * max_ldrv_num increases by 0x80 if some logical drive was
602                  * deleted.
603                  */
604                 if(adapter->read_ldidmap)
605                         max_ldrv_num += 0x80;
606
607                 if(ldrv_num > max_ldrv_num ) {
608                         cmd->result = (DID_BAD_TARGET << 16);
609                         cmd->scsi_done(cmd);
610                         return NULL;
611                 }
612
613         }
614         else {
615                 if( cmd->device->lun > 7) {
616                         /*
617                          * Do not support lun >7 for physically accessed
618                          * devices
619                          */
620                         cmd->result = (DID_BAD_TARGET << 16);
621                         cmd->scsi_done(cmd);
622                         return NULL;
623                 }
624         }
625
626         /*
627          *
628          * Logical drive commands
629          *
630          */
631         if(islogical) {
632                 switch (cmd->cmnd[0]) {
633                 case TEST_UNIT_READY:
634 #if MEGA_HAVE_CLUSTERING
635                         /*
636                          * Do we support clustering and is the support enabled
637                          * If no, return success always
638                          */
639                         if( !adapter->has_cluster ) {
640                                 cmd->result = (DID_OK << 16);
641                                 cmd->scsi_done(cmd);
642                                 return NULL;
643                         }
644
645                         if(!(scb = mega_allocate_scb(adapter, cmd))) {
646                                 *busy = 1;
647                                 return NULL;
648                         }
649
650                         scb->raw_mbox[0] = MEGA_CLUSTER_CMD;
651                         scb->raw_mbox[2] = MEGA_RESERVATION_STATUS;
652                         scb->raw_mbox[3] = ldrv_num;
653
654                         scb->dma_direction = PCI_DMA_NONE;
655
656                         return scb;
657 #else
658                         cmd->result = (DID_OK << 16);
659                         cmd->scsi_done(cmd);
660                         return NULL;
661 #endif
662
663                 case MODE_SENSE: {
664                         char *buf;
665                         struct scatterlist *sg;
666
667                         sg = scsi_sglist(cmd);
668                         buf = kmap_atomic(sg_page(sg)) + sg->offset;
669
670                         memset(buf, 0, cmd->cmnd[4]);
671                         kunmap_atomic(buf - sg->offset);
672
673                         cmd->result = (DID_OK << 16);
674                         cmd->scsi_done(cmd);
675                         return NULL;
676                 }
677
678                 case READ_CAPACITY:
679                 case INQUIRY:
680
681                         if(!(adapter->flag & (1L << cmd->device->channel))) {
682
683                                 dev_notice(&adapter->dev->dev,
684                                         "scsi%d: scanning scsi channel %d "
685                                         "for logical drives\n",
686                                                 adapter->host->host_no,
687                                                 cmd->device->channel);
688
689                                 adapter->flag |= (1L << cmd->device->channel);
690                         }
691
692                         /* Allocate a SCB and initialize passthru */
693                         if(!(scb = mega_allocate_scb(adapter, cmd))) {
694                                 *busy = 1;
695                                 return NULL;
696                         }
697                         pthru = scb->pthru;
698
699                         mbox = (mbox_t *)scb->raw_mbox;
700                         memset(mbox, 0, sizeof(scb->raw_mbox));
701                         memset(pthru, 0, sizeof(mega_passthru));
702
703                         pthru->timeout = 0;
704                         pthru->ars = 1;
705                         pthru->reqsenselen = 14;
706                         pthru->islogical = 1;
707                         pthru->logdrv = ldrv_num;
708                         pthru->cdblen = cmd->cmd_len;
709                         memcpy(pthru->cdb, cmd->cmnd, cmd->cmd_len);
710
711                         if( adapter->has_64bit_addr ) {
712                                 mbox->m_out.cmd = MEGA_MBOXCMD_PASSTHRU64;
713                         }
714                         else {
715                                 mbox->m_out.cmd = MEGA_MBOXCMD_PASSTHRU;
716                         }
717
718                         scb->dma_direction = PCI_DMA_FROMDEVICE;
719
720                         pthru->numsgelements = mega_build_sglist(adapter, scb,
721                                 &pthru->dataxferaddr, &pthru->dataxferlen);
722
723                         mbox->m_out.xferaddr = scb->pthru_dma_addr;
724
725                         return scb;
726
727                 case READ_6:
728                 case WRITE_6:
729                 case READ_10:
730                 case WRITE_10:
731                 case READ_12:
732                 case WRITE_12:
733
734                         /* Allocate a SCB and initialize mailbox */
735                         if(!(scb = mega_allocate_scb(adapter, cmd))) {
736                                 *busy = 1;
737                                 return NULL;
738                         }
739                         mbox = (mbox_t *)scb->raw_mbox;
740
741                         memset(mbox, 0, sizeof(scb->raw_mbox));
742                         mbox->m_out.logdrv = ldrv_num;
743
744                         /*
745                          * A little hack: 2nd bit is zero for all scsi read
746                          * commands and is set for all scsi write commands
747                          */
748                         if( adapter->has_64bit_addr ) {
749                                 mbox->m_out.cmd = (*cmd->cmnd & 0x02) ?
750                                         MEGA_MBOXCMD_LWRITE64:
751                                         MEGA_MBOXCMD_LREAD64 ;
752                         }
753                         else {
754                                 mbox->m_out.cmd = (*cmd->cmnd & 0x02) ?
755                                         MEGA_MBOXCMD_LWRITE:
756                                         MEGA_MBOXCMD_LREAD ;
757                         }
758
759                         /*
760                          * 6-byte READ(0x08) or WRITE(0x0A) cdb
761                          */
762                         if( cmd->cmd_len == 6 ) {
763                                 mbox->m_out.numsectors = (u32) cmd->cmnd[4];
764                                 mbox->m_out.lba =
765                                         ((u32)cmd->cmnd[1] << 16) |
766                                         ((u32)cmd->cmnd[2] << 8) |
767                                         (u32)cmd->cmnd[3];
768
769                                 mbox->m_out.lba &= 0x1FFFFF;
770
771 #if MEGA_HAVE_STATS
772                                 /*
773                                  * Take modulo 0x80, since the logical drive
774                                  * number increases by 0x80 when a logical
775                                  * drive was deleted
776                                  */
777                                 if (*cmd->cmnd == READ_6) {
778                                         adapter->nreads[ldrv_num%0x80]++;
779                                         adapter->nreadblocks[ldrv_num%0x80] +=
780                                                 mbox->m_out.numsectors;
781                                 } else {
782                                         adapter->nwrites[ldrv_num%0x80]++;
783                                         adapter->nwriteblocks[ldrv_num%0x80] +=
784                                                 mbox->m_out.numsectors;
785                                 }
786 #endif
787                         }
788
789                         /*
790                          * 10-byte READ(0x28) or WRITE(0x2A) cdb
791                          */
792                         if( cmd->cmd_len == 10 ) {
793                                 mbox->m_out.numsectors =
794                                         (u32)cmd->cmnd[8] |
795                                         ((u32)cmd->cmnd[7] << 8);
796                                 mbox->m_out.lba =
797                                         ((u32)cmd->cmnd[2] << 24) |
798                                         ((u32)cmd->cmnd[3] << 16) |
799                                         ((u32)cmd->cmnd[4] << 8) |
800                                         (u32)cmd->cmnd[5];
801
802 #if MEGA_HAVE_STATS
803                                 if (*cmd->cmnd == READ_10) {
804                                         adapter->nreads[ldrv_num%0x80]++;
805                                         adapter->nreadblocks[ldrv_num%0x80] +=
806                                                 mbox->m_out.numsectors;
807                                 } else {
808                                         adapter->nwrites[ldrv_num%0x80]++;
809                                         adapter->nwriteblocks[ldrv_num%0x80] +=
810                                                 mbox->m_out.numsectors;
811                                 }
812 #endif
813                         }
814
815                         /*
816                          * 12-byte READ(0xA8) or WRITE(0xAA) cdb
817                          */
818                         if( cmd->cmd_len == 12 ) {
819                                 mbox->m_out.lba =
820                                         ((u32)cmd->cmnd[2] << 24) |
821                                         ((u32)cmd->cmnd[3] << 16) |
822                                         ((u32)cmd->cmnd[4] << 8) |
823                                         (u32)cmd->cmnd[5];
824
825                                 mbox->m_out.numsectors =
826                                         ((u32)cmd->cmnd[6] << 24) |
827                                         ((u32)cmd->cmnd[7] << 16) |
828                                         ((u32)cmd->cmnd[8] << 8) |
829                                         (u32)cmd->cmnd[9];
830
831 #if MEGA_HAVE_STATS
832                                 if (*cmd->cmnd == READ_12) {
833                                         adapter->nreads[ldrv_num%0x80]++;
834                                         adapter->nreadblocks[ldrv_num%0x80] +=
835                                                 mbox->m_out.numsectors;
836                                 } else {
837                                         adapter->nwrites[ldrv_num%0x80]++;
838                                         adapter->nwriteblocks[ldrv_num%0x80] +=
839                                                 mbox->m_out.numsectors;
840                                 }
841 #endif
842                         }
843
844                         /*
845                          * If it is a read command
846                          */
847                         if( (*cmd->cmnd & 0x0F) == 0x08 ) {
848                                 scb->dma_direction = PCI_DMA_FROMDEVICE;
849                         }
850                         else {
851                                 scb->dma_direction = PCI_DMA_TODEVICE;
852                         }
853
854                         /* Calculate Scatter-Gather info */
855                         mbox->m_out.numsgelements = mega_build_sglist(adapter, scb,
856                                         (u32 *)&mbox->m_out.xferaddr, &seg);
857
858                         return scb;
859
860 #if MEGA_HAVE_CLUSTERING
861                 case RESERVE:   /* Fall through */
862                 case RELEASE:
863
864                         /*
865                          * Do we support clustering and is the support enabled
866                          */
867                         if( ! adapter->has_cluster ) {
868
869                                 cmd->result = (DID_BAD_TARGET << 16);
870                                 cmd->scsi_done(cmd);
871                                 return NULL;
872                         }
873
874                         /* Allocate a SCB and initialize mailbox */
875                         if(!(scb = mega_allocate_scb(adapter, cmd))) {
876                                 *busy = 1;
877                                 return NULL;
878                         }
879
880                         scb->raw_mbox[0] = MEGA_CLUSTER_CMD;
881                         scb->raw_mbox[2] = ( *cmd->cmnd == RESERVE ) ?
882                                 MEGA_RESERVE_LD : MEGA_RELEASE_LD;
883
884                         scb->raw_mbox[3] = ldrv_num;
885
886                         scb->dma_direction = PCI_DMA_NONE;
887
888                         return scb;
889 #endif
890
891                 default:
892                         cmd->result = (DID_BAD_TARGET << 16);
893                         cmd->scsi_done(cmd);
894                         return NULL;
895                 }
896         }
897
898         /*
899          * Passthru drive commands
900          */
901         else {
902                 /* Allocate a SCB and initialize passthru */
903                 if(!(scb = mega_allocate_scb(adapter, cmd))) {
904                         *busy = 1;
905                         return NULL;
906                 }
907
908                 mbox = (mbox_t *)scb->raw_mbox;
909                 memset(mbox, 0, sizeof(scb->raw_mbox));
910
911                 if( adapter->support_ext_cdb ) {
912
913                         epthru = mega_prepare_extpassthru(adapter, scb, cmd,
914                                         channel, target);
915
916                         mbox->m_out.cmd = MEGA_MBOXCMD_EXTPTHRU;
917
918                         mbox->m_out.xferaddr = scb->epthru_dma_addr;
919
920                 }
921                 else {
922
923                         pthru = mega_prepare_passthru(adapter, scb, cmd,
924                                         channel, target);
925
926                         /* Initialize mailbox */
927                         if( adapter->has_64bit_addr ) {
928                                 mbox->m_out.cmd = MEGA_MBOXCMD_PASSTHRU64;
929                         }
930                         else {
931                                 mbox->m_out.cmd = MEGA_MBOXCMD_PASSTHRU;
932                         }
933
934                         mbox->m_out.xferaddr = scb->pthru_dma_addr;
935
936                 }
937                 return scb;
938         }
939         return NULL;
940 }
941
942
943 /**
944  * mega_prepare_passthru()
945  * @adapter - pointer to our soft state
946  * @scb - our scsi control block
947  * @cmd - scsi command from the mid-layer
948  * @channel - actual channel on the controller
949  * @target - actual id on the controller.
950  *
951  * prepare a command for the scsi physical devices.
952  */
953 static mega_passthru *
954 mega_prepare_passthru(adapter_t *adapter, scb_t *scb, Scsi_Cmnd *cmd,
955                 int channel, int target)
956 {
957         mega_passthru *pthru;
958
959         pthru = scb->pthru;
960         memset(pthru, 0, sizeof (mega_passthru));
961
962         /* 0=6sec/1=60sec/2=10min/3=3hrs */
963         pthru->timeout = 2;
964
965         pthru->ars = 1;
966         pthru->reqsenselen = 14;
967         pthru->islogical = 0;
968
969         pthru->channel = (adapter->flag & BOARD_40LD) ? 0 : channel;
970
971         pthru->target = (adapter->flag & BOARD_40LD) ?
972                 (channel << 4) | target : target;
973
974         pthru->cdblen = cmd->cmd_len;
975         pthru->logdrv = cmd->device->lun;
976
977         memcpy(pthru->cdb, cmd->cmnd, cmd->cmd_len);
978
979         /* Not sure about the direction */
980         scb->dma_direction = PCI_DMA_BIDIRECTIONAL;
981
982         /* Special Code for Handling READ_CAPA/ INQ using bounce buffers */
983         switch (cmd->cmnd[0]) {
984         case INQUIRY:
985         case READ_CAPACITY:
986                 if(!(adapter->flag & (1L << cmd->device->channel))) {
987
988                         dev_notice(&adapter->dev->dev,
989                                 "scsi%d: scanning scsi channel %d [P%d] "
990                                 "for physical devices\n",
991                                         adapter->host->host_no,
992                                         cmd->device->channel, channel);
993
994                         adapter->flag |= (1L << cmd->device->channel);
995                 }
996                 /* Fall through */
997         default:
998                 pthru->numsgelements = mega_build_sglist(adapter, scb,
999                                 &pthru->dataxferaddr, &pthru->dataxferlen);
1000                 break;
1001         }
1002         return pthru;
1003 }
1004
1005
1006 /**
1007  * mega_prepare_extpassthru()
1008  * @adapter - pointer to our soft state
1009  * @scb - our scsi control block
1010  * @cmd - scsi command from the mid-layer
1011  * @channel - actual channel on the controller
1012  * @target - actual id on the controller.
1013  *
1014  * prepare a command for the scsi physical devices. This rountine prepares
1015  * commands for devices which can take extended CDBs (>10 bytes)
1016  */
1017 static mega_ext_passthru *
1018 mega_prepare_extpassthru(adapter_t *adapter, scb_t *scb, Scsi_Cmnd *cmd,
1019                 int channel, int target)
1020 {
1021         mega_ext_passthru       *epthru;
1022
1023         epthru = scb->epthru;
1024         memset(epthru, 0, sizeof(mega_ext_passthru));
1025
1026         /* 0=6sec/1=60sec/2=10min/3=3hrs */
1027         epthru->timeout = 2;
1028
1029         epthru->ars = 1;
1030         epthru->reqsenselen = 14;
1031         epthru->islogical = 0;
1032
1033         epthru->channel = (adapter->flag & BOARD_40LD) ? 0 : channel;
1034         epthru->target = (adapter->flag & BOARD_40LD) ?
1035                 (channel << 4) | target : target;
1036
1037         epthru->cdblen = cmd->cmd_len;
1038         epthru->logdrv = cmd->device->lun;
1039
1040         memcpy(epthru->cdb, cmd->cmnd, cmd->cmd_len);
1041
1042         /* Not sure about the direction */
1043         scb->dma_direction = PCI_DMA_BIDIRECTIONAL;
1044
1045         switch(cmd->cmnd[0]) {
1046         case INQUIRY:
1047         case READ_CAPACITY:
1048                 if(!(adapter->flag & (1L << cmd->device->channel))) {
1049
1050                         dev_notice(&adapter->dev->dev,
1051                                 "scsi%d: scanning scsi channel %d [P%d] "
1052                                 "for physical devices\n",
1053                                         adapter->host->host_no,
1054                                         cmd->device->channel, channel);
1055
1056                         adapter->flag |= (1L << cmd->device->channel);
1057                 }
1058                 /* Fall through */
1059         default:
1060                 epthru->numsgelements = mega_build_sglist(adapter, scb,
1061                                 &epthru->dataxferaddr, &epthru->dataxferlen);
1062                 break;
1063         }
1064
1065         return epthru;
1066 }
1067
1068 static void
1069 __mega_runpendq(adapter_t *adapter)
1070 {
1071         scb_t *scb;
1072         struct list_head *pos, *next;
1073
1074         /* Issue any pending commands to the card */
1075         list_for_each_safe(pos, next, &adapter->pending_list) {
1076
1077                 scb = list_entry(pos, scb_t, list);
1078
1079                 if( !(scb->state & SCB_ISSUED) ) {
1080
1081                         if( issue_scb(adapter, scb) != 0 )
1082                                 return;
1083                 }
1084         }
1085
1086         return;
1087 }
1088
1089
1090 /**
1091  * issue_scb()
1092  * @adapter - pointer to our soft state
1093  * @scb - scsi control block
1094  *
1095  * Post a command to the card if the mailbox is available, otherwise return
1096  * busy. We also take the scb from the pending list if the mailbox is
1097  * available.
1098  */
1099 static int
1100 issue_scb(adapter_t *adapter, scb_t *scb)
1101 {
1102         volatile mbox64_t       *mbox64 = adapter->mbox64;
1103         volatile mbox_t         *mbox = adapter->mbox;
1104         unsigned int    i = 0;
1105
1106         if(unlikely(mbox->m_in.busy)) {
1107                 do {
1108                         udelay(1);
1109                         i++;
1110                 } while( mbox->m_in.busy && (i < max_mbox_busy_wait) );
1111
1112                 if(mbox->m_in.busy) return -1;
1113         }
1114
1115         /* Copy mailbox data into host structure */
1116         memcpy((char *)&mbox->m_out, (char *)scb->raw_mbox, 
1117                         sizeof(struct mbox_out));
1118
1119         mbox->m_out.cmdid = scb->idx;   /* Set cmdid */
1120         mbox->m_in.busy = 1;            /* Set busy */
1121
1122
1123         /*
1124          * Increment the pending queue counter
1125          */
1126         atomic_inc(&adapter->pend_cmds);
1127
1128         switch (mbox->m_out.cmd) {
1129         case MEGA_MBOXCMD_LREAD64:
1130         case MEGA_MBOXCMD_LWRITE64:
1131         case MEGA_MBOXCMD_PASSTHRU64:
1132         case MEGA_MBOXCMD_EXTPTHRU:
1133                 mbox64->xfer_segment_lo = mbox->m_out.xferaddr;
1134                 mbox64->xfer_segment_hi = 0;
1135                 mbox->m_out.xferaddr = 0xFFFFFFFF;
1136                 break;
1137         default:
1138                 mbox64->xfer_segment_lo = 0;
1139                 mbox64->xfer_segment_hi = 0;
1140         }
1141
1142         /*
1143          * post the command
1144          */
1145         scb->state |= SCB_ISSUED;
1146
1147         if( likely(adapter->flag & BOARD_MEMMAP) ) {
1148                 mbox->m_in.poll = 0;
1149                 mbox->m_in.ack = 0;
1150                 WRINDOOR(adapter, adapter->mbox_dma | 0x1);
1151         }
1152         else {
1153                 irq_enable(adapter);
1154                 issue_command(adapter);
1155         }
1156
1157         return 0;
1158 }
1159
1160 /*
1161  * Wait until the controller's mailbox is available
1162  */
1163 static inline int
1164 mega_busywait_mbox (adapter_t *adapter)
1165 {
1166         if (adapter->mbox->m_in.busy)
1167                 return __mega_busywait_mbox(adapter);
1168         return 0;
1169 }
1170
1171 /**
1172  * issue_scb_block()
1173  * @adapter - pointer to our soft state
1174  * @raw_mbox - the mailbox
1175  *
1176  * Issue a scb in synchronous and non-interrupt mode
1177  */
1178 static int
1179 issue_scb_block(adapter_t *adapter, u_char *raw_mbox)
1180 {
1181         volatile mbox64_t *mbox64 = adapter->mbox64;
1182         volatile mbox_t *mbox = adapter->mbox;
1183         u8      byte;
1184
1185         /* Wait until mailbox is free */
1186         if(mega_busywait_mbox (adapter))
1187                 goto bug_blocked_mailbox;
1188
1189         /* Copy mailbox data into host structure */
1190         memcpy((char *) mbox, raw_mbox, sizeof(struct mbox_out));
1191         mbox->m_out.cmdid = 0xFE;
1192         mbox->m_in.busy = 1;
1193
1194         switch (raw_mbox[0]) {
1195         case MEGA_MBOXCMD_LREAD64:
1196         case MEGA_MBOXCMD_LWRITE64:
1197         case MEGA_MBOXCMD_PASSTHRU64:
1198         case MEGA_MBOXCMD_EXTPTHRU:
1199                 mbox64->xfer_segment_lo = mbox->m_out.xferaddr;
1200                 mbox64->xfer_segment_hi = 0;
1201                 mbox->m_out.xferaddr = 0xFFFFFFFF;
1202                 break;
1203         default:
1204                 mbox64->xfer_segment_lo = 0;
1205                 mbox64->xfer_segment_hi = 0;
1206         }
1207
1208         if( likely(adapter->flag & BOARD_MEMMAP) ) {
1209                 mbox->m_in.poll = 0;
1210                 mbox->m_in.ack = 0;
1211                 mbox->m_in.numstatus = 0xFF;
1212                 mbox->m_in.status = 0xFF;
1213                 WRINDOOR(adapter, adapter->mbox_dma | 0x1);
1214
1215                 while((volatile u8)mbox->m_in.numstatus == 0xFF)
1216                         cpu_relax();
1217
1218                 mbox->m_in.numstatus = 0xFF;
1219
1220                 while( (volatile u8)mbox->m_in.poll != 0x77 )
1221                         cpu_relax();
1222
1223                 mbox->m_in.poll = 0;
1224                 mbox->m_in.ack = 0x77;
1225
1226                 WRINDOOR(adapter, adapter->mbox_dma | 0x2);
1227
1228                 while(RDINDOOR(adapter) & 0x2)
1229                         cpu_relax();
1230         }
1231         else {
1232                 irq_disable(adapter);
1233                 issue_command(adapter);
1234
1235                 while (!((byte = irq_state(adapter)) & INTR_VALID))
1236                         cpu_relax();
1237
1238                 set_irq_state(adapter, byte);
1239                 irq_enable(adapter);
1240                 irq_ack(adapter);
1241         }
1242
1243         return mbox->m_in.status;
1244
1245 bug_blocked_mailbox:
1246         dev_warn(&adapter->dev->dev, "Blocked mailbox......!!\n");
1247         udelay (1000);
1248         return -1;
1249 }
1250
1251
1252 /**
1253  * megaraid_isr_iomapped()
1254  * @irq - irq
1255  * @devp - pointer to our soft state
1256  *
1257  * Interrupt service routine for io-mapped controllers.
1258  * Find out if our device is interrupting. If yes, acknowledge the interrupt
1259  * and service the completed commands.
1260  */
1261 static irqreturn_t
1262 megaraid_isr_iomapped(int irq, void *devp)
1263 {
1264         adapter_t       *adapter = devp;
1265         unsigned long   flags;
1266         u8      status;
1267         u8      nstatus;
1268         u8      completed[MAX_FIRMWARE_STATUS];
1269         u8      byte;
1270         int     handled = 0;
1271
1272
1273         /*
1274          * loop till F/W has more commands for us to complete.
1275          */
1276         spin_lock_irqsave(&adapter->lock, flags);
1277
1278         do {
1279                 /* Check if a valid interrupt is pending */
1280                 byte = irq_state(adapter);
1281                 if( (byte & VALID_INTR_BYTE) == 0 ) {
1282                         /*
1283                          * No more pending commands
1284                          */
1285                         goto out_unlock;
1286                 }
1287                 set_irq_state(adapter, byte);
1288
1289                 while((nstatus = (volatile u8)adapter->mbox->m_in.numstatus)
1290                                 == 0xFF)
1291                         cpu_relax();
1292                 adapter->mbox->m_in.numstatus = 0xFF;
1293
1294                 status = adapter->mbox->m_in.status;
1295
1296                 /*
1297                  * decrement the pending queue counter
1298                  */
1299                 atomic_sub(nstatus, &adapter->pend_cmds);
1300
1301                 memcpy(completed, (void *)adapter->mbox->m_in.completed, 
1302                                 nstatus);
1303
1304                 /* Acknowledge interrupt */
1305                 irq_ack(adapter);
1306
1307                 mega_cmd_done(adapter, completed, nstatus, status);
1308
1309                 mega_rundoneq(adapter);
1310
1311                 handled = 1;
1312
1313                 /* Loop through any pending requests */
1314                 if(atomic_read(&adapter->quiescent) == 0) {
1315                         mega_runpendq(adapter);
1316                 }
1317
1318         } while(1);
1319
1320  out_unlock:
1321
1322         spin_unlock_irqrestore(&adapter->lock, flags);
1323
1324         return IRQ_RETVAL(handled);
1325 }
1326
1327
1328 /**
1329  * megaraid_isr_memmapped()
1330  * @irq - irq
1331  * @devp - pointer to our soft state
1332  *
1333  * Interrupt service routine for memory-mapped controllers.
1334  * Find out if our device is interrupting. If yes, acknowledge the interrupt
1335  * and service the completed commands.
1336  */
1337 static irqreturn_t
1338 megaraid_isr_memmapped(int irq, void *devp)
1339 {
1340         adapter_t       *adapter = devp;
1341         unsigned long   flags;
1342         u8      status;
1343         u32     dword = 0;
1344         u8      nstatus;
1345         u8      completed[MAX_FIRMWARE_STATUS];
1346         int     handled = 0;
1347
1348
1349         /*
1350          * loop till F/W has more commands for us to complete.
1351          */
1352         spin_lock_irqsave(&adapter->lock, flags);
1353
1354         do {
1355                 /* Check if a valid interrupt is pending */
1356                 dword = RDOUTDOOR(adapter);
1357                 if(dword != 0x10001234) {
1358                         /*
1359                          * No more pending commands
1360                          */
1361                         goto out_unlock;
1362                 }
1363                 WROUTDOOR(adapter, 0x10001234);
1364
1365                 while((nstatus = (volatile u8)adapter->mbox->m_in.numstatus)
1366                                 == 0xFF) {
1367                         cpu_relax();
1368                 }
1369                 adapter->mbox->m_in.numstatus = 0xFF;
1370
1371                 status = adapter->mbox->m_in.status;
1372
1373                 /*
1374                  * decrement the pending queue counter
1375                  */
1376                 atomic_sub(nstatus, &adapter->pend_cmds);
1377
1378                 memcpy(completed, (void *)adapter->mbox->m_in.completed, 
1379                                 nstatus);
1380
1381                 /* Acknowledge interrupt */
1382                 WRINDOOR(adapter, 0x2);
1383
1384                 handled = 1;
1385
1386                 while( RDINDOOR(adapter) & 0x02 )
1387                         cpu_relax();
1388
1389                 mega_cmd_done(adapter, completed, nstatus, status);
1390
1391                 mega_rundoneq(adapter);
1392
1393                 /* Loop through any pending requests */
1394                 if(atomic_read(&adapter->quiescent) == 0) {
1395                         mega_runpendq(adapter);
1396                 }
1397
1398         } while(1);
1399
1400  out_unlock:
1401
1402         spin_unlock_irqrestore(&adapter->lock, flags);
1403
1404         return IRQ_RETVAL(handled);
1405 }
1406 /**
1407  * mega_cmd_done()
1408  * @adapter - pointer to our soft state
1409  * @completed - array of ids of completed commands
1410  * @nstatus - number of completed commands
1411  * @status - status of the last command completed
1412  *
1413  * Complete the commands and call the scsi mid-layer callback hooks.
1414  */
1415 static void
1416 mega_cmd_done(adapter_t *adapter, u8 completed[], int nstatus, int status)
1417 {
1418         mega_ext_passthru       *epthru = NULL;
1419         struct scatterlist      *sgl;
1420         Scsi_Cmnd       *cmd = NULL;
1421         mega_passthru   *pthru = NULL;
1422         mbox_t  *mbox = NULL;
1423         u8      c;
1424         scb_t   *scb;
1425         int     islogical;
1426         int     cmdid;
1427         int     i;
1428
1429         /*
1430          * for all the commands completed, call the mid-layer callback routine
1431          * and free the scb.
1432          */
1433         for( i = 0; i < nstatus; i++ ) {
1434
1435                 cmdid = completed[i];
1436
1437                 /*
1438                  * Only free SCBs for the commands coming down from the
1439                  * mid-layer, not for which were issued internally
1440                  *
1441                  * For internal command, restore the status returned by the
1442                  * firmware so that user can interpret it.
1443                  */
1444                 if (cmdid == CMDID_INT_CMDS) {
1445                         scb = &adapter->int_scb;
1446                         cmd = scb->cmd;
1447
1448                         list_del_init(&scb->list);
1449                         scb->state = SCB_FREE;
1450
1451                         adapter->int_status = status;
1452                         complete(&adapter->int_waitq);
1453                 } else {
1454                         scb = &adapter->scb_list[cmdid];
1455
1456                         /*
1457                          * Make sure f/w has completed a valid command
1458                          */
1459                         if( !(scb->state & SCB_ISSUED) || scb->cmd == NULL ) {
1460                                 dev_crit(&adapter->dev->dev, "invalid command "
1461                                         "Id %d, scb->state:%x, scsi cmd:%p\n",
1462                                         cmdid, scb->state, scb->cmd);
1463
1464                                 continue;
1465                         }
1466
1467                         /*
1468                          * Was a abort issued for this command
1469                          */
1470                         if( scb->state & SCB_ABORT ) {
1471
1472                                 dev_warn(&adapter->dev->dev,
1473                                         "aborted cmd [%x] complete\n",
1474                                         scb->idx);
1475
1476                                 scb->cmd->result = (DID_ABORT << 16);
1477
1478                                 list_add_tail(SCSI_LIST(scb->cmd),
1479                                                 &adapter->completed_list);
1480
1481                                 mega_free_scb(adapter, scb);
1482
1483                                 continue;
1484                         }
1485
1486                         /*
1487                          * Was a reset issued for this command
1488                          */
1489                         if( scb->state & SCB_RESET ) {
1490
1491                                 dev_warn(&adapter->dev->dev,
1492                                         "reset cmd [%x] complete\n",
1493                                         scb->idx);
1494
1495                                 scb->cmd->result = (DID_RESET << 16);
1496
1497                                 list_add_tail(SCSI_LIST(scb->cmd),
1498                                                 &adapter->completed_list);
1499
1500                                 mega_free_scb (adapter, scb);
1501
1502                                 continue;
1503                         }
1504
1505                         cmd = scb->cmd;
1506                         pthru = scb->pthru;
1507                         epthru = scb->epthru;
1508                         mbox = (mbox_t *)scb->raw_mbox;
1509
1510 #if MEGA_HAVE_STATS
1511                         {
1512
1513                         int     logdrv = mbox->m_out.logdrv;
1514
1515                         islogical = adapter->logdrv_chan[cmd->channel];
1516                         /*
1517                          * Maintain an error counter for the logical drive.
1518                          * Some application like SNMP agent need such
1519                          * statistics
1520                          */
1521                         if( status && islogical && (cmd->cmnd[0] == READ_6 ||
1522                                                 cmd->cmnd[0] == READ_10 ||
1523                                                 cmd->cmnd[0] == READ_12)) {
1524                                 /*
1525                                  * Logical drive number increases by 0x80 when
1526                                  * a logical drive is deleted
1527                                  */
1528                                 adapter->rd_errors[logdrv%0x80]++;
1529                         }
1530
1531                         if( status && islogical && (cmd->cmnd[0] == WRITE_6 ||
1532                                                 cmd->cmnd[0] == WRITE_10 ||
1533                                                 cmd->cmnd[0] == WRITE_12)) {
1534                                 /*
1535                                  * Logical drive number increases by 0x80 when
1536                                  * a logical drive is deleted
1537                                  */
1538                                 adapter->wr_errors[logdrv%0x80]++;
1539                         }
1540
1541                         }
1542 #endif
1543                 }
1544
1545                 /*
1546                  * Do not return the presence of hard disk on the channel so,
1547                  * inquiry sent, and returned data==hard disk or removable
1548                  * hard disk and not logical, request should return failure! -
1549                  * PJ
1550                  */
1551                 islogical = adapter->logdrv_chan[cmd->device->channel];
1552                 if( cmd->cmnd[0] == INQUIRY && !islogical ) {
1553
1554                         sgl = scsi_sglist(cmd);
1555                         if( sg_page(sgl) ) {
1556                                 c = *(unsigned char *) sg_virt(&sgl[0]);
1557                         } else {
1558                                 dev_warn(&adapter->dev->dev, "invalid sg\n");
1559                                 c = 0;
1560                         }
1561
1562                         if(IS_RAID_CH(adapter, cmd->device->channel) &&
1563                                         ((c & 0x1F ) == TYPE_DISK)) {
1564                                 status = 0xF0;
1565                         }
1566                 }
1567
1568                 /* clear result; otherwise, success returns corrupt value */
1569                 cmd->result = 0;
1570
1571                 /* Convert MegaRAID status to Linux error code */
1572                 switch (status) {
1573                 case 0x00:      /* SUCCESS , i.e. SCSI_STATUS_GOOD */
1574                         cmd->result |= (DID_OK << 16);
1575                         break;
1576
1577                 case 0x02:      /* ERROR_ABORTED, i.e.
1578                                    SCSI_STATUS_CHECK_CONDITION */
1579
1580                         /* set sense_buffer and result fields */
1581                         if( mbox->m_out.cmd == MEGA_MBOXCMD_PASSTHRU ||
1582                                 mbox->m_out.cmd == MEGA_MBOXCMD_PASSTHRU64 ) {
1583
1584                                 memcpy(cmd->sense_buffer, pthru->reqsensearea,
1585                                                 14);
1586
1587                                 cmd->result = (DRIVER_SENSE << 24) |
1588                                         (DID_OK << 16) |
1589                                         (CHECK_CONDITION << 1);
1590                         }
1591                         else {
1592                                 if (mbox->m_out.cmd == MEGA_MBOXCMD_EXTPTHRU) {
1593
1594                                         memcpy(cmd->sense_buffer,
1595                                                 epthru->reqsensearea, 14);
1596
1597                                         cmd->result = (DRIVER_SENSE << 24) |
1598                                                 (DID_OK << 16) |
1599                                                 (CHECK_CONDITION << 1);
1600                                 } else {
1601                                         cmd->sense_buffer[0] = 0x70;
1602                                         cmd->sense_buffer[2] = ABORTED_COMMAND;
1603                                         cmd->result |= (CHECK_CONDITION << 1);
1604                                 }
1605                         }
1606                         break;
1607
1608                 case 0x08:      /* ERR_DEST_DRIVE_FAILED, i.e.
1609                                    SCSI_STATUS_BUSY */
1610                         cmd->result |= (DID_BUS_BUSY << 16) | status;
1611                         break;
1612
1613                 default:
1614 #if MEGA_HAVE_CLUSTERING
1615                         /*
1616                          * If TEST_UNIT_READY fails, we know
1617                          * MEGA_RESERVATION_STATUS failed
1618                          */
1619                         if( cmd->cmnd[0] == TEST_UNIT_READY ) {
1620                                 cmd->result |= (DID_ERROR << 16) |
1621                                         (RESERVATION_CONFLICT << 1);
1622                         }
1623                         else
1624                         /*
1625                          * Error code returned is 1 if Reserve or Release
1626                          * failed or the input parameter is invalid
1627                          */
1628                         if( status == 1 &&
1629                                 (cmd->cmnd[0] == RESERVE ||
1630                                          cmd->cmnd[0] == RELEASE) ) {
1631
1632                                 cmd->result |= (DID_ERROR << 16) |
1633                                         (RESERVATION_CONFLICT << 1);
1634                         }
1635                         else
1636 #endif
1637                                 cmd->result |= (DID_BAD_TARGET << 16)|status;
1638                 }
1639
1640                 mega_free_scb(adapter, scb);
1641
1642                 /* Add Scsi_Command to end of completed queue */
1643                 list_add_tail(SCSI_LIST(cmd), &adapter->completed_list);
1644         }
1645 }
1646
1647
1648 /*
1649  * mega_runpendq()
1650  *
1651  * Run through the list of completed requests and finish it
1652  */
1653 static void
1654 mega_rundoneq (adapter_t *adapter)
1655 {
1656         Scsi_Cmnd *cmd;
1657         struct list_head *pos;
1658
1659         list_for_each(pos, &adapter->completed_list) {
1660
1661                 struct scsi_pointer* spos = (struct scsi_pointer *)pos;
1662
1663                 cmd = list_entry(spos, Scsi_Cmnd, SCp);
1664                 cmd->scsi_done(cmd);
1665         }
1666
1667         INIT_LIST_HEAD(&adapter->completed_list);
1668 }
1669
1670
1671 /*
1672  * Free a SCB structure
1673  * Note: We assume the scsi commands associated with this scb is not free yet.
1674  */
1675 static void
1676 mega_free_scb(adapter_t *adapter, scb_t *scb)
1677 {
1678         switch( scb->dma_type ) {
1679
1680         case MEGA_DMA_TYPE_NONE:
1681                 break;
1682
1683         case MEGA_SGLIST:
1684                 scsi_dma_unmap(scb->cmd);
1685                 break;
1686         default:
1687                 break;
1688         }
1689
1690         /*
1691          * Remove from the pending list
1692          */
1693         list_del_init(&scb->list);
1694
1695         /* Link the scb back into free list */
1696         scb->state = SCB_FREE;
1697         scb->cmd = NULL;
1698
1699         list_add(&scb->list, &adapter->free_list);
1700 }
1701
1702
1703 static int
1704 __mega_busywait_mbox (adapter_t *adapter)
1705 {
1706         volatile mbox_t *mbox = adapter->mbox;
1707         long counter;
1708
1709         for (counter = 0; counter < 10000; counter++) {
1710                 if (!mbox->m_in.busy)
1711                         return 0;
1712                 udelay(100);
1713                 cond_resched();
1714         }
1715         return -1;              /* give up after 1 second */
1716 }
1717
1718 /*
1719  * Copies data to SGLIST
1720  * Note: For 64 bit cards, we need a minimum of one SG element for read/write
1721  */
1722 static int
1723 mega_build_sglist(adapter_t *adapter, scb_t *scb, u32 *buf, u32 *len)
1724 {
1725         struct scatterlist *sg;
1726         Scsi_Cmnd       *cmd;
1727         int     sgcnt;
1728         int     idx;
1729
1730         cmd = scb->cmd;
1731
1732         /*
1733          * Copy Scatter-Gather list info into controller structure.
1734          *
1735          * The number of sg elements returned must not exceed our limit
1736          */
1737         sgcnt = scsi_dma_map(cmd);
1738
1739         scb->dma_type = MEGA_SGLIST;
1740
1741         BUG_ON(sgcnt > adapter->sglen || sgcnt < 0);
1742
1743         *len = 0;
1744
1745         if (scsi_sg_count(cmd) == 1 && !adapter->has_64bit_addr) {
1746                 sg = scsi_sglist(cmd);
1747                 scb->dma_h_bulkdata = sg_dma_address(sg);
1748                 *buf = (u32)scb->dma_h_bulkdata;
1749                 *len = sg_dma_len(sg);
1750                 return 0;
1751         }
1752
1753         scsi_for_each_sg(cmd, sg, sgcnt, idx) {
1754                 if (adapter->has_64bit_addr) {
1755                         scb->sgl64[idx].address = sg_dma_address(sg);
1756                         *len += scb->sgl64[idx].length = sg_dma_len(sg);
1757                 } else {
1758                         scb->sgl[idx].address = sg_dma_address(sg);
1759                         *len += scb->sgl[idx].length = sg_dma_len(sg);
1760                 }
1761         }
1762
1763         /* Reset pointer and length fields */
1764         *buf = scb->sgl_dma_addr;
1765
1766         /* Return count of SG requests */
1767         return sgcnt;
1768 }
1769
1770
1771 /*
1772  * mega_8_to_40ld()
1773  *
1774  * takes all info in AdapterInquiry structure and puts it into ProductInfo and
1775  * Enquiry3 structures for later use
1776  */
1777 static void
1778 mega_8_to_40ld(mraid_inquiry *inquiry, mega_inquiry3 *enquiry3,
1779                 mega_product_info *product_info)
1780 {
1781         int i;
1782
1783         product_info->max_commands = inquiry->adapter_info.max_commands;
1784         enquiry3->rebuild_rate = inquiry->adapter_info.rebuild_rate;
1785         product_info->nchannels = inquiry->adapter_info.nchannels;
1786
1787         for (i = 0; i < 4; i++) {
1788                 product_info->fw_version[i] =
1789                         inquiry->adapter_info.fw_version[i];
1790
1791                 product_info->bios_version[i] =
1792                         inquiry->adapter_info.bios_version[i];
1793         }
1794         enquiry3->cache_flush_interval =
1795                 inquiry->adapter_info.cache_flush_interval;
1796
1797         product_info->dram_size = inquiry->adapter_info.dram_size;
1798
1799         enquiry3->num_ldrv = inquiry->logdrv_info.num_ldrv;
1800
1801         for (i = 0; i < MAX_LOGICAL_DRIVES_8LD; i++) {
1802                 enquiry3->ldrv_size[i] = inquiry->logdrv_info.ldrv_size[i];
1803                 enquiry3->ldrv_prop[i] = inquiry->logdrv_info.ldrv_prop[i];
1804                 enquiry3->ldrv_state[i] = inquiry->logdrv_info.ldrv_state[i];
1805         }
1806
1807         for (i = 0; i < (MAX_PHYSICAL_DRIVES); i++)
1808                 enquiry3->pdrv_state[i] = inquiry->pdrv_info.pdrv_state[i];
1809 }
1810
1811 static inline void
1812 mega_free_sgl(adapter_t *adapter)
1813 {
1814         scb_t   *scb;
1815         int     i;
1816
1817         for(i = 0; i < adapter->max_cmds; i++) {
1818
1819                 scb = &adapter->scb_list[i];
1820
1821                 if( scb->sgl64 ) {
1822                         pci_free_consistent(adapter->dev,
1823                                 sizeof(mega_sgl64) * adapter->sglen,
1824                                 scb->sgl64,
1825                                 scb->sgl_dma_addr);
1826
1827                         scb->sgl64 = NULL;
1828                 }
1829
1830                 if( scb->pthru ) {
1831                         pci_free_consistent(adapter->dev, sizeof(mega_passthru),
1832                                 scb->pthru, scb->pthru_dma_addr);
1833
1834                         scb->pthru = NULL;
1835                 }
1836
1837                 if( scb->epthru ) {
1838                         pci_free_consistent(adapter->dev,
1839                                 sizeof(mega_ext_passthru),
1840                                 scb->epthru, scb->epthru_dma_addr);
1841
1842                         scb->epthru = NULL;
1843                 }
1844
1845         }
1846 }
1847
1848
1849 /*
1850  * Get information about the card/driver
1851  */
1852 const char *
1853 megaraid_info(struct Scsi_Host *host)
1854 {
1855         static char buffer[512];
1856         adapter_t *adapter;
1857
1858         adapter = (adapter_t *)host->hostdata;
1859
1860         sprintf (buffer,
1861                  "LSI Logic MegaRAID %s %d commands %d targs %d chans %d luns",
1862                  adapter->fw_version, adapter->product_info.max_commands,
1863                  adapter->host->max_id, adapter->host->max_channel,
1864                  (u32)adapter->host->max_lun);
1865         return buffer;
1866 }
1867
1868 /*
1869  * Abort a previous SCSI request. Only commands on the pending list can be
1870  * aborted. All the commands issued to the F/W must complete.
1871  */
1872 static int
1873 megaraid_abort(Scsi_Cmnd *cmd)
1874 {
1875         adapter_t       *adapter;
1876         int             rval;
1877
1878         adapter = (adapter_t *)cmd->device->host->hostdata;
1879
1880         rval =  megaraid_abort_and_reset(adapter, cmd, SCB_ABORT);
1881
1882         /*
1883          * This is required here to complete any completed requests
1884          * to be communicated over to the mid layer.
1885          */
1886         mega_rundoneq(adapter);
1887
1888         return rval;
1889 }
1890
1891
1892 static int
1893 megaraid_reset(struct scsi_cmnd *cmd)
1894 {
1895         adapter_t       *adapter;
1896         megacmd_t       mc;
1897         int             rval;
1898
1899         adapter = (adapter_t *)cmd->device->host->hostdata;
1900
1901 #if MEGA_HAVE_CLUSTERING
1902         mc.cmd = MEGA_CLUSTER_CMD;
1903         mc.opcode = MEGA_RESET_RESERVATIONS;
1904
1905         if( mega_internal_command(adapter, &mc, NULL) != 0 ) {
1906                 dev_warn(&adapter->dev->dev, "reservation reset failed\n");
1907         }
1908         else {
1909                 dev_info(&adapter->dev->dev, "reservation reset\n");
1910         }
1911 #endif
1912
1913         spin_lock_irq(&adapter->lock);
1914
1915         rval =  megaraid_abort_and_reset(adapter, cmd, SCB_RESET);
1916
1917         /*
1918          * This is required here to complete any completed requests
1919          * to be communicated over to the mid layer.
1920          */
1921         mega_rundoneq(adapter);
1922         spin_unlock_irq(&adapter->lock);
1923
1924         return rval;
1925 }
1926
1927 /**
1928  * megaraid_abort_and_reset()
1929  * @adapter - megaraid soft state
1930  * @cmd - scsi command to be aborted or reset
1931  * @aor - abort or reset flag
1932  *
1933  * Try to locate the scsi command in the pending queue. If found and is not
1934  * issued to the controller, abort/reset it. Otherwise return failure
1935  */
1936 static int
1937 megaraid_abort_and_reset(adapter_t *adapter, Scsi_Cmnd *cmd, int aor)
1938 {
1939         struct list_head        *pos, *next;
1940         scb_t                   *scb;
1941
1942         dev_warn(&adapter->dev->dev, "%s cmd=%x <c=%d t=%d l=%d>\n",
1943              (aor == SCB_ABORT)? "ABORTING":"RESET",
1944              cmd->cmnd[0], cmd->device->channel,
1945              cmd->device->id, (u32)cmd->device->lun);
1946
1947         if(list_empty(&adapter->pending_list))
1948                 return FAILED;
1949
1950         list_for_each_safe(pos, next, &adapter->pending_list) {
1951
1952                 scb = list_entry(pos, scb_t, list);
1953
1954                 if (scb->cmd == cmd) { /* Found command */
1955
1956                         scb->state |= aor;
1957
1958                         /*
1959                          * Check if this command has firmware ownership. If
1960                          * yes, we cannot reset this command. Whenever f/w
1961                          * completes this command, we will return appropriate
1962                          * status from ISR.
1963                          */
1964                         if( scb->state & SCB_ISSUED ) {
1965
1966                                 dev_warn(&adapter->dev->dev,
1967                                         "%s[%x], fw owner\n",
1968                                         (aor==SCB_ABORT) ? "ABORTING":"RESET",
1969                                         scb->idx);
1970
1971                                 return FAILED;
1972                         }
1973                         else {
1974
1975                                 /*
1976                                  * Not yet issued! Remove from the pending
1977                                  * list
1978                                  */
1979                                 dev_warn(&adapter->dev->dev,
1980                                         "%s-[%x], driver owner\n",
1981                                         (aor==SCB_ABORT) ? "ABORTING":"RESET",
1982                                         scb->idx);
1983
1984                                 mega_free_scb(adapter, scb);
1985
1986                                 if( aor == SCB_ABORT ) {
1987                                         cmd->result = (DID_ABORT << 16);
1988                                 }
1989                                 else {
1990                                         cmd->result = (DID_RESET << 16);
1991                                 }
1992
1993                                 list_add_tail(SCSI_LIST(cmd),
1994                                                 &adapter->completed_list);
1995
1996                                 return SUCCESS;
1997                         }
1998                 }
1999         }
2000
2001         return FAILED;
2002 }
2003
2004 static inline int
2005 make_local_pdev(adapter_t *adapter, struct pci_dev **pdev)
2006 {
2007         *pdev = pci_alloc_dev(NULL);
2008
2009         if( *pdev == NULL ) return -1;
2010
2011         memcpy(*pdev, adapter->dev, sizeof(struct pci_dev));
2012
2013         if( pci_set_dma_mask(*pdev, DMA_BIT_MASK(32)) != 0 ) {
2014                 kfree(*pdev);
2015                 return -1;
2016         }
2017
2018         return 0;
2019 }
2020
2021 static inline void
2022 free_local_pdev(struct pci_dev *pdev)
2023 {
2024         kfree(pdev);
2025 }
2026
2027 /**
2028  * mega_allocate_inquiry()
2029  * @dma_handle - handle returned for dma address
2030  * @pdev - handle to pci device
2031  *
2032  * allocates memory for inquiry structure
2033  */
2034 static inline void *
2035 mega_allocate_inquiry(dma_addr_t *dma_handle, struct pci_dev *pdev)
2036 {
2037         return pci_alloc_consistent(pdev, sizeof(mega_inquiry3), dma_handle);
2038 }
2039
2040
2041 static inline void
2042 mega_free_inquiry(void *inquiry, dma_addr_t dma_handle, struct pci_dev *pdev)
2043 {
2044         pci_free_consistent(pdev, sizeof(mega_inquiry3), inquiry, dma_handle);
2045 }
2046
2047
2048 #ifdef CONFIG_PROC_FS
2049 /* Following code handles /proc fs  */
2050
2051 /**
2052  * proc_show_config()
2053  * @m - Synthetic file construction data
2054  * @v - File iterator
2055  *
2056  * Display configuration information about the controller.
2057  */
2058 static int
2059 proc_show_config(struct seq_file *m, void *v)
2060 {
2061
2062         adapter_t *adapter = m->private;
2063
2064         seq_puts(m, MEGARAID_VERSION);
2065         if(adapter->product_info.product_name[0])
2066                 seq_printf(m, "%s\n", adapter->product_info.product_name);
2067
2068         seq_puts(m, "Controller Type: ");
2069
2070         if( adapter->flag & BOARD_MEMMAP )
2071                 seq_puts(m, "438/466/467/471/493/518/520/531/532\n");
2072         else
2073                 seq_puts(m, "418/428/434\n");
2074
2075         if(adapter->flag & BOARD_40LD)
2076                 seq_puts(m, "Controller Supports 40 Logical Drives\n");
2077
2078         if(adapter->flag & BOARD_64BIT)
2079                 seq_puts(m, "Controller capable of 64-bit memory addressing\n");
2080         if( adapter->has_64bit_addr )
2081                 seq_puts(m, "Controller using 64-bit memory addressing\n");
2082         else
2083                 seq_puts(m, "Controller is not using 64-bit memory addressing\n");
2084
2085         seq_printf(m, "Base = %08lx, Irq = %d, ",
2086                    adapter->base, adapter->host->irq);
2087
2088         seq_printf(m, "Logical Drives = %d, Channels = %d\n",
2089                    adapter->numldrv, adapter->product_info.nchannels);
2090
2091         seq_printf(m, "Version =%s:%s, DRAM = %dMb\n",
2092                    adapter->fw_version, adapter->bios_version,
2093                    adapter->product_info.dram_size);
2094
2095         seq_printf(m, "Controller Queue Depth = %d, Driver Queue Depth = %d\n",
2096                    adapter->product_info.max_commands, adapter->max_cmds);
2097
2098         seq_printf(m, "support_ext_cdb    = %d\n", adapter->support_ext_cdb);
2099         seq_printf(m, "support_random_del = %d\n", adapter->support_random_del);
2100         seq_printf(m, "boot_ldrv_enabled  = %d\n", adapter->boot_ldrv_enabled);
2101         seq_printf(m, "boot_ldrv          = %d\n", adapter->boot_ldrv);
2102         seq_printf(m, "boot_pdrv_enabled  = %d\n", adapter->boot_pdrv_enabled);
2103         seq_printf(m, "boot_pdrv_ch       = %d\n", adapter->boot_pdrv_ch);
2104         seq_printf(m, "boot_pdrv_tgt      = %d\n", adapter->boot_pdrv_tgt);
2105         seq_printf(m, "quiescent          = %d\n",
2106                    atomic_read(&adapter->quiescent));
2107         seq_printf(m, "has_cluster        = %d\n", adapter->has_cluster);
2108
2109         seq_puts(m, "\nModule Parameters:\n");
2110         seq_printf(m, "max_cmd_per_lun    = %d\n", max_cmd_per_lun);
2111         seq_printf(m, "max_sectors_per_io = %d\n", max_sectors_per_io);
2112         return 0;
2113 }
2114
2115 /**
2116  * proc_show_stat()
2117  * @m - Synthetic file construction data
2118  * @v - File iterator
2119  *
2120  * Display statistical information about the I/O activity.
2121  */
2122 static int
2123 proc_show_stat(struct seq_file *m, void *v)
2124 {
2125         adapter_t *adapter = m->private;
2126 #if MEGA_HAVE_STATS
2127         int     i;
2128 #endif
2129
2130         seq_puts(m, "Statistical Information for this controller\n");
2131         seq_printf(m, "pend_cmds = %d\n", atomic_read(&adapter->pend_cmds));
2132 #if MEGA_HAVE_STATS
2133         for(i = 0; i < adapter->numldrv; i++) {
2134                 seq_printf(m, "Logical Drive %d:\n", i);
2135                 seq_printf(m, "\tReads Issued = %lu, Writes Issued = %lu\n",
2136                            adapter->nreads[i], adapter->nwrites[i]);
2137                 seq_printf(m, "\tSectors Read = %lu, Sectors Written = %lu\n",
2138                            adapter->nreadblocks[i], adapter->nwriteblocks[i]);
2139                 seq_printf(m, "\tRead errors = %lu, Write errors = %lu\n\n",
2140                            adapter->rd_errors[i], adapter->wr_errors[i]);
2141         }
2142 #else
2143         seq_puts(m, "IO and error counters not compiled in driver.\n");
2144 #endif
2145         return 0;
2146 }
2147
2148
2149 /**
2150  * proc_show_mbox()
2151  * @m - Synthetic file construction data
2152  * @v - File iterator
2153  *
2154  * Display mailbox information for the last command issued. This information
2155  * is good for debugging.
2156  */
2157 static int
2158 proc_show_mbox(struct seq_file *m, void *v)
2159 {
2160         adapter_t       *adapter = m->private;
2161         volatile mbox_t *mbox = adapter->mbox;
2162
2163         seq_puts(m, "Contents of Mail Box Structure\n");
2164         seq_printf(m, "  Fw Command   = 0x%02x\n", mbox->m_out.cmd);
2165         seq_printf(m, "  Cmd Sequence = 0x%02x\n", mbox->m_out.cmdid);
2166         seq_printf(m, "  No of Sectors= %04d\n", mbox->m_out.numsectors);
2167         seq_printf(m, "  LBA          = 0x%02x\n", mbox->m_out.lba);
2168         seq_printf(m, "  DTA          = 0x%08x\n", mbox->m_out.xferaddr);
2169         seq_printf(m, "  Logical Drive= 0x%02x\n", mbox->m_out.logdrv);
2170         seq_printf(m, "  No of SG Elmt= 0x%02x\n", mbox->m_out.numsgelements);
2171         seq_printf(m, "  Busy         = %01x\n", mbox->m_in.busy);
2172         seq_printf(m, "  Status       = 0x%02x\n", mbox->m_in.status);
2173         return 0;
2174 }
2175
2176
2177 /**
2178  * proc_show_rebuild_rate()
2179  * @m - Synthetic file construction data
2180  * @v - File iterator
2181  *
2182  * Display current rebuild rate
2183  */
2184 static int
2185 proc_show_rebuild_rate(struct seq_file *m, void *v)
2186 {
2187         adapter_t       *adapter = m->private;
2188         dma_addr_t      dma_handle;
2189         caddr_t         inquiry;
2190         struct pci_dev  *pdev;
2191
2192         if( make_local_pdev(adapter, &pdev) != 0 )
2193                 return 0;
2194
2195         if( (inquiry = mega_allocate_inquiry(&dma_handle, pdev)) == NULL )
2196                 goto free_pdev;
2197
2198         if( mega_adapinq(adapter, dma_handle) != 0 ) {
2199                 seq_puts(m, "Adapter inquiry failed.\n");
2200                 dev_warn(&adapter->dev->dev, "inquiry failed\n");
2201                 goto free_inquiry;
2202         }
2203
2204         if( adapter->flag & BOARD_40LD )
2205                 seq_printf(m, "Rebuild Rate: [%d%%]\n",
2206                            ((mega_inquiry3 *)inquiry)->rebuild_rate);
2207         else
2208                 seq_printf(m, "Rebuild Rate: [%d%%]\n",
2209                         ((mraid_ext_inquiry *)
2210                          inquiry)->raid_inq.adapter_info.rebuild_rate);
2211
2212 free_inquiry:
2213         mega_free_inquiry(inquiry, dma_handle, pdev);
2214 free_pdev:
2215         free_local_pdev(pdev);
2216         return 0;
2217 }
2218
2219
2220 /**
2221  * proc_show_battery()
2222  * @m - Synthetic file construction data
2223  * @v - File iterator
2224  *
2225  * Display information about the battery module on the controller.
2226  */
2227 static int
2228 proc_show_battery(struct seq_file *m, void *v)
2229 {
2230         adapter_t       *adapter = m->private;
2231         dma_addr_t      dma_handle;
2232         caddr_t         inquiry;
2233         struct pci_dev  *pdev;
2234         u8      battery_status;
2235
2236         if( make_local_pdev(adapter, &pdev) != 0 )
2237                 return 0;
2238
2239         if( (inquiry = mega_allocate_inquiry(&dma_handle, pdev)) == NULL )
2240                 goto free_pdev;
2241
2242         if( mega_adapinq(adapter, dma_handle) != 0 ) {
2243                 seq_puts(m, "Adapter inquiry failed.\n");
2244                 dev_warn(&adapter->dev->dev, "inquiry failed\n");
2245                 goto free_inquiry;
2246         }
2247
2248         if( adapter->flag & BOARD_40LD ) {
2249                 battery_status = ((mega_inquiry3 *)inquiry)->battery_status;
2250         }
2251         else {
2252                 battery_status = ((mraid_ext_inquiry *)inquiry)->
2253                         raid_inq.adapter_info.battery_status;
2254         }
2255
2256         /*
2257          * Decode the battery status
2258          */
2259         seq_printf(m, "Battery Status:[%d]", battery_status);
2260
2261         if(battery_status == MEGA_BATT_CHARGE_DONE)
2262                 seq_puts(m, " Charge Done");
2263
2264         if(battery_status & MEGA_BATT_MODULE_MISSING)
2265                 seq_puts(m, " Module Missing");
2266         
2267         if(battery_status & MEGA_BATT_LOW_VOLTAGE)
2268                 seq_puts(m, " Low Voltage");
2269         
2270         if(battery_status & MEGA_BATT_TEMP_HIGH)
2271                 seq_puts(m, " Temperature High");
2272         
2273         if(battery_status & MEGA_BATT_PACK_MISSING)
2274                 seq_puts(m, " Pack Missing");
2275         
2276         if(battery_status & MEGA_BATT_CHARGE_INPROG)
2277                 seq_puts(m, " Charge In-progress");
2278         
2279         if(battery_status & MEGA_BATT_CHARGE_FAIL)
2280                 seq_puts(m, " Charge Fail");
2281         
2282         if(battery_status & MEGA_BATT_CYCLES_EXCEEDED)
2283                 seq_puts(m, " Cycles Exceeded");
2284
2285         seq_putc(m, '\n');
2286
2287 free_inquiry:
2288         mega_free_inquiry(inquiry, dma_handle, pdev);
2289 free_pdev:
2290         free_local_pdev(pdev);
2291         return 0;
2292 }
2293
2294
2295 /*
2296  * Display scsi inquiry
2297  */
2298 static void
2299 mega_print_inquiry(struct seq_file *m, char *scsi_inq)
2300 {
2301         int     i;
2302
2303         seq_puts(m, "  Vendor: ");
2304         seq_write(m, scsi_inq + 8, 8);
2305         seq_puts(m, "  Model: ");
2306         seq_write(m, scsi_inq + 16, 16);
2307         seq_puts(m, "  Rev: ");
2308         seq_write(m, scsi_inq + 32, 4);
2309         seq_putc(m, '\n');
2310
2311         i = scsi_inq[0] & 0x1f;
2312         seq_printf(m, "  Type:   %s ", scsi_device_type(i));
2313
2314         seq_printf(m, "                 ANSI SCSI revision: %02x",
2315                    scsi_inq[2] & 0x07);
2316
2317         if( (scsi_inq[2] & 0x07) == 1 && (scsi_inq[3] & 0x0f) == 1 )
2318                 seq_puts(m, " CCS\n");
2319         else
2320                 seq_putc(m, '\n');
2321 }
2322
2323 /**
2324  * proc_show_pdrv()
2325  * @m - Synthetic file construction data
2326  * @page - buffer to write the data in
2327  * @adapter - pointer to our soft state
2328  *
2329  * Display information about the physical drives.
2330  */
2331 static int
2332 proc_show_pdrv(struct seq_file *m, adapter_t *adapter, int channel)
2333 {
2334         dma_addr_t      dma_handle;
2335         char            *scsi_inq;
2336         dma_addr_t      scsi_inq_dma_handle;
2337         caddr_t         inquiry;
2338         struct pci_dev  *pdev;
2339         u8      *pdrv_state;
2340         u8      state;
2341         int     tgt;
2342         int     max_channels;
2343         int     i;
2344
2345         if( make_local_pdev(adapter, &pdev) != 0 )
2346                 return 0;
2347
2348         if( (inquiry = mega_allocate_inquiry(&dma_handle, pdev)) == NULL )
2349                 goto free_pdev;
2350
2351         if( mega_adapinq(adapter, dma_handle) != 0 ) {
2352                 seq_puts(m, "Adapter inquiry failed.\n");
2353                 dev_warn(&adapter->dev->dev, "inquiry failed\n");
2354                 goto free_inquiry;
2355         }
2356
2357
2358         scsi_inq = pci_alloc_consistent(pdev, 256, &scsi_inq_dma_handle);
2359         if( scsi_inq == NULL ) {
2360                 seq_puts(m, "memory not available for scsi inq.\n");
2361                 goto free_inquiry;
2362         }
2363
2364         if( adapter->flag & BOARD_40LD ) {
2365                 pdrv_state = ((mega_inquiry3 *)inquiry)->pdrv_state;
2366         }
2367         else {
2368                 pdrv_state = ((mraid_ext_inquiry *)inquiry)->
2369                         raid_inq.pdrv_info.pdrv_state;
2370         }
2371
2372         max_channels = adapter->product_info.nchannels;
2373
2374         if( channel >= max_channels ) {
2375                 goto free_pci;
2376         }
2377
2378         for( tgt = 0; tgt <= MAX_TARGET; tgt++ ) {
2379
2380                 i = channel*16 + tgt;
2381
2382                 state = *(pdrv_state + i);
2383                 switch( state & 0x0F ) {
2384                 case PDRV_ONLINE:
2385                         seq_printf(m, "Channel:%2d Id:%2d State: Online",
2386                                    channel, tgt);
2387                         break;
2388
2389                 case PDRV_FAILED:
2390                         seq_printf(m, "Channel:%2d Id:%2d State: Failed",
2391                                    channel, tgt);
2392                         break;
2393
2394                 case PDRV_RBLD:
2395                         seq_printf(m, "Channel:%2d Id:%2d State: Rebuild",
2396                                    channel, tgt);
2397                         break;
2398
2399                 case PDRV_HOTSPARE:
2400                         seq_printf(m, "Channel:%2d Id:%2d State: Hot spare",
2401                                    channel, tgt);
2402                         break;
2403
2404                 default:
2405                         seq_printf(m, "Channel:%2d Id:%2d State: Un-configured",
2406                                    channel, tgt);
2407                         break;
2408                 }
2409
2410                 /*
2411                  * This interface displays inquiries for disk drives
2412                  * only. Inquries for logical drives and non-disk
2413                  * devices are available through /proc/scsi/scsi
2414                  */
2415                 memset(scsi_inq, 0, 256);
2416                 if( mega_internal_dev_inquiry(adapter, channel, tgt,
2417                                 scsi_inq_dma_handle) ||
2418                                 (scsi_inq[0] & 0x1F) != TYPE_DISK ) {
2419                         continue;
2420                 }
2421
2422                 /*
2423                  * Check for overflow. We print less than 240
2424                  * characters for inquiry
2425                  */
2426                 seq_puts(m, ".\n");
2427                 mega_print_inquiry(m, scsi_inq);
2428         }
2429
2430 free_pci:
2431         pci_free_consistent(pdev, 256, scsi_inq, scsi_inq_dma_handle);
2432 free_inquiry:
2433         mega_free_inquiry(inquiry, dma_handle, pdev);
2434 free_pdev:
2435         free_local_pdev(pdev);
2436         return 0;
2437 }
2438
2439 /**
2440  * proc_show_pdrv_ch0()
2441  * @m - Synthetic file construction data
2442  * @v - File iterator
2443  *
2444  * Display information about the physical drives on physical channel 0.
2445  */
2446 static int
2447 proc_show_pdrv_ch0(struct seq_file *m, void *v)
2448 {
2449         return proc_show_pdrv(m, m->private, 0);
2450 }
2451
2452
2453 /**
2454  * proc_show_pdrv_ch1()
2455  * @m - Synthetic file construction data
2456  * @v - File iterator
2457  *
2458  * Display information about the physical drives on physical channel 1.
2459  */
2460 static int
2461 proc_show_pdrv_ch1(struct seq_file *m, void *v)
2462 {
2463         return proc_show_pdrv(m, m->private, 1);
2464 }
2465
2466
2467 /**
2468  * proc_show_pdrv_ch2()
2469  * @m - Synthetic file construction data
2470  * @v - File iterator
2471  *
2472  * Display information about the physical drives on physical channel 2.
2473  */
2474 static int
2475 proc_show_pdrv_ch2(struct seq_file *m, void *v)
2476 {
2477         return proc_show_pdrv(m, m->private, 2);
2478 }
2479
2480
2481 /**
2482  * proc_show_pdrv_ch3()
2483  * @m - Synthetic file construction data
2484  * @v - File iterator
2485  *
2486  * Display information about the physical drives on physical channel 3.
2487  */
2488 static int
2489 proc_show_pdrv_ch3(struct seq_file *m, void *v)
2490 {
2491         return proc_show_pdrv(m, m->private, 3);
2492 }
2493
2494
2495 /**
2496  * proc_show_rdrv()
2497  * @m - Synthetic file construction data
2498  * @adapter - pointer to our soft state
2499  * @start - starting logical drive to display
2500  * @end - ending logical drive to display
2501  *
2502  * We do not print the inquiry information since its already available through
2503  * /proc/scsi/scsi interface
2504  */
2505 static int
2506 proc_show_rdrv(struct seq_file *m, adapter_t *adapter, int start, int end )
2507 {
2508         dma_addr_t      dma_handle;
2509         logdrv_param    *lparam;
2510         megacmd_t       mc;
2511         char            *disk_array;
2512         dma_addr_t      disk_array_dma_handle;
2513         caddr_t         inquiry;
2514         struct pci_dev  *pdev;
2515         u8      *rdrv_state;
2516         int     num_ldrv;
2517         u32     array_sz;
2518         int     i;
2519
2520         if( make_local_pdev(adapter, &pdev) != 0 )
2521                 return 0;
2522
2523         if( (inquiry = mega_allocate_inquiry(&dma_handle, pdev)) == NULL )
2524                 goto free_pdev;
2525
2526         if( mega_adapinq(adapter, dma_handle) != 0 ) {
2527                 seq_puts(m, "Adapter inquiry failed.\n");
2528                 dev_warn(&adapter->dev->dev, "inquiry failed\n");
2529                 goto free_inquiry;
2530         }
2531
2532         memset(&mc, 0, sizeof(megacmd_t));
2533
2534         if( adapter->flag & BOARD_40LD ) {
2535                 array_sz = sizeof(disk_array_40ld);
2536
2537                 rdrv_state = ((mega_inquiry3 *)inquiry)->ldrv_state;
2538
2539                 num_ldrv = ((mega_inquiry3 *)inquiry)->num_ldrv;
2540         }
2541         else {
2542                 array_sz = sizeof(disk_array_8ld);
2543
2544                 rdrv_state = ((mraid_ext_inquiry *)inquiry)->
2545                         raid_inq.logdrv_info.ldrv_state;
2546
2547                 num_ldrv = ((mraid_ext_inquiry *)inquiry)->
2548                         raid_inq.logdrv_info.num_ldrv;
2549         }
2550
2551         disk_array = pci_alloc_consistent(pdev, array_sz,
2552                         &disk_array_dma_handle);
2553
2554         if( disk_array == NULL ) {
2555                 seq_puts(m, "memory not available.\n");
2556                 goto free_inquiry;
2557         }
2558
2559         mc.xferaddr = (u32)disk_array_dma_handle;
2560
2561         if( adapter->flag & BOARD_40LD ) {
2562                 mc.cmd = FC_NEW_CONFIG;
2563                 mc.opcode = OP_DCMD_READ_CONFIG;
2564
2565                 if( mega_internal_command(adapter, &mc, NULL) ) {
2566                         seq_puts(m, "40LD read config failed.\n");
2567                         goto free_pci;
2568                 }
2569
2570         }
2571         else {
2572                 mc.cmd = NEW_READ_CONFIG_8LD;
2573
2574                 if( mega_internal_command(adapter, &mc, NULL) ) {
2575                         mc.cmd = READ_CONFIG_8LD;
2576                         if( mega_internal_command(adapter, &mc, NULL) ) {
2577                                 seq_puts(m, "8LD read config failed.\n");
2578                                 goto free_pci;
2579                         }
2580                 }
2581         }
2582
2583         for( i = start; i < ( (end+1 < num_ldrv) ? end+1 : num_ldrv ); i++ ) {
2584
2585                 if( adapter->flag & BOARD_40LD ) {
2586                         lparam =
2587                         &((disk_array_40ld *)disk_array)->ldrv[i].lparam;
2588                 }
2589                 else {
2590                         lparam =
2591                         &((disk_array_8ld *)disk_array)->ldrv[i].lparam;
2592                 }
2593
2594                 /*
2595                  * Check for overflow. We print less than 240 characters for
2596                  * information about each logical drive.
2597                  */
2598                 seq_printf(m, "Logical drive:%2d:, ", i);
2599
2600                 switch( rdrv_state[i] & 0x0F ) {
2601                 case RDRV_OFFLINE:
2602                         seq_puts(m, "state: offline");
2603                         break;
2604                 case RDRV_DEGRADED:
2605                         seq_puts(m, "state: degraded");
2606                         break;
2607                 case RDRV_OPTIMAL:
2608                         seq_puts(m, "state: optimal");
2609                         break;
2610                 case RDRV_DELETED:
2611                         seq_puts(m, "state: deleted");
2612                         break;
2613                 default:
2614                         seq_puts(m, "state: unknown");
2615                         break;
2616                 }
2617
2618                 /*
2619                  * Check if check consistency or initialization is going on
2620                  * for this logical drive.
2621                  */
2622                 if( (rdrv_state[i] & 0xF0) == 0x20 )
2623                         seq_puts(m, ", check-consistency in progress");
2624                 else if( (rdrv_state[i] & 0xF0) == 0x10 )
2625                         seq_puts(m, ", initialization in progress");
2626                 
2627                 seq_putc(m, '\n');
2628
2629                 seq_printf(m, "Span depth:%3d, ", lparam->span_depth);
2630                 seq_printf(m, "RAID level:%3d, ", lparam->level);
2631                 seq_printf(m, "Stripe size:%3d, ",
2632                            lparam->stripe_sz ? lparam->stripe_sz/2: 128);
2633                 seq_printf(m, "Row size:%3d\n", lparam->row_size);
2634
2635                 seq_puts(m, "Read Policy: ");
2636                 switch(lparam->read_ahead) {
2637                 case NO_READ_AHEAD:
2638                         seq_puts(m, "No read ahead, ");
2639                         break;
2640                 case READ_AHEAD:
2641                         seq_puts(m, "Read ahead, ");
2642                         break;
2643                 case ADAP_READ_AHEAD:
2644                         seq_puts(m, "Adaptive, ");
2645                         break;
2646
2647                 }
2648
2649                 seq_puts(m, "Write Policy: ");
2650                 switch(lparam->write_mode) {
2651                 case WRMODE_WRITE_THRU:
2652                         seq_puts(m, "Write thru, ");
2653                         break;
2654                 case WRMODE_WRITE_BACK:
2655                         seq_puts(m, "Write back, ");
2656                         break;
2657                 }
2658
2659                 seq_puts(m, "Cache Policy: ");
2660                 switch(lparam->direct_io) {
2661                 case CACHED_IO:
2662                         seq_puts(m, "Cached IO\n\n");
2663                         break;
2664                 case DIRECT_IO:
2665                         seq_puts(m, "Direct IO\n\n");
2666                         break;
2667                 }
2668         }
2669
2670 free_pci:
2671         pci_free_consistent(pdev, array_sz, disk_array,
2672                         disk_array_dma_handle);
2673 free_inquiry:
2674         mega_free_inquiry(inquiry, dma_handle, pdev);
2675 free_pdev:
2676         free_local_pdev(pdev);
2677         return 0;
2678 }
2679
2680 /**
2681  * proc_show_rdrv_10()
2682  * @m - Synthetic file construction data
2683  * @v - File iterator
2684  *
2685  * Display real time information about the logical drives 0 through 9.
2686  */
2687 static int
2688 proc_show_rdrv_10(struct seq_file *m, void *v)
2689 {
2690         return proc_show_rdrv(m, m->private, 0, 9);
2691 }
2692
2693
2694 /**
2695  * proc_show_rdrv_20()
2696  * @m - Synthetic file construction data
2697  * @v - File iterator
2698  *
2699  * Display real time information about the logical drives 0 through 9.
2700  */
2701 static int
2702 proc_show_rdrv_20(struct seq_file *m, void *v)
2703 {
2704         return proc_show_rdrv(m, m->private, 10, 19);
2705 }
2706
2707
2708 /**
2709  * proc_show_rdrv_30()
2710  * @m - Synthetic file construction data
2711  * @v - File iterator
2712  *
2713  * Display real time information about the logical drives 0 through 9.
2714  */
2715 static int
2716 proc_show_rdrv_30(struct seq_file *m, void *v)
2717 {
2718         return proc_show_rdrv(m, m->private, 20, 29);
2719 }
2720
2721
2722 /**
2723  * proc_show_rdrv_40()
2724  * @m - Synthetic file construction data
2725  * @v - File iterator
2726  *
2727  * Display real time information about the logical drives 0 through 9.
2728  */
2729 static int
2730 proc_show_rdrv_40(struct seq_file *m, void *v)
2731 {
2732         return proc_show_rdrv(m, m->private, 30, 39);
2733 }
2734
2735
2736 /*
2737  * seq_file wrappers for procfile show routines.
2738  */
2739 static int mega_proc_open(struct inode *inode, struct file *file)
2740 {
2741         adapter_t *adapter = proc_get_parent_data(inode);
2742         int (*show)(struct seq_file *, void *) = PDE_DATA(inode);
2743
2744         return single_open(file, show, adapter);
2745 }
2746
2747 static const struct file_operations mega_proc_fops = {
2748         .open           = mega_proc_open,
2749         .read           = seq_read,
2750         .llseek         = seq_lseek,
2751         .release        = single_release,
2752 };
2753
2754 /*
2755  * Table of proc files we need to create.
2756  */
2757 struct mega_proc_file {
2758         const char *name;
2759         unsigned short ptr_offset;
2760         int (*show) (struct seq_file *m, void *v);
2761 };
2762
2763 static const struct mega_proc_file mega_proc_files[] = {
2764         { "config",           offsetof(adapter_t, proc_read), proc_show_config },
2765         { "stat",             offsetof(adapter_t, proc_stat), proc_show_stat },
2766         { "mailbox",          offsetof(adapter_t, proc_mbox), proc_show_mbox },
2767 #if MEGA_HAVE_ENH_PROC
2768         { "rebuild-rate",     offsetof(adapter_t, proc_rr), proc_show_rebuild_rate },
2769         { "battery-status",   offsetof(adapter_t, proc_battery), proc_show_battery },
2770         { "diskdrives-ch0",   offsetof(adapter_t, proc_pdrvstat[0]), proc_show_pdrv_ch0 },
2771         { "diskdrives-ch1",   offsetof(adapter_t, proc_pdrvstat[1]), proc_show_pdrv_ch1 },
2772         { "diskdrives-ch2",   offsetof(adapter_t, proc_pdrvstat[2]), proc_show_pdrv_ch2 },
2773         { "diskdrives-ch3",   offsetof(adapter_t, proc_pdrvstat[3]), proc_show_pdrv_ch3 },
2774         { "raiddrives-0-9",   offsetof(adapter_t, proc_rdrvstat[0]), proc_show_rdrv_10 },
2775         { "raiddrives-10-19", offsetof(adapter_t, proc_rdrvstat[1]), proc_show_rdrv_20 },
2776         { "raiddrives-20-29", offsetof(adapter_t, proc_rdrvstat[2]), proc_show_rdrv_30 },
2777         { "raiddrives-30-39", offsetof(adapter_t, proc_rdrvstat[3]), proc_show_rdrv_40 },
2778 #endif
2779         { NULL }
2780 };
2781
2782 /**
2783  * mega_create_proc_entry()
2784  * @index - index in soft state array
2785  * @parent - parent node for this /proc entry
2786  *
2787  * Creates /proc entries for our controllers.
2788  */
2789 static void
2790 mega_create_proc_entry(int index, struct proc_dir_entry *parent)
2791 {
2792         const struct mega_proc_file *f;
2793         adapter_t       *adapter = hba_soft_state[index];
2794         struct proc_dir_entry   *dir, *de, **ppde;
2795         u8              string[16];
2796
2797         sprintf(string, "hba%d", adapter->host->host_no);
2798
2799         dir = adapter->controller_proc_dir_entry =
2800                 proc_mkdir_data(string, 0, parent, adapter);
2801         if(!dir) {
2802                 dev_warn(&adapter->dev->dev, "proc_mkdir failed\n");
2803                 return;
2804         }
2805
2806         for (f = mega_proc_files; f->name; f++) {
2807                 de = proc_create_data(f->name, S_IRUSR, dir, &mega_proc_fops,
2808                                       f->show);
2809                 if (!de) {
2810                         dev_warn(&adapter->dev->dev, "proc_create failed\n");
2811                         return;
2812                 }
2813
2814                 ppde = (void *)adapter + f->ptr_offset;
2815                 *ppde = de;
2816         }
2817 }
2818
2819 #else
2820 static inline void mega_create_proc_entry(int index, struct proc_dir_entry *parent)
2821 {
2822 }
2823 #endif
2824
2825
2826 /**
2827  * megaraid_biosparam()
2828  *
2829  * Return the disk geometry for a particular disk
2830  */
2831 static int
2832 megaraid_biosparam(struct scsi_device *sdev, struct block_device *bdev,
2833                     sector_t capacity, int geom[])
2834 {
2835         adapter_t       *adapter;
2836         unsigned char   *bh;
2837         int     heads;
2838         int     sectors;
2839         int     cylinders;
2840         int     rval;
2841
2842         /* Get pointer to host config structure */
2843         adapter = (adapter_t *)sdev->host->hostdata;
2844
2845         if (IS_RAID_CH(adapter, sdev->channel)) {
2846                         /* Default heads (64) & sectors (32) */
2847                         heads = 64;
2848                         sectors = 32;
2849                         cylinders = (ulong)capacity / (heads * sectors);
2850
2851                         /*
2852                          * Handle extended translation size for logical drives
2853                          * > 1Gb
2854                          */
2855                         if ((ulong)capacity >= 0x200000) {
2856                                 heads = 255;
2857                                 sectors = 63;
2858                                 cylinders = (ulong)capacity / (heads * sectors);
2859                         }
2860
2861                         /* return result */
2862                         geom[0] = heads;
2863                         geom[1] = sectors;
2864                         geom[2] = cylinders;
2865         }
2866         else {
2867                 bh = scsi_bios_ptable(bdev);
2868
2869                 if( bh ) {
2870                         rval = scsi_partsize(bh, capacity,
2871                                             &geom[2], &geom[0], &geom[1]);
2872                         kfree(bh);
2873                         if( rval != -1 )
2874                                 return rval;
2875                 }
2876
2877                 dev_info(&adapter->dev->dev,
2878                          "invalid partition on this disk on channel %d\n",
2879                          sdev->channel);
2880
2881                 /* Default heads (64) & sectors (32) */
2882                 heads = 64;
2883                 sectors = 32;
2884                 cylinders = (ulong)capacity / (heads * sectors);
2885
2886                 /* Handle extended translation size for logical drives > 1Gb */
2887                 if ((ulong)capacity >= 0x200000) {
2888                         heads = 255;
2889                         sectors = 63;
2890                         cylinders = (ulong)capacity / (heads * sectors);
2891                 }
2892
2893                 /* return result */
2894                 geom[0] = heads;
2895                 geom[1] = sectors;
2896                 geom[2] = cylinders;
2897         }
2898
2899         return 0;
2900 }
2901
2902 /**
2903  * mega_init_scb()
2904  * @adapter - pointer to our soft state
2905  *
2906  * Allocate memory for the various pointers in the scb structures:
2907  * scatter-gather list pointer, passthru and extended passthru structure
2908  * pointers.
2909  */
2910 static int
2911 mega_init_scb(adapter_t *adapter)
2912 {
2913         scb_t   *scb;
2914         int     i;
2915
2916         for( i = 0; i < adapter->max_cmds; i++ ) {
2917
2918                 scb = &adapter->scb_list[i];
2919
2920                 scb->sgl64 = NULL;
2921                 scb->sgl = NULL;
2922                 scb->pthru = NULL;
2923                 scb->epthru = NULL;
2924         }
2925
2926         for( i = 0; i < adapter->max_cmds; i++ ) {
2927
2928                 scb = &adapter->scb_list[i];
2929
2930                 scb->idx = i;
2931
2932                 scb->sgl64 = pci_alloc_consistent(adapter->dev,
2933                                 sizeof(mega_sgl64) * adapter->sglen,
2934                                 &scb->sgl_dma_addr);
2935
2936                 scb->sgl = (mega_sglist *)scb->sgl64;
2937
2938                 if( !scb->sgl ) {
2939                         dev_warn(&adapter->dev->dev, "RAID: Can't allocate sglist\n");
2940                         mega_free_sgl(adapter);
2941                         return -1;
2942                 }
2943
2944                 scb->pthru = pci_alloc_consistent(adapter->dev,
2945                                 sizeof(mega_passthru),
2946                                 &scb->pthru_dma_addr);
2947
2948                 if( !scb->pthru ) {
2949                         dev_warn(&adapter->dev->dev, "RAID: Can't allocate passthru\n");
2950                         mega_free_sgl(adapter);
2951                         return -1;
2952                 }
2953
2954                 scb->epthru = pci_alloc_consistent(adapter->dev,
2955                                 sizeof(mega_ext_passthru),
2956                                 &scb->epthru_dma_addr);
2957
2958                 if( !scb->epthru ) {
2959                         dev_warn(&adapter->dev->dev,
2960                                 "Can't allocate extended passthru\n");
2961                         mega_free_sgl(adapter);
2962                         return -1;
2963                 }
2964
2965
2966                 scb->dma_type = MEGA_DMA_TYPE_NONE;
2967
2968                 /*
2969                  * Link to free list
2970                  * lock not required since we are loading the driver, so no
2971                  * commands possible right now.
2972                  */
2973                 scb->state = SCB_FREE;
2974                 scb->cmd = NULL;
2975                 list_add(&scb->list, &adapter->free_list);
2976         }
2977
2978         return 0;
2979 }
2980
2981
2982 /**
2983  * megadev_open()
2984  * @inode - unused
2985  * @filep - unused
2986  *
2987  * Routines for the character/ioctl interface to the driver. Find out if this
2988  * is a valid open. 
2989  */
2990 static int
2991 megadev_open (struct inode *inode, struct file *filep)
2992 {
2993         /*
2994          * Only allow superuser to access private ioctl interface
2995          */
2996         if( !capable(CAP_SYS_ADMIN) ) return -EACCES;
2997
2998         return 0;
2999 }
3000
3001
3002 /**
3003  * megadev_ioctl()
3004  * @inode - Our device inode
3005  * @filep - unused
3006  * @cmd - ioctl command
3007  * @arg - user buffer
3008  *
3009  * ioctl entry point for our private ioctl interface. We move the data in from
3010  * the user space, prepare the command (if necessary, convert the old MIMD
3011  * ioctl to new ioctl command), and issue a synchronous command to the
3012  * controller.
3013  */
3014 static int
3015 megadev_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
3016 {
3017         adapter_t       *adapter;
3018         nitioctl_t      uioc;
3019         int             adapno;
3020         int             rval;
3021         mega_passthru   __user *upthru; /* user address for passthru */
3022         mega_passthru   *pthru;         /* copy user passthru here */
3023         dma_addr_t      pthru_dma_hndl;
3024         void            *data = NULL;   /* data to be transferred */
3025         dma_addr_t      data_dma_hndl;  /* dma handle for data xfer area */
3026         megacmd_t       mc;
3027         megastat_t      __user *ustats;
3028         int             num_ldrv;
3029         u32             uxferaddr = 0;
3030         struct pci_dev  *pdev;
3031
3032         ustats = NULL; /* avoid compilation warnings */
3033         num_ldrv = 0;
3034
3035         /*
3036          * Make sure only USCSICMD are issued through this interface.
3037          * MIMD application would still fire different command.
3038          */
3039         if( (_IOC_TYPE(cmd) != MEGAIOC_MAGIC) && (cmd != USCSICMD) ) {
3040                 return -EINVAL;
3041         }
3042
3043         /*
3044          * Check and convert a possible MIMD command to NIT command.
3045          * mega_m_to_n() copies the data from the user space, so we do not
3046          * have to do it here.
3047          * NOTE: We will need some user address to copyout the data, therefore
3048          * the inteface layer will also provide us with the required user
3049          * addresses.
3050          */
3051         memset(&uioc, 0, sizeof(nitioctl_t));
3052         if( (rval = mega_m_to_n( (void __user *)arg, &uioc)) != 0 )
3053                 return rval;
3054
3055
3056         switch( uioc.opcode ) {
3057
3058         case GET_DRIVER_VER:
3059                 if( put_user(driver_ver, (u32 __user *)uioc.uioc_uaddr) )
3060                         return (-EFAULT);
3061
3062                 break;
3063
3064         case GET_N_ADAP:
3065                 if( put_user(hba_count, (u32 __user *)uioc.uioc_uaddr) )
3066                         return (-EFAULT);
3067
3068                 /*
3069                  * Shucks. MIMD interface returns a positive value for number
3070                  * of adapters. TODO: Change it to return 0 when there is no
3071                  * applicatio using mimd interface.
3072                  */
3073                 return hba_count;
3074
3075         case GET_ADAP_INFO:
3076
3077                 /*
3078                  * Which adapter
3079                  */
3080                 if( (adapno = GETADAP(uioc.adapno)) >= hba_count )
3081                         return (-ENODEV);
3082
3083                 if( copy_to_user(uioc.uioc_uaddr, mcontroller+adapno,
3084                                 sizeof(struct mcontroller)) )
3085                         return (-EFAULT);
3086                 break;
3087
3088 #if MEGA_HAVE_STATS
3089
3090         case GET_STATS:
3091                 /*
3092                  * Which adapter
3093                  */
3094                 if( (adapno = GETADAP(uioc.adapno)) >= hba_count )
3095                         return (-ENODEV);
3096
3097                 adapter = hba_soft_state[adapno];
3098
3099                 ustats = uioc.uioc_uaddr;
3100
3101                 if( copy_from_user(&num_ldrv, &ustats->num_ldrv, sizeof(int)) )
3102                         return (-EFAULT);
3103
3104                 /*
3105                  * Check for the validity of the logical drive number
3106                  */
3107                 if( num_ldrv >= MAX_LOGICAL_DRIVES_40LD ) return -EINVAL;
3108
3109                 if( copy_to_user(ustats->nreads, adapter->nreads,
3110                                         num_ldrv*sizeof(u32)) )
3111                         return -EFAULT;
3112
3113                 if( copy_to_user(ustats->nreadblocks, adapter->nreadblocks,
3114                                         num_ldrv*sizeof(u32)) )
3115                         return -EFAULT;
3116
3117                 if( copy_to_user(ustats->nwrites, adapter->nwrites,
3118                                         num_ldrv*sizeof(u32)) )
3119                         return -EFAULT;
3120
3121                 if( copy_to_user(ustats->nwriteblocks, adapter->nwriteblocks,
3122                                         num_ldrv*sizeof(u32)) )
3123                         return -EFAULT;
3124
3125                 if( copy_to_user(ustats->rd_errors, adapter->rd_errors,
3126                                         num_ldrv*sizeof(u32)) )
3127                         return -EFAULT;
3128
3129                 if( copy_to_user(ustats->wr_errors, adapter->wr_errors,
3130                                         num_ldrv*sizeof(u32)) )
3131                         return -EFAULT;
3132
3133                 return 0;
3134
3135 #endif
3136         case MBOX_CMD:
3137
3138                 /*
3139                  * Which adapter
3140                  */
3141                 if( (adapno = GETADAP(uioc.adapno)) >= hba_count )
3142                         return (-ENODEV);
3143
3144                 adapter = hba_soft_state[adapno];
3145
3146                 /*
3147                  * Deletion of logical drive is a special case. The adapter
3148                  * should be quiescent before this command is issued.
3149                  */
3150                 if( uioc.uioc_rmbox[0] == FC_DEL_LOGDRV &&
3151                                 uioc.uioc_rmbox[2] == OP_DEL_LOGDRV ) {
3152
3153                         /*
3154                          * Do we support this feature
3155                          */
3156                         if( !adapter->support_random_del ) {
3157                                 dev_warn(&adapter->dev->dev, "logdrv "
3158                                         "delete on non-supporting F/W\n");
3159
3160                                 return (-EINVAL);
3161                         }
3162
3163                         rval = mega_del_logdrv( adapter, uioc.uioc_rmbox[3] );
3164
3165                         if( rval == 0 ) {
3166                                 memset(&mc, 0, sizeof(megacmd_t));
3167
3168                                 mc.status = rval;
3169
3170                                 rval = mega_n_to_m((void __user *)arg, &mc);
3171                         }
3172
3173                         return rval;
3174                 }
3175                 /*
3176                  * This interface only support the regular passthru commands.
3177                  * Reject extended passthru and 64-bit passthru
3178                  */
3179                 if( uioc.uioc_rmbox[0] == MEGA_MBOXCMD_PASSTHRU64 ||
3180                         uioc.uioc_rmbox[0] == MEGA_MBOXCMD_EXTPTHRU ) {
3181
3182                         dev_warn(&adapter->dev->dev, "rejected passthru\n");
3183
3184                         return (-EINVAL);
3185                 }
3186
3187                 /*
3188                  * For all internal commands, the buffer must be allocated in
3189                  * <4GB address range
3190                  */
3191                 if( make_local_pdev(adapter, &pdev) != 0 )
3192                         return -EIO;
3193
3194                 /* Is it a passthru command or a DCMD */
3195                 if( uioc.uioc_rmbox[0] == MEGA_MBOXCMD_PASSTHRU ) {
3196                         /* Passthru commands */
3197
3198                         pthru = pci_alloc_consistent(pdev,
3199                                         sizeof(mega_passthru),
3200                                         &pthru_dma_hndl);
3201
3202                         if( pthru == NULL ) {
3203                                 free_local_pdev(pdev);
3204                                 return (-ENOMEM);
3205                         }
3206
3207                         /*
3208                          * The user passthru structure
3209                          */
3210                         upthru = (mega_passthru __user *)(unsigned long)MBOX(uioc)->xferaddr;
3211
3212                         /*
3213                          * Copy in the user passthru here.
3214                          */
3215                         if( copy_from_user(pthru, upthru,
3216                                                 sizeof(mega_passthru)) ) {
3217
3218                                 pci_free_consistent(pdev,
3219                                                 sizeof(mega_passthru), pthru,
3220                                                 pthru_dma_hndl);
3221
3222                                 free_local_pdev(pdev);
3223
3224                                 return (-EFAULT);
3225                         }
3226
3227                         /*
3228                          * Is there a data transfer
3229                          */
3230                         if( pthru->dataxferlen ) {
3231                                 data = pci_alloc_consistent(pdev,
3232                                                 pthru->dataxferlen,
3233                                                 &data_dma_hndl);
3234
3235                                 if( data == NULL ) {
3236                                         pci_free_consistent(pdev,
3237                                                         sizeof(mega_passthru),
3238                                                         pthru,
3239                                                         pthru_dma_hndl);
3240
3241                                         free_local_pdev(pdev);
3242
3243                                         return (-ENOMEM);
3244                                 }
3245
3246                                 /*
3247                                  * Save the user address and point the kernel
3248                                  * address at just allocated memory
3249                                  */
3250                                 uxferaddr = pthru->dataxferaddr;
3251                                 pthru->dataxferaddr = data_dma_hndl;
3252                         }
3253
3254
3255                         /*
3256                          * Is data coming down-stream
3257                          */
3258                         if( pthru->dataxferlen && (uioc.flags & UIOC_WR) ) {
3259                                 /*
3260                                  * Get the user data
3261                                  */
3262                                 if( copy_from_user(data, (char __user *)(unsigned long) uxferaddr,
3263                                                         pthru->dataxferlen) ) {
3264                                         rval = (-EFAULT);
3265                                         goto freemem_and_return;
3266                                 }
3267                         }
3268
3269                         memset(&mc, 0, sizeof(megacmd_t));
3270
3271                         mc.cmd = MEGA_MBOXCMD_PASSTHRU;
3272                         mc.xferaddr = (u32)pthru_dma_hndl;
3273
3274                         /*
3275                          * Issue the command
3276                          */
3277                         mega_internal_command(adapter, &mc, pthru);
3278
3279                         rval = mega_n_to_m((void __user *)arg, &mc);
3280
3281                         if( rval ) goto freemem_and_return;
3282
3283
3284                         /*
3285                          * Is data going up-stream
3286                          */
3287                         if( pthru->dataxferlen && (uioc.flags & UIOC_RD) ) {
3288                                 if( copy_to_user((char __user *)(unsigned long) uxferaddr, data,
3289                                                         pthru->dataxferlen) ) {
3290                                         rval = (-EFAULT);
3291                                 }
3292                         }
3293
3294                         /*
3295                          * Send the request sense data also, irrespective of
3296                          * whether the user has asked for it or not.
3297                          */
3298                         if (copy_to_user(upthru->reqsensearea,
3299                                         pthru->reqsensearea, 14))
3300                                 rval = -EFAULT;
3301
3302 freemem_and_return:
3303                         if( pthru->dataxferlen ) {
3304                                 pci_free_consistent(pdev,
3305                                                 pthru->dataxferlen, data,
3306                                                 data_dma_hndl);
3307                         }
3308
3309                         pci_free_consistent(pdev, sizeof(mega_passthru),
3310                                         pthru, pthru_dma_hndl);
3311
3312                         free_local_pdev(pdev);
3313
3314                         return rval;
3315                 }
3316                 else {
3317                         /* DCMD commands */
3318
3319                         /*
3320                          * Is there a data transfer
3321                          */
3322                         if( uioc.xferlen ) {
3323                                 data = pci_alloc_consistent(pdev,
3324                                                 uioc.xferlen, &data_dma_hndl);
3325
3326                                 if( data == NULL ) {
3327                                         free_local_pdev(pdev);
3328                                         return (-ENOMEM);
3329                                 }
3330
3331                                 uxferaddr = MBOX(uioc)->xferaddr;
3332                         }
3333
3334                         /*
3335                          * Is data coming down-stream
3336                          */
3337                         if( uioc.xferlen && (uioc.flags & UIOC_WR) ) {
3338                                 /*
3339                                  * Get the user data
3340                                  */
3341                                 if( copy_from_user(data, (char __user *)(unsigned long) uxferaddr,
3342                                                         uioc.xferlen) ) {
3343
3344                                         pci_free_consistent(pdev,
3345                                                         uioc.xferlen,
3346                                                         data, data_dma_hndl);
3347
3348                                         free_local_pdev(pdev);
3349
3350                                         return (-EFAULT);
3351                                 }
3352                         }
3353
3354                         memcpy(&mc, MBOX(uioc), sizeof(megacmd_t));
3355
3356                         mc.xferaddr = (u32)data_dma_hndl;
3357
3358                         /*
3359                          * Issue the command
3360                          */
3361                         mega_internal_command(adapter, &mc, NULL);
3362
3363                         rval = mega_n_to_m((void __user *)arg, &mc);
3364
3365                         if( rval ) {
3366                                 if( uioc.xferlen ) {
3367                                         pci_free_consistent(pdev,
3368                                                         uioc.xferlen, data,
3369                                                         data_dma_hndl);
3370                                 }
3371
3372                                 free_local_pdev(pdev);
3373
3374                                 return rval;
3375                         }
3376
3377                         /*
3378                          * Is data going up-stream
3379                          */
3380                         if( uioc.xferlen && (uioc.flags & UIOC_RD) ) {
3381                                 if( copy_to_user((char __user *)(unsigned long) uxferaddr, data,
3382                                                         uioc.xferlen) ) {
3383
3384                                         rval = (-EFAULT);
3385                                 }
3386                         }
3387
3388                         if( uioc.xferlen ) {
3389                                 pci_free_consistent(pdev,
3390                                                 uioc.xferlen, data,
3391                                                 data_dma_hndl);
3392                         }
3393
3394                         free_local_pdev(pdev);
3395
3396                         return rval;
3397                 }
3398
3399         default:
3400                 return (-EINVAL);
3401         }
3402
3403         return 0;
3404 }
3405
3406 static long
3407 megadev_unlocked_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
3408 {
3409         int ret;
3410
3411         mutex_lock(&megadev_mutex);
3412         ret = megadev_ioctl(filep, cmd, arg);
3413         mutex_unlock(&megadev_mutex);
3414
3415         return ret;
3416 }
3417
3418 /**
3419  * mega_m_to_n()
3420  * @arg - user address
3421  * @uioc - new ioctl structure
3422  *
3423  * A thin layer to convert older mimd interface ioctl structure to NIT ioctl
3424  * structure
3425  *
3426  * Converts the older mimd ioctl structure to newer NIT structure
3427  */
3428 static int
3429 mega_m_to_n(void __user *arg, nitioctl_t *uioc)
3430 {
3431         struct uioctl_t uioc_mimd;
3432         char    signature[8] = {0};
3433         u8      opcode;
3434         u8      subopcode;
3435
3436
3437         /*
3438          * check is the application conforms to NIT. We do not have to do much
3439          * in that case.
3440          * We exploit the fact that the signature is stored in the very
3441          * beginning of the structure.
3442          */
3443
3444         if( copy_from_user(signature, arg, 7) )
3445                 return (-EFAULT);
3446
3447         if( memcmp(signature, "MEGANIT", 7) == 0 ) {
3448
3449                 /*
3450                  * NOTE NOTE: The nit ioctl is still under flux because of
3451                  * change of mailbox definition, in HPE. No applications yet
3452                  * use this interface and let's not have applications use this
3453                  * interface till the new specifitions are in place.
3454                  */
3455                 return -EINVAL;
3456 #if 0
3457                 if( copy_from_user(uioc, arg, sizeof(nitioctl_t)) )
3458                         return (-EFAULT);
3459                 return 0;
3460 #endif
3461         }
3462
3463         /*
3464          * Else assume we have mimd uioctl_t as arg. Convert to nitioctl_t
3465          *
3466          * Get the user ioctl structure
3467          */
3468         if( copy_from_user(&uioc_mimd, arg, sizeof(struct uioctl_t)) )
3469                 return (-EFAULT);
3470
3471
3472         /*
3473          * Get the opcode and subopcode for the commands
3474          */
3475         opcode = uioc_mimd.ui.fcs.opcode;
3476         subopcode = uioc_mimd.ui.fcs.subopcode;
3477
3478         switch (opcode) {
3479         case 0x82:
3480
3481                 switch (subopcode) {
3482
3483                 case MEGAIOC_QDRVRVER:  /* Query driver version */
3484                         uioc->opcode = GET_DRIVER_VER;
3485                         uioc->uioc_uaddr = uioc_mimd.data;
3486                         break;
3487
3488                 case MEGAIOC_QNADAP:    /* Get # of adapters */
3489                         uioc->opcode = GET_N_ADAP;
3490                         uioc->uioc_uaddr = uioc_mimd.data;
3491                         break;
3492
3493                 case MEGAIOC_QADAPINFO: /* Get adapter information */
3494                         uioc->opcode = GET_ADAP_INFO;
3495                         uioc->adapno = uioc_mimd.ui.fcs.adapno;
3496                         uioc->uioc_uaddr = uioc_mimd.data;
3497                         break;
3498
3499                 default:
3500                         return(-EINVAL);
3501                 }
3502
3503                 break;
3504
3505
3506         case 0x81:
3507
3508                 uioc->opcode = MBOX_CMD;
3509                 uioc->adapno = uioc_mimd.ui.fcs.adapno;
3510
3511                 memcpy(uioc->uioc_rmbox, uioc_mimd.mbox, 18);
3512
3513                 uioc->xferlen = uioc_mimd.ui.fcs.length;
3514
3515                 if( uioc_mimd.outlen ) uioc->flags = UIOC_RD;
3516                 if( uioc_mimd.inlen ) uioc->flags |= UIOC_WR;
3517
3518                 break;
3519
3520         case 0x80:
3521
3522                 uioc->opcode = MBOX_CMD;
3523                 uioc->adapno = uioc_mimd.ui.fcs.adapno;
3524
3525                 memcpy(uioc->uioc_rmbox, uioc_mimd.mbox, 18);
3526
3527                 /*
3528                  * Choose the xferlen bigger of input and output data
3529                  */
3530                 uioc->xferlen = uioc_mimd.outlen > uioc_mimd.inlen ?
3531                         uioc_mimd.outlen : uioc_mimd.inlen;
3532
3533                 if( uioc_mimd.outlen ) uioc->flags = UIOC_RD;
3534                 if( uioc_mimd.inlen ) uioc->flags |= UIOC_WR;
3535
3536                 break;
3537
3538         default:
3539                 return (-EINVAL);
3540
3541         }
3542
3543         return 0;
3544 }
3545
3546 /*
3547  * mega_n_to_m()
3548  * @arg - user address
3549  * @mc - mailbox command
3550  *
3551  * Updates the status information to the application, depending on application
3552  * conforms to older mimd ioctl interface or newer NIT ioctl interface
3553  */
3554 static int
3555 mega_n_to_m(void __user *arg, megacmd_t *mc)
3556 {
3557         nitioctl_t      __user *uiocp;
3558         megacmd_t       __user *umc;
3559         mega_passthru   __user *upthru;
3560         struct uioctl_t __user *uioc_mimd;
3561         char    signature[8] = {0};
3562
3563         /*
3564          * check is the application conforms to NIT.
3565          */
3566         if( copy_from_user(signature, arg, 7) )
3567                 return -EFAULT;
3568
3569         if( memcmp(signature, "MEGANIT", 7) == 0 ) {
3570
3571                 uiocp = arg;
3572
3573                 if( put_user(mc->status, (u8 __user *)&MBOX_P(uiocp)->status) )
3574                         return (-EFAULT);
3575
3576                 if( mc->cmd == MEGA_MBOXCMD_PASSTHRU ) {
3577
3578                         umc = MBOX_P(uiocp);
3579
3580                         if (get_user(upthru, (mega_passthru __user * __user *)&umc->xferaddr))
3581                                 return -EFAULT;
3582
3583                         if( put_user(mc->status, (u8 __user *)&upthru->scsistatus))
3584                                 return (-EFAULT);
3585                 }
3586         }
3587         else {
3588                 uioc_mimd = arg;
3589
3590                 if( put_user(mc->status, (u8 __user *)&uioc_mimd->mbox[17]) )
3591                         return (-EFAULT);
3592
3593                 if( mc->cmd == MEGA_MBOXCMD_PASSTHRU ) {
3594
3595                         umc = (megacmd_t __user *)uioc_mimd->mbox;
3596
3597                         if (get_user(upthru, (mega_passthru __user * __user *)&umc->xferaddr))
3598                                 return (-EFAULT);
3599
3600                         if( put_user(mc->status, (u8 __user *)&upthru->scsistatus) )
3601                                 return (-EFAULT);
3602                 }
3603         }
3604
3605         return 0;
3606 }
3607
3608
3609 /*
3610  * MEGARAID 'FW' commands.
3611  */
3612
3613 /**
3614  * mega_is_bios_enabled()
3615  * @adapter - pointer to our soft state
3616  *
3617  * issue command to find out if the BIOS is enabled for this controller
3618  */
3619 static int
3620 mega_is_bios_enabled(adapter_t *adapter)
3621 {
3622         unsigned char   raw_mbox[sizeof(struct mbox_out)];
3623         mbox_t  *mbox;
3624         int     ret;
3625
3626         mbox = (mbox_t *)raw_mbox;
3627
3628         memset(&mbox->m_out, 0, sizeof(raw_mbox));
3629
3630         memset((void *)adapter->mega_buffer, 0, MEGA_BUFFER_SIZE);
3631
3632         mbox->m_out.xferaddr = (u32)adapter->buf_dma_handle;
3633
3634         raw_mbox[0] = IS_BIOS_ENABLED;
3635         raw_mbox[2] = GET_BIOS;
3636
3637
3638         ret = issue_scb_block(adapter, raw_mbox);
3639
3640         return *(char *)adapter->mega_buffer;
3641 }
3642
3643
3644 /**
3645  * mega_enum_raid_scsi()
3646  * @adapter - pointer to our soft state
3647  *
3648  * Find out what channels are RAID/SCSI. This information is used to
3649  * differentiate the virtual channels and physical channels and to support
3650  * ROMB feature and non-disk devices.
3651  */
3652 static void
3653 mega_enum_raid_scsi(adapter_t *adapter)
3654 {
3655         unsigned char raw_mbox[sizeof(struct mbox_out)];
3656         mbox_t *mbox;
3657         int i;
3658
3659         mbox = (mbox_t *)raw_mbox;
3660
3661         memset(&mbox->m_out, 0, sizeof(raw_mbox));
3662
3663         /*
3664          * issue command to find out what channels are raid/scsi
3665          */
3666         raw_mbox[0] = CHNL_CLASS;
3667         raw_mbox[2] = GET_CHNL_CLASS;
3668
3669         memset((void *)adapter->mega_buffer, 0, MEGA_BUFFER_SIZE);
3670
3671         mbox->m_out.xferaddr = (u32)adapter->buf_dma_handle;
3672
3673         /*
3674          * Non-ROMB firmware fail this command, so all channels
3675          * must be shown RAID
3676          */
3677         adapter->mega_ch_class = 0xFF;
3678
3679         if(!issue_scb_block(adapter, raw_mbox)) {
3680                 adapter->mega_ch_class = *((char *)adapter->mega_buffer);
3681
3682         }
3683
3684         for( i = 0; i < adapter->product_info.nchannels; i++ ) { 
3685                 if( (adapter->mega_ch_class >> i) & 0x01 ) {
3686                         dev_info(&adapter->dev->dev, "channel[%d] is raid\n",
3687                                         i);
3688                 }
3689                 else {
3690                         dev_info(&adapter->dev->dev, "channel[%d] is scsi\n",
3691                                         i);
3692                 }
3693         }
3694
3695         return;
3696 }
3697
3698
3699 /**
3700  * mega_get_boot_drv()
3701  * @adapter - pointer to our soft state
3702  *
3703  * Find out which device is the boot device. Note, any logical drive or any
3704  * phyical device (e.g., a CDROM) can be designated as a boot device.
3705  */
3706 static void
3707 mega_get_boot_drv(adapter_t *adapter)
3708 {
3709         struct private_bios_data        *prv_bios_data;
3710         unsigned char   raw_mbox[sizeof(struct mbox_out)];
3711         mbox_t  *mbox;
3712         u16     cksum = 0;
3713         u8      *cksum_p;
3714         u8      boot_pdrv;
3715         int     i;
3716
3717         mbox = (mbox_t *)raw_mbox;
3718
3719         memset(&mbox->m_out, 0, sizeof(raw_mbox));
3720
3721         raw_mbox[0] = BIOS_PVT_DATA;
3722         raw_mbox[2] = GET_BIOS_PVT_DATA;
3723
3724         memset((void *)adapter->mega_buffer, 0, MEGA_BUFFER_SIZE);
3725
3726         mbox->m_out.xferaddr = (u32)adapter->buf_dma_handle;
3727
3728         adapter->boot_ldrv_enabled = 0;
3729         adapter->boot_ldrv = 0;
3730
3731         adapter->boot_pdrv_enabled = 0;
3732         adapter->boot_pdrv_ch = 0;
3733         adapter->boot_pdrv_tgt = 0;
3734
3735         if(issue_scb_block(adapter, raw_mbox) == 0) {
3736                 prv_bios_data =
3737                         (struct private_bios_data *)adapter->mega_buffer;
3738
3739                 cksum = 0;
3740                 cksum_p = (char *)prv_bios_data;
3741                 for (i = 0; i < 14; i++ ) {
3742                         cksum += (u16)(*cksum_p++);
3743                 }
3744
3745                 if (prv_bios_data->cksum == (u16)(0-cksum) ) {
3746
3747                         /*
3748                          * If MSB is set, a physical drive is set as boot
3749                          * device
3750                          */
3751                         if( prv_bios_data->boot_drv & 0x80 ) {
3752                                 adapter->boot_pdrv_enabled = 1;
3753                                 boot_pdrv = prv_bios_data->boot_drv & 0x7F;
3754                                 adapter->boot_pdrv_ch = boot_pdrv / 16;
3755                                 adapter->boot_pdrv_tgt = boot_pdrv % 16;
3756                         }
3757                         else {
3758                                 adapter->boot_ldrv_enabled = 1;
3759                                 adapter->boot_ldrv = prv_bios_data->boot_drv;
3760                         }
3761                 }
3762         }
3763
3764 }
3765
3766 /**
3767  * mega_support_random_del()
3768  * @adapter - pointer to our soft state
3769  *
3770  * Find out if this controller supports random deletion and addition of
3771  * logical drives
3772  */
3773 static int
3774 mega_support_random_del(adapter_t *adapter)
3775 {
3776         unsigned char raw_mbox[sizeof(struct mbox_out)];
3777         mbox_t *mbox;
3778         int rval;
3779
3780         mbox = (mbox_t *)raw_mbox;
3781
3782         memset(&mbox->m_out, 0, sizeof(raw_mbox));
3783
3784         /*
3785          * issue command
3786          */
3787         raw_mbox[0] = FC_DEL_LOGDRV;
3788         raw_mbox[2] = OP_SUP_DEL_LOGDRV;
3789
3790         rval = issue_scb_block(adapter, raw_mbox);
3791
3792         return !rval;
3793 }
3794
3795
3796 /**
3797  * mega_support_ext_cdb()
3798  * @adapter - pointer to our soft state
3799  *
3800  * Find out if this firmware support cdblen > 10
3801  */
3802 static int
3803 mega_support_ext_cdb(adapter_t *adapter)
3804 {
3805         unsigned char raw_mbox[sizeof(struct mbox_out)];
3806         mbox_t *mbox;
3807         int rval;
3808
3809         mbox = (mbox_t *)raw_mbox;
3810
3811         memset(&mbox->m_out, 0, sizeof(raw_mbox));
3812         /*
3813          * issue command to find out if controller supports extended CDBs.
3814          */
3815         raw_mbox[0] = 0xA4;
3816         raw_mbox[2] = 0x16;
3817
3818         rval = issue_scb_block(adapter, raw_mbox);
3819
3820         return !rval;
3821 }
3822
3823
3824 /**
3825  * mega_del_logdrv()
3826  * @adapter - pointer to our soft state
3827  * @logdrv - logical drive to be deleted
3828  *
3829  * Delete the specified logical drive. It is the responsibility of the user
3830  * app to let the OS know about this operation.
3831  */
3832 static int
3833 mega_del_logdrv(adapter_t *adapter, int logdrv)
3834 {
3835         unsigned long flags;
3836         scb_t *scb;
3837         int rval;
3838
3839         /*
3840          * Stop sending commands to the controller, queue them internally.
3841          * When deletion is complete, ISR will flush the queue.
3842          */
3843         atomic_set(&adapter->quiescent, 1);
3844
3845         /*
3846          * Wait till all the issued commands are complete and there are no
3847          * commands in the pending queue
3848          */
3849         while (atomic_read(&adapter->pend_cmds) > 0 ||
3850                !list_empty(&adapter->pending_list))
3851                 msleep(1000);   /* sleep for 1s */
3852
3853         rval = mega_do_del_logdrv(adapter, logdrv);
3854
3855         spin_lock_irqsave(&adapter->lock, flags);
3856
3857         /*
3858          * If delete operation was successful, add 0x80 to the logical drive
3859          * ids for commands in the pending queue.
3860          */
3861         if (adapter->read_ldidmap) {
3862                 struct list_head *pos;
3863                 list_for_each(pos, &adapter->pending_list) {
3864                         scb = list_entry(pos, scb_t, list);
3865                         if (scb->pthru->logdrv < 0x80 )
3866                                 scb->pthru->logdrv += 0x80;
3867                 }
3868         }
3869
3870         atomic_set(&adapter->quiescent, 0);
3871
3872         mega_runpendq(adapter);
3873
3874         spin_unlock_irqrestore(&adapter->lock, flags);
3875
3876         return rval;
3877 }
3878
3879
3880 static int
3881 mega_do_del_logdrv(adapter_t *adapter, int logdrv)
3882 {
3883         megacmd_t       mc;
3884         int     rval;
3885
3886         memset( &mc, 0, sizeof(megacmd_t));
3887
3888         mc.cmd = FC_DEL_LOGDRV;
3889         mc.opcode = OP_DEL_LOGDRV;
3890         mc.subopcode = logdrv;
3891
3892         rval = mega_internal_command(adapter, &mc, NULL);
3893
3894         /* log this event */
3895         if(rval) {
3896                 dev_warn(&adapter->dev->dev, "Delete LD-%d failed", logdrv);
3897                 return rval;
3898         }
3899
3900         /*
3901          * After deleting first logical drive, the logical drives must be
3902          * addressed by adding 0x80 to the logical drive id.
3903          */
3904         adapter->read_ldidmap = 1;
3905
3906         return rval;
3907 }
3908
3909
3910 /**
3911  * mega_get_max_sgl()
3912  * @adapter - pointer to our soft state
3913  *
3914  * Find out the maximum number of scatter-gather elements supported by this
3915  * version of the firmware
3916  */
3917 static void
3918 mega_get_max_sgl(adapter_t *adapter)
3919 {
3920         unsigned char   raw_mbox[sizeof(struct mbox_out)];
3921         mbox_t  *mbox;
3922
3923         mbox = (mbox_t *)raw_mbox;
3924
3925         memset(mbox, 0, sizeof(raw_mbox));
3926
3927         memset((void *)adapter->mega_buffer, 0, MEGA_BUFFER_SIZE);
3928
3929         mbox->m_out.xferaddr = (u32)adapter->buf_dma_handle;
3930
3931         raw_mbox[0] = MAIN_MISC_OPCODE;
3932         raw_mbox[2] = GET_MAX_SG_SUPPORT;
3933
3934
3935         if( issue_scb_block(adapter, raw_mbox) ) {
3936                 /*
3937                  * f/w does not support this command. Choose the default value
3938                  */
3939                 adapter->sglen = MIN_SGLIST;
3940         }
3941         else {
3942                 adapter->sglen = *((char *)adapter->mega_buffer);
3943                 
3944                 /*
3945                  * Make sure this is not more than the resources we are
3946                  * planning to allocate
3947                  */
3948                 if ( adapter->sglen > MAX_SGLIST )
3949                         adapter->sglen = MAX_SGLIST;
3950         }
3951
3952         return;
3953 }
3954
3955
3956 /**
3957  * mega_support_cluster()
3958  * @adapter - pointer to our soft state
3959  *
3960  * Find out if this firmware support cluster calls.
3961  */
3962 static int
3963 mega_support_cluster(adapter_t *adapter)
3964 {
3965         unsigned char   raw_mbox[sizeof(struct mbox_out)];
3966         mbox_t  *mbox;
3967
3968         mbox = (mbox_t *)raw_mbox;
3969
3970         memset(mbox, 0, sizeof(raw_mbox));
3971
3972         memset((void *)adapter->mega_buffer, 0, MEGA_BUFFER_SIZE);
3973
3974         mbox->m_out.xferaddr = (u32)adapter->buf_dma_handle;
3975
3976         /*
3977          * Try to get the initiator id. This command will succeed iff the
3978          * clustering is available on this HBA.
3979          */
3980         raw_mbox[0] = MEGA_GET_TARGET_ID;
3981
3982         if( issue_scb_block(adapter, raw_mbox) == 0 ) {
3983
3984                 /*
3985                  * Cluster support available. Get the initiator target id.
3986                  * Tell our id to mid-layer too.
3987                  */
3988                 adapter->this_id = *(u32 *)adapter->mega_buffer;
3989                 adapter->host->this_id = adapter->this_id;
3990
3991                 return 1;
3992         }
3993
3994         return 0;
3995 }
3996
3997 #ifdef CONFIG_PROC_FS
3998 /**
3999  * mega_adapinq()
4000  * @adapter - pointer to our soft state
4001  * @dma_handle - DMA address of the buffer
4002  *
4003  * Issue internal commands while interrupts are available.
4004  * We only issue direct mailbox commands from within the driver. ioctl()
4005  * interface using these routines can issue passthru commands.
4006  */
4007 static int
4008 mega_adapinq(adapter_t *adapter, dma_addr_t dma_handle)
4009 {
4010         megacmd_t       mc;
4011
4012         memset(&mc, 0, sizeof(megacmd_t));
4013
4014         if( adapter->flag & BOARD_40LD ) {
4015                 mc.cmd = FC_NEW_CONFIG;
4016                 mc.opcode = NC_SUBOP_ENQUIRY3;
4017                 mc.subopcode = ENQ3_GET_SOLICITED_FULL;
4018         }
4019         else {
4020                 mc.cmd = MEGA_MBOXCMD_ADPEXTINQ;
4021         }
4022
4023         mc.xferaddr = (u32)dma_handle;
4024
4025         if ( mega_internal_command(adapter, &mc, NULL) != 0 ) {
4026                 return -1;
4027         }
4028
4029         return 0;
4030 }
4031
4032
4033 /** mega_internal_dev_inquiry()
4034  * @adapter - pointer to our soft state
4035  * @ch - channel for this device
4036  * @tgt - ID of this device
4037  * @buf_dma_handle - DMA address of the buffer
4038  *
4039  * Issue the scsi inquiry for the specified device.
4040  */
4041 static int
4042 mega_internal_dev_inquiry(adapter_t *adapter, u8 ch, u8 tgt,
4043                 dma_addr_t buf_dma_handle)
4044 {
4045         mega_passthru   *pthru;
4046         dma_addr_t      pthru_dma_handle;
4047         megacmd_t       mc;
4048         int             rval;
4049         struct pci_dev  *pdev;
4050
4051
4052         /*
4053          * For all internal commands, the buffer must be allocated in <4GB
4054          * address range
4055          */
4056         if( make_local_pdev(adapter, &pdev) != 0 ) return -1;
4057
4058         pthru = pci_alloc_consistent(pdev, sizeof(mega_passthru),
4059                         &pthru_dma_handle);
4060
4061         if( pthru == NULL ) {
4062                 free_local_pdev(pdev);
4063                 return -1;
4064         }
4065
4066         pthru->timeout = 2;
4067         pthru->ars = 1;
4068         pthru->reqsenselen = 14;
4069         pthru->islogical = 0;
4070
4071         pthru->channel = (adapter->flag & BOARD_40LD) ? 0 : ch;
4072
4073         pthru->target = (adapter->flag & BOARD_40LD) ? (ch << 4)|tgt : tgt;
4074
4075         pthru->cdblen = 6;
4076
4077         pthru->cdb[0] = INQUIRY;
4078         pthru->cdb[1] = 0;
4079         pthru->cdb[2] = 0;
4080         pthru->cdb[3] = 0;
4081         pthru->cdb[4] = 255;
4082         pthru->cdb[5] = 0;
4083
4084
4085         pthru->dataxferaddr = (u32)buf_dma_handle;
4086         pthru->dataxferlen = 256;
4087
4088         memset(&mc, 0, sizeof(megacmd_t));
4089
4090         mc.cmd = MEGA_MBOXCMD_PASSTHRU;
4091         mc.xferaddr = (u32)pthru_dma_handle;
4092
4093         rval = mega_internal_command(adapter, &mc, pthru);
4094
4095         pci_free_consistent(pdev, sizeof(mega_passthru), pthru,
4096                         pthru_dma_handle);
4097
4098         free_local_pdev(pdev);
4099
4100         return rval;
4101 }
4102 #endif
4103
4104 /**
4105  * mega_internal_command()
4106  * @adapter - pointer to our soft state
4107  * @mc - the mailbox command
4108  * @pthru - Passthru structure for DCDB commands
4109  *
4110  * Issue the internal commands in interrupt mode.
4111  * The last argument is the address of the passthru structure if the command
4112  * to be fired is a passthru command
4113  *
4114  * Note: parameter 'pthru' is null for non-passthru commands.
4115  */
4116 static int
4117 mega_internal_command(adapter_t *adapter, megacmd_t *mc, mega_passthru *pthru)
4118 {
4119         unsigned long flags;
4120         scb_t   *scb;
4121         int     rval;
4122
4123         /*
4124          * The internal commands share one command id and hence are
4125          * serialized. This is so because we want to reserve maximum number of
4126          * available command ids for the I/O commands.
4127          */
4128         mutex_lock(&adapter->int_mtx);
4129
4130         scb = &adapter->int_scb;
4131         memset(scb, 0, sizeof(scb_t));
4132
4133         scb->idx = CMDID_INT_CMDS;
4134         scb->state |= SCB_ACTIVE | SCB_PENDQ;
4135
4136         memcpy(scb->raw_mbox, mc, sizeof(megacmd_t));
4137
4138         /*
4139          * Is it a passthru command
4140          */
4141         if (mc->cmd == MEGA_MBOXCMD_PASSTHRU)
4142                 scb->pthru = pthru;
4143
4144         spin_lock_irqsave(&adapter->lock, flags);
4145         list_add_tail(&scb->list, &adapter->pending_list);
4146         /*
4147          * Check if the HBA is in quiescent state, e.g., during a
4148          * delete logical drive opertion. If it is, don't run
4149          * the pending_list.
4150          */
4151         if (atomic_read(&adapter->quiescent) == 0)
4152                 mega_runpendq(adapter);
4153         spin_unlock_irqrestore(&adapter->lock, flags);
4154
4155         wait_for_completion(&adapter->int_waitq);
4156
4157         mc->status = rval = adapter->int_status;
4158
4159         /*
4160          * Print a debug message for all failed commands. Applications can use
4161          * this information.
4162          */
4163         if (rval && trace_level) {
4164                 dev_info(&adapter->dev->dev, "cmd [%x, %x, %x] status:[%x]\n",
4165                         mc->cmd, mc->opcode, mc->subopcode, rval);
4166         }
4167
4168         mutex_unlock(&adapter->int_mtx);
4169         return rval;
4170 }
4171
4172 static struct scsi_host_template megaraid_template = {
4173         .module                         = THIS_MODULE,
4174         .name                           = "MegaRAID",
4175         .proc_name                      = "megaraid_legacy",
4176         .info                           = megaraid_info,
4177         .queuecommand                   = megaraid_queue,       
4178         .bios_param                     = megaraid_biosparam,
4179         .max_sectors                    = MAX_SECTORS_PER_IO,
4180         .can_queue                      = MAX_COMMANDS,
4181         .this_id                        = DEFAULT_INITIATOR_ID,
4182         .sg_tablesize                   = MAX_SGLIST,
4183         .cmd_per_lun                    = DEF_CMD_PER_LUN,
4184         .use_clustering                 = ENABLE_CLUSTERING,
4185         .eh_abort_handler               = megaraid_abort,
4186         .eh_device_reset_handler        = megaraid_reset,
4187         .eh_bus_reset_handler           = megaraid_reset,
4188         .eh_host_reset_handler          = megaraid_reset,
4189         .no_write_same                  = 1,
4190 };
4191
4192 static int
4193 megaraid_probe_one(struct pci_dev *pdev, const struct pci_device_id *id)
4194 {
4195         struct Scsi_Host *host;
4196         adapter_t *adapter;
4197         unsigned long mega_baseport, tbase, flag = 0;
4198         u16 subsysid, subsysvid;
4199         u8 pci_bus, pci_dev_func;
4200         int irq, i, j;
4201         int error = -ENODEV;
4202
4203         if (hba_count >= MAX_CONTROLLERS)
4204                 goto out;
4205
4206         if (pci_enable_device(pdev))
4207                 goto out;
4208         pci_set_master(pdev);
4209
4210         pci_bus = pdev->bus->number;
4211         pci_dev_func = pdev->devfn;
4212
4213         /*
4214          * The megaraid3 stuff reports the ID of the Intel part which is not
4215          * remotely specific to the megaraid
4216          */
4217         if (pdev->vendor == PCI_VENDOR_ID_INTEL) {
4218                 u16 magic;
4219                 /*
4220                  * Don't fall over the Compaq management cards using the same
4221                  * PCI identifier
4222                  */
4223                 if (pdev->subsystem_vendor == PCI_VENDOR_ID_COMPAQ &&
4224                     pdev->subsystem_device == 0xC000)
4225                         goto out_disable_device;
4226                 /* Now check the magic signature byte */
4227                 pci_read_config_word(pdev, PCI_CONF_AMISIG, &magic);
4228                 if (magic != HBA_SIGNATURE_471 && magic != HBA_SIGNATURE)
4229                         goto out_disable_device;
4230                 /* Ok it is probably a megaraid */
4231         }
4232
4233         /*
4234          * For these vendor and device ids, signature offsets are not
4235          * valid and 64 bit is implicit
4236          */
4237         if (id->driver_data & BOARD_64BIT)
4238                 flag |= BOARD_64BIT;
4239         else {
4240                 u32 magic64;
4241
4242                 pci_read_config_dword(pdev, PCI_CONF_AMISIG64, &magic64);
4243                 if (magic64 == HBA_SIGNATURE_64BIT)
4244                         flag |= BOARD_64BIT;
4245         }
4246
4247         subsysvid = pdev->subsystem_vendor;
4248         subsysid = pdev->subsystem_device;
4249
4250         dev_notice(&pdev->dev, "found 0x%4.04x:0x%4.04x\n",
4251                 id->vendor, id->device);
4252
4253         /* Read the base port and IRQ from PCI */
4254         mega_baseport = pci_resource_start(pdev, 0);
4255         irq = pdev->irq;
4256
4257         tbase = mega_baseport;
4258         if (pci_resource_flags(pdev, 0) & IORESOURCE_MEM) {
4259                 flag |= BOARD_MEMMAP;
4260
4261                 if (!request_mem_region(mega_baseport, 128, "megaraid")) {
4262                         dev_warn(&pdev->dev, "mem region busy!\n");
4263                         goto out_disable_device;
4264                 }
4265
4266                 mega_baseport = (unsigned long)ioremap(mega_baseport, 128);
4267                 if (!mega_baseport) {
4268                         dev_warn(&pdev->dev, "could not map hba memory\n");
4269                         goto out_release_region;
4270                 }
4271         } else {
4272                 flag |= BOARD_IOMAP;
4273                 mega_baseport += 0x10;
4274
4275                 if (!request_region(mega_baseport, 16, "megaraid"))
4276                         goto out_disable_device;
4277         }
4278
4279         /* Initialize SCSI Host structure */
4280         host = scsi_host_alloc(&megaraid_template, sizeof(adapter_t));
4281         if (!host)
4282                 goto out_iounmap;
4283
4284         adapter = (adapter_t *)host->hostdata;
4285         memset(adapter, 0, sizeof(adapter_t));
4286
4287         dev_notice(&pdev->dev,
4288                 "scsi%d:Found MegaRAID controller at 0x%lx, IRQ:%d\n",
4289                 host->host_no, mega_baseport, irq);
4290
4291         adapter->base = mega_baseport;
4292         if (flag & BOARD_MEMMAP)
4293                 adapter->mmio_base = (void __iomem *) mega_baseport;
4294
4295         INIT_LIST_HEAD(&adapter->free_list);
4296         INIT_LIST_HEAD(&adapter->pending_list);
4297         INIT_LIST_HEAD(&adapter->completed_list);
4298
4299         adapter->flag = flag;
4300         spin_lock_init(&adapter->lock);
4301
4302         host->cmd_per_lun = max_cmd_per_lun;
4303         host->max_sectors = max_sectors_per_io;
4304
4305         adapter->dev = pdev;
4306         adapter->host = host;
4307
4308         adapter->host->irq = irq;
4309
4310         if (flag & BOARD_MEMMAP)
4311                 adapter->host->base = tbase;
4312         else {
4313                 adapter->host->io_port = tbase;
4314                 adapter->host->n_io_port = 16;
4315         }
4316
4317         adapter->host->unique_id = (pci_bus << 8) | pci_dev_func;
4318
4319         /*
4320          * Allocate buffer to issue internal commands.
4321          */
4322         adapter->mega_buffer = pci_alloc_consistent(adapter->dev,
4323                 MEGA_BUFFER_SIZE, &adapter->buf_dma_handle);
4324         if (!adapter->mega_buffer) {
4325                 dev_warn(&pdev->dev, "out of RAM\n");
4326                 goto out_host_put;
4327         }
4328
4329         adapter->scb_list = kmalloc(sizeof(scb_t) * MAX_COMMANDS, GFP_KERNEL);
4330         if (!adapter->scb_list) {
4331                 dev_warn(&pdev->dev, "out of RAM\n");
4332                 goto out_free_cmd_buffer;
4333         }
4334
4335         if (request_irq(irq, (adapter->flag & BOARD_MEMMAP) ?
4336                                 megaraid_isr_memmapped : megaraid_isr_iomapped,
4337                                         IRQF_SHARED, "megaraid", adapter)) {
4338                 dev_warn(&pdev->dev, "Couldn't register IRQ %d!\n", irq);
4339                 goto out_free_scb_list;
4340         }
4341
4342         if (mega_setup_mailbox(adapter))
4343                 goto out_free_irq;
4344
4345         if (mega_query_adapter(adapter))
4346                 goto out_free_mbox;
4347
4348         /*
4349          * Have checks for some buggy f/w
4350          */
4351         if ((subsysid == 0x1111) && (subsysvid == 0x1111)) {
4352                 /*
4353                  * Which firmware
4354                  */
4355                 if (!strcmp(adapter->fw_version, "3.00") ||
4356                                 !strcmp(adapter->fw_version, "3.01")) {
4357
4358                         dev_warn(&pdev->dev,
4359                                 "Your card is a Dell PERC "
4360                                 "2/SC RAID controller with "
4361                                 "firmware\nmegaraid: 3.00 or 3.01.  "
4362                                 "This driver is known to have "
4363                                 "corruption issues\nmegaraid: with "
4364                                 "those firmware versions on this "
4365                                 "specific card.  In order\nmegaraid: "
4366                                 "to protect your data, please upgrade "
4367                                 "your firmware to version\nmegaraid: "
4368                                 "3.10 or later, available from the "
4369                                 "Dell Technical Support web\n"
4370                                 "megaraid: site at\nhttp://support."
4371                                 "dell.com/us/en/filelib/download/"
4372                                 "index.asp?fileid=2940\n"
4373                         );
4374                 }
4375         }
4376
4377         /*
4378          * If we have a HP 1M(0x60E7)/2M(0x60E8) controller with
4379          * firmware H.01.07, H.01.08, and H.01.09 disable 64 bit
4380          * support, since this firmware cannot handle 64 bit
4381          * addressing
4382          */
4383         if ((subsysvid == PCI_VENDOR_ID_HP) &&
4384             ((subsysid == 0x60E7) || (subsysid == 0x60E8))) {
4385                 /*
4386                  * which firmware
4387                  */
4388                 if (!strcmp(adapter->fw_version, "H01.07") ||
4389                     !strcmp(adapter->fw_version, "H01.08") ||
4390                     !strcmp(adapter->fw_version, "H01.09") ) {
4391                         dev_warn(&pdev->dev,
4392                                 "Firmware H.01.07, "
4393                                 "H.01.08, and H.01.09 on 1M/2M "
4394                                 "controllers\n"
4395                                 "do not support 64 bit "
4396                                 "addressing.\nDISABLING "
4397                                 "64 bit support.\n");
4398                         adapter->flag &= ~BOARD_64BIT;
4399                 }
4400         }
4401
4402         if (mega_is_bios_enabled(adapter))
4403                 mega_hbas[hba_count].is_bios_enabled = 1;
4404         mega_hbas[hba_count].hostdata_addr = adapter;
4405
4406         /*
4407          * Find out which channel is raid and which is scsi. This is
4408          * for ROMB support.
4409          */
4410         mega_enum_raid_scsi(adapter);
4411
4412         /*
4413          * Find out if a logical drive is set as the boot drive. If
4414          * there is one, will make that as the first logical drive.
4415          * ROMB: Do we have to boot from a physical drive. Then all
4416          * the physical drives would appear before the logical disks.
4417          * Else, all the physical drives would be exported to the mid
4418          * layer after logical drives.
4419          */
4420         mega_get_boot_drv(adapter);
4421
4422         if (adapter->boot_pdrv_enabled) {
4423                 j = adapter->product_info.nchannels;
4424                 for( i = 0; i < j; i++ )
4425                         adapter->logdrv_chan[i] = 0;
4426                 for( i = j; i < NVIRT_CHAN + j; i++ )
4427                         adapter->logdrv_chan[i] = 1;
4428         } else {
4429                 for (i = 0; i < NVIRT_CHAN; i++)
4430                         adapter->logdrv_chan[i] = 1;
4431                 for (i = NVIRT_CHAN; i < MAX_CHANNELS+NVIRT_CHAN; i++)
4432                         adapter->logdrv_chan[i] = 0;
4433                 adapter->mega_ch_class <<= NVIRT_CHAN;
4434         }
4435
4436         /*
4437          * Do we support random deletion and addition of logical
4438          * drives
4439          */
4440         adapter->read_ldidmap = 0;      /* set it after first logdrv
4441                                                    delete cmd */
4442         adapter->support_random_del = mega_support_random_del(adapter);
4443
4444         /* Initialize SCBs */
4445         if (mega_init_scb(adapter))
4446                 goto out_free_mbox;
4447
4448         /*
4449          * Reset the pending commands counter
4450          */
4451         atomic_set(&adapter->pend_cmds, 0);
4452
4453         /*
4454          * Reset the adapter quiescent flag
4455          */
4456         atomic_set(&adapter->quiescent, 0);
4457
4458         hba_soft_state[hba_count] = adapter;
4459
4460         /*
4461          * Fill in the structure which needs to be passed back to the
4462          * application when it does an ioctl() for controller related
4463          * information.
4464          */
4465         i = hba_count;
4466
4467         mcontroller[i].base = mega_baseport;
4468         mcontroller[i].irq = irq;
4469         mcontroller[i].numldrv = adapter->numldrv;
4470         mcontroller[i].pcibus = pci_bus;
4471         mcontroller[i].pcidev = id->device;
4472         mcontroller[i].pcifun = PCI_FUNC (pci_dev_func);
4473         mcontroller[i].pciid = -1;
4474         mcontroller[i].pcivendor = id->vendor;
4475         mcontroller[i].pcislot = PCI_SLOT(pci_dev_func);
4476         mcontroller[i].uid = (pci_bus << 8) | pci_dev_func;
4477
4478
4479         /* Set the Mode of addressing to 64 bit if we can */
4480         if ((adapter->flag & BOARD_64BIT) && (sizeof(dma_addr_t) == 8)) {
4481                 pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
4482                 adapter->has_64bit_addr = 1;
4483         } else  {
4484                 pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
4485                 adapter->has_64bit_addr = 0;
4486         }
4487                 
4488         mutex_init(&adapter->int_mtx);
4489         init_completion(&adapter->int_waitq);
4490
4491         adapter->this_id = DEFAULT_INITIATOR_ID;
4492         adapter->host->this_id = DEFAULT_INITIATOR_ID;
4493
4494 #if MEGA_HAVE_CLUSTERING
4495         /*
4496          * Is cluster support enabled on this controller
4497          * Note: In a cluster the HBAs ( the initiators ) will have
4498          * different target IDs and we cannot assume it to be 7. Call
4499          * to mega_support_cluster() will get the target ids also if
4500          * the cluster support is available
4501          */
4502         adapter->has_cluster = mega_support_cluster(adapter);
4503         if (adapter->has_cluster) {
4504                 dev_notice(&pdev->dev,
4505                         "Cluster driver, initiator id:%d\n",
4506                         adapter->this_id);
4507         }
4508 #endif
4509
4510         pci_set_drvdata(pdev, host);
4511
4512         mega_create_proc_entry(hba_count, mega_proc_dir_entry);
4513
4514         error = scsi_add_host(host, &pdev->dev);
4515         if (error)
4516                 goto out_free_mbox;
4517
4518         scsi_scan_host(host);
4519         hba_count++;
4520         return 0;
4521
4522  out_free_mbox:
4523         pci_free_consistent(adapter->dev, sizeof(mbox64_t),
4524                         adapter->una_mbox64, adapter->una_mbox64_dma);
4525  out_free_irq:
4526         free_irq(adapter->host->irq, adapter);
4527  out_free_scb_list:
4528         kfree(adapter->scb_list);
4529  out_free_cmd_buffer:
4530         pci_free_consistent(adapter->dev, MEGA_BUFFER_SIZE,
4531                         adapter->mega_buffer, adapter->buf_dma_handle);
4532  out_host_put:
4533         scsi_host_put(host);
4534  out_iounmap:
4535         if (flag & BOARD_MEMMAP)
4536                 iounmap((void *)mega_baseport);
4537  out_release_region:
4538         if (flag & BOARD_MEMMAP)
4539                 release_mem_region(tbase, 128);
4540         else
4541                 release_region(mega_baseport, 16);
4542  out_disable_device:
4543         pci_disable_device(pdev);
4544  out:
4545         return error;
4546 }
4547
4548 static void
4549 __megaraid_shutdown(adapter_t *adapter)
4550 {
4551         u_char  raw_mbox[sizeof(struct mbox_out)];
4552         mbox_t  *mbox = (mbox_t *)raw_mbox;
4553         int     i;
4554
4555         /* Flush adapter cache */
4556         memset(&mbox->m_out, 0, sizeof(raw_mbox));
4557         raw_mbox[0] = FLUSH_ADAPTER;
4558
4559         free_irq(adapter->host->irq, adapter);
4560
4561         /* Issue a blocking (interrupts disabled) command to the card */
4562         issue_scb_block(adapter, raw_mbox);
4563
4564         /* Flush disks cache */
4565         memset(&mbox->m_out, 0, sizeof(raw_mbox));
4566         raw_mbox[0] = FLUSH_SYSTEM;
4567
4568         /* Issue a blocking (interrupts disabled) command to the card */
4569         issue_scb_block(adapter, raw_mbox);
4570         
4571         if (atomic_read(&adapter->pend_cmds) > 0)
4572                 dev_warn(&adapter->dev->dev, "pending commands!!\n");
4573
4574         /*
4575          * Have a delibrate delay to make sure all the caches are
4576          * actually flushed.
4577          */
4578         for (i = 0; i <= 10; i++)
4579                 mdelay(1000);
4580 }
4581
4582 static void
4583 megaraid_remove_one(struct pci_dev *pdev)
4584 {
4585         struct Scsi_Host *host = pci_get_drvdata(pdev);
4586         adapter_t *adapter = (adapter_t *)host->hostdata;
4587
4588         scsi_remove_host(host);
4589
4590         __megaraid_shutdown(adapter);
4591
4592         /* Free our resources */
4593         if (adapter->flag & BOARD_MEMMAP) {
4594                 iounmap((void *)adapter->base);
4595                 release_mem_region(adapter->host->base, 128);
4596         } else
4597                 release_region(adapter->base, 16);
4598
4599         mega_free_sgl(adapter);
4600
4601 #ifdef CONFIG_PROC_FS
4602         if (adapter->controller_proc_dir_entry) {
4603                 remove_proc_entry("stat", adapter->controller_proc_dir_entry);
4604                 remove_proc_entry("config",
4605                                 adapter->controller_proc_dir_entry);
4606                 remove_proc_entry("mailbox",
4607                                 adapter->controller_proc_dir_entry);
4608 #if MEGA_HAVE_ENH_PROC
4609                 remove_proc_entry("rebuild-rate",
4610                                 adapter->controller_proc_dir_entry);
4611                 remove_proc_entry("battery-status",
4612                                 adapter->controller_proc_dir_entry);
4613
4614                 remove_proc_entry("diskdrives-ch0",
4615                                 adapter->controller_proc_dir_entry);
4616                 remove_proc_entry("diskdrives-ch1",
4617                                 adapter->controller_proc_dir_entry);
4618                 remove_proc_entry("diskdrives-ch2",
4619                                 adapter->controller_proc_dir_entry);
4620                 remove_proc_entry("diskdrives-ch3",
4621                                 adapter->controller_proc_dir_entry);
4622
4623                 remove_proc_entry("raiddrives-0-9",
4624                                 adapter->controller_proc_dir_entry);
4625                 remove_proc_entry("raiddrives-10-19",
4626                                 adapter->controller_proc_dir_entry);
4627                 remove_proc_entry("raiddrives-20-29",
4628                                 adapter->controller_proc_dir_entry);
4629                 remove_proc_entry("raiddrives-30-39",
4630                                 adapter->controller_proc_dir_entry);
4631 #endif
4632                 {
4633                         char    buf[12] = { 0 };
4634                         sprintf(buf, "hba%d", adapter->host->host_no);
4635                         remove_proc_entry(buf, mega_proc_dir_entry);
4636                 }
4637         }
4638 #endif
4639
4640         pci_free_consistent(adapter->dev, MEGA_BUFFER_SIZE,
4641                         adapter->mega_buffer, adapter->buf_dma_handle);
4642         kfree(adapter->scb_list);
4643         pci_free_consistent(adapter->dev, sizeof(mbox64_t),
4644                         adapter->una_mbox64, adapter->una_mbox64_dma);
4645
4646         scsi_host_put(host);
4647         pci_disable_device(pdev);
4648
4649         hba_count--;
4650 }
4651
4652 static void
4653 megaraid_shutdown(struct pci_dev *pdev)
4654 {
4655         struct Scsi_Host *host = pci_get_drvdata(pdev);
4656         adapter_t *adapter = (adapter_t *)host->hostdata;
4657
4658         __megaraid_shutdown(adapter);
4659 }
4660
4661 static struct pci_device_id megaraid_pci_tbl[] = {
4662         {PCI_VENDOR_ID_AMI, PCI_DEVICE_ID_AMI_MEGARAID,
4663                 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4664         {PCI_VENDOR_ID_AMI, PCI_DEVICE_ID_AMI_MEGARAID2,
4665                 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4666         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_AMI_MEGARAID3,
4667                 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
4668         {0,}
4669 };
4670 MODULE_DEVICE_TABLE(pci, megaraid_pci_tbl);
4671
4672 static struct pci_driver megaraid_pci_driver = {
4673         .name           = "megaraid_legacy",
4674         .id_table       = megaraid_pci_tbl,
4675         .probe          = megaraid_probe_one,
4676         .remove         = megaraid_remove_one,
4677         .shutdown       = megaraid_shutdown,
4678 };
4679
4680 static int __init megaraid_init(void)
4681 {
4682         int error;
4683
4684         if ((max_cmd_per_lun <= 0) || (max_cmd_per_lun > MAX_CMD_PER_LUN))
4685                 max_cmd_per_lun = MAX_CMD_PER_LUN;
4686         if (max_mbox_busy_wait > MBOX_BUSY_WAIT)
4687                 max_mbox_busy_wait = MBOX_BUSY_WAIT;
4688
4689 #ifdef CONFIG_PROC_FS
4690         mega_proc_dir_entry = proc_mkdir("megaraid", NULL);
4691         if (!mega_proc_dir_entry) {
4692                 printk(KERN_WARNING
4693                                 "megaraid: failed to create megaraid root\n");
4694         }
4695 #endif
4696         error = pci_register_driver(&megaraid_pci_driver);
4697         if (error) {
4698 #ifdef CONFIG_PROC_FS
4699                 remove_proc_entry("megaraid", NULL);
4700 #endif
4701                 return error;
4702         }
4703
4704         /*
4705          * Register the driver as a character device, for applications
4706          * to access it for ioctls.
4707          * First argument (major) to register_chrdev implies a dynamic
4708          * major number allocation.
4709          */
4710         major = register_chrdev(0, "megadev_legacy", &megadev_fops);
4711         if (major < 0) {
4712                 printk(KERN_WARNING
4713                                 "megaraid: failed to register char device\n");
4714         }
4715
4716         return 0;
4717 }
4718
4719 static void __exit megaraid_exit(void)
4720 {
4721         /*
4722          * Unregister the character device interface to the driver.
4723          */
4724         unregister_chrdev(major, "megadev_legacy");
4725
4726         pci_unregister_driver(&megaraid_pci_driver);
4727
4728 #ifdef CONFIG_PROC_FS
4729         remove_proc_entry("megaraid", NULL);
4730 #endif
4731 }
4732
4733 module_init(megaraid_init);
4734 module_exit(megaraid_exit);
4735
4736 /* vi: set ts=8 sw=8 tw=78: */