4a58ffd7e41147d1b41b50f33ea1575af04bdae7
[linux-flexiantxendom0-3.2.10.git] / drivers / block / cciss.c
1 /*
2  *    Disk Array driver for HP SA 5xxx and 6xxx Controllers
3  *    Copyright 2000, 2002 Hewlett-Packard Development Company, L.P.
4  *
5  *    This program is free software; you can redistribute it and/or modify
6  *    it under the terms of the GNU General Public License as published by
7  *    the Free Software Foundation; either version 2 of the License, or
8  *    (at your option) any later version.
9  *
10  *    This program is distributed in the hope that it will be useful,
11  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
13  *    NON INFRINGEMENT.  See the GNU General Public License for more details.
14  *
15  *    You should have received a copy of the GNU General Public License
16  *    along with this program; if not, write to the Free Software
17  *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  *    Questions/Comments/Bugfixes to Cciss-discuss@lists.sourceforge.net
20  *
21  */
22
23 #include <linux/config.h>       /* CONFIG_PROC_FS */
24 #include <linux/module.h>
25 #include <linux/interrupt.h>
26 #include <linux/version.h>
27 #include <linux/types.h>
28 #include <linux/pci.h>
29 #include <linux/kernel.h>
30 #include <linux/slab.h>
31 #include <linux/delay.h>
32 #include <linux/major.h>
33 #include <linux/fs.h>
34 #include <linux/bio.h>
35 #include <linux/blkpg.h>
36 #include <linux/timer.h>
37 #include <linux/proc_fs.h>
38 #include <linux/init.h> 
39 #include <linux/hdreg.h>
40 #include <linux/spinlock.h>
41 #include <asm/uaccess.h>
42 #include <asm/io.h>
43
44 #include <linux/blkdev.h>
45 #include <linux/genhd.h>
46 #include <linux/completion.h>
47
48 #define CCISS_DRIVER_VERSION(maj,min,submin) ((maj<<16)|(min<<8)|(submin))
49 #define DRIVER_NAME "Compaq CISS Driver (v 2.5.0)"
50 #define DRIVER_VERSION CCISS_DRIVER_VERSION(2,5,0)
51
52 /* Embedded module documentation macros - see modules.h */
53 MODULE_AUTHOR("Charles M. White III - Compaq Computer Corporation");
54 MODULE_DESCRIPTION("Driver for Compaq Smart Array Controller 5xxx v. 2.5.0");
55 MODULE_LICENSE("GPL");
56
57 #include "cciss_cmd.h"
58 #include "cciss.h"
59 #include <linux/cciss_ioctl.h>
60
61 /* define the PCI info for the cards we can control */
62 const struct pci_device_id cciss_pci_device_id[] = {
63         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISS,
64                         0x0E11, 0x4070, 0, 0, 0},
65         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB,
66                         0x0E11, 0x4080, 0, 0, 0},
67         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB,
68                         0x0E11, 0x4082, 0, 0, 0},
69         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB,
70                         0x0E11, 0x4083, 0, 0, 0},
71         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
72                 0x0E11, 0x409A, 0, 0, 0},
73         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
74                 0x0E11, 0x409B, 0, 0, 0},
75         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
76                 0x0E11, 0x409C, 0, 0, 0},
77         { PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
78                 0x0E11, 0x409D, 0, 0, 0},
79         {0,}
80 };
81 MODULE_DEVICE_TABLE(pci, cciss_pci_device_id);
82
83 #define NR_PRODUCTS (sizeof(products)/sizeof(struct board_type))
84
85 /*  board_id = Subsystem Device ID & Vendor ID
86  *  product = Marketing Name for the board
87  *  access = Address of the struct of function pointers 
88  */
89 static struct board_type products[] = {
90         { 0x40700E11, "Smart Array 5300", &SA5_access },
91         { 0x40800E11, "Smart Array 5i", &SA5B_access},
92         { 0x40820E11, "Smart Array 532", &SA5B_access},
93         { 0x40830E11, "Smart Array 5312", &SA5B_access},
94         { 0x409A0E11, "Smart Array 641", &SA5_access},
95         { 0x409B0E11, "Smart Array 642", &SA5_access},
96         { 0x409C0E11, "Smart Array 6400", &SA5_access},
97         { 0x409D0E11, "Smart Array 6400 EM", &SA5_access},
98 };
99
100 /* How long to wait (in millesconds) for board to go into simple mode */
101 #define MAX_CONFIG_WAIT 30000 
102 #define MAX_IOCTL_CONFIG_WAIT 1000
103
104 /*define how many times we will try a command because of bus resets */
105 #define MAX_CMD_RETRIES 3
106
107 #define READ_AHEAD       128
108 #define NR_CMDS          384 /* #commands that can be outstanding */
109 #define MAX_CTLR 8
110
111 #define CCISS_DMA_MASK  0xFFFFFFFF      /* 32 bit DMA */
112
113 static ctlr_info_t *hba[MAX_CTLR];
114
115 static struct proc_dir_entry *proc_cciss;
116
117 static void do_cciss_request(request_queue_t *q);
118 static int cciss_open(struct inode *inode, struct file *filep);
119 static int cciss_release(struct inode *inode, struct file *filep);
120 static int cciss_ioctl(struct inode *inode, struct file *filep, 
121                 unsigned int cmd, unsigned long arg);
122
123 static int revalidate_allvol(kdev_t dev);
124 static int cciss_revalidate(struct gendisk *disk);
125 static int deregister_disk(int ctlr, int logvol);
126 static int register_new_disk(int cltr);
127
128 static void cciss_getgeometry(int cntl_num);
129
130 static inline void addQ(CommandList_struct **Qptr, CommandList_struct *c);
131 static void start_io( ctlr_info_t *h);
132 static int sendcmd( __u8 cmd, int ctlr, void *buff, size_t size,
133         unsigned int use_unit_num, unsigned int log_unit, __u8 page_code,
134         unsigned char *scsi3addr, int cmd_type);
135
136 #ifdef CONFIG_PROC_FS
137 static int cciss_proc_get_info(char *buffer, char **start, off_t offset, 
138                 int length, int *eof, void *data);
139 static void cciss_procinit(int i);
140 #else
141 static int cciss_proc_get_info(char *buffer, char **start, off_t offset, 
142                 int length, int *eof, void *data) { return 0;}
143 static void cciss_procinit(int i) {}
144 #endif /* CONFIG_PROC_FS */
145
146 static struct block_device_operations cciss_fops  = {
147         .owner          = THIS_MODULE,
148         .open           = cciss_open, 
149         .release        = cciss_release,
150         .ioctl          = cciss_ioctl,
151         .revalidate_disk= cciss_revalidate,
152 };
153
154 #include "cciss_scsi.c"         /* For SCSI tape support */
155
156 /*
157  * Report information about this controller.
158  */
159 #ifdef CONFIG_PROC_FS
160 static int cciss_proc_get_info(char *buffer, char **start, off_t offset, 
161                 int length, int *eof, void *data)
162 {
163         off_t pos = 0;
164         off_t len = 0;
165         int size, i, ctlr;
166         ctlr_info_t *h = (ctlr_info_t*)data;
167         drive_info_struct *drv;
168
169         ctlr = h->ctlr;
170         size = sprintf(buffer, "%s:  Compaq %s Controller\n"
171                 "       Board ID: 0x%08lx\n"
172                 "       Firmware Version: %c%c%c%c\n"
173                 "       Memory Address: 0x%08lx\n"
174                 "       IRQ: %d\n"
175                 "       Logical drives: %d\n"
176                 "       Highest Logical Volume ID: %d\n"
177                 "       Current Q depth: %d\n"
178                 "       Max Q depth since init: %d\n"
179                 "       Max # commands on controller since init: %d\n"
180                 "       Max SG entries since init: %d\n\n",
181                 h->devname,
182                 h->product_name,
183                 (unsigned long)h->board_id,
184                 h->firm_ver[0], h->firm_ver[1], h->firm_ver[2], h->firm_ver[3],
185                 (unsigned long)h->vaddr,
186                 (unsigned int)h->intr,
187                 h->num_luns, 
188                 h->highest_lun, 
189                 h->Qdepth, h->maxQsinceinit, h->max_outstanding, h->maxSG);
190
191         pos += size; len += size;
192         cciss_proc_tape_report(ctlr, buffer, &pos, &len);
193         for(i=0; i<h->highest_lun; i++) {
194                 drv = &h->drv[i];
195                 if (drv->block_size == 0)
196                         continue;
197                 size = sprintf(buffer+len, "cciss/c%dd%d: blksz=%d nr_blocks=%llu\n",
198                                 ctlr, i, drv->block_size, (unsigned long long)drv->nr_blocks);
199                 pos += size; len += size;
200         }
201
202         size = sprintf(buffer+len, "nr_allocs = %d\nnr_frees = %d\n",
203                         h->nr_allocs, h->nr_frees);
204         pos += size; len += size;
205
206         *eof = 1;
207         *start = buffer+offset;
208         len -= offset;
209         if (len>length)
210                 len = length;
211         return len;
212 }
213
214 static int 
215 cciss_proc_write(struct file *file, const char *buffer, 
216                         unsigned long count, void *data)
217 {
218         unsigned char cmd[80];
219         int len;
220 #ifdef CONFIG_CISS_SCSI_TAPE
221         ctlr_info_t *h = (ctlr_info_t *) data;
222         int rc;
223 #endif
224
225         if (count > sizeof(cmd)-1) return -EINVAL;
226         if (copy_from_user(cmd, buffer, count)) return -EFAULT;
227         cmd[count] = '\0';
228         len = strlen(cmd);      // above 3 lines ensure safety
229         if (cmd[len-1] == '\n') 
230                 cmd[--len] = '\0';
231 #       ifdef CONFIG_CISS_SCSI_TAPE
232                 if (strcmp("engage scsi", cmd)==0) {
233                         rc = cciss_engage_scsi(h->ctlr);
234                         if (rc != 0) return -rc;
235                         return count;
236                 }
237                 /* might be nice to have "disengage" too, but it's not 
238                    safely possible. (only 1 module use count, lock issues.) */
239 #       endif
240         return -EINVAL;
241 }
242
243 /*
244  * Get us a file in /proc/cciss that says something about each controller.
245  * Create /proc/cciss if it doesn't exist yet.
246  */
247 static void __init cciss_procinit(int i)
248 {
249         struct proc_dir_entry *pde;
250
251         if (proc_cciss == NULL) {
252                 proc_cciss = proc_mkdir("cciss", proc_root_driver);
253                 if (!proc_cciss) 
254                         return;
255         }
256
257         pde = create_proc_read_entry(hba[i]->devname, 
258                 S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH, 
259                 proc_cciss, cciss_proc_get_info, hba[i]);
260         pde->write_proc = cciss_proc_write;
261 }
262 #endif /* CONFIG_PROC_FS */
263
264 /* 
265  * For operations that cannot sleep, a command block is allocated at init, 
266  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
267  * which ones are free or in use.  For operations that can wait for kmalloc 
268  * to possible sleep, this routine can be called with get_from_pool set to 0. 
269  * cmd_free() MUST be called with a got_from_pool set to 0 if cmd_alloc was. 
270  */ 
271 static CommandList_struct * cmd_alloc(ctlr_info_t *h, int get_from_pool)
272 {
273         CommandList_struct *c;
274         int i; 
275         u64bit temp64;
276         dma_addr_t cmd_dma_handle, err_dma_handle;
277
278         if (!get_from_pool)
279         {
280                 c = (CommandList_struct *) pci_alloc_consistent(
281                         h->pdev, sizeof(CommandList_struct), &cmd_dma_handle); 
282                 if(c==NULL)
283                         return NULL;
284                 memset(c, 0, sizeof(CommandList_struct));
285
286                 c->err_info = (ErrorInfo_struct *)pci_alloc_consistent(
287                                         h->pdev, sizeof(ErrorInfo_struct), 
288                                         &err_dma_handle);
289         
290                 if (c->err_info == NULL)
291                 {
292                         pci_free_consistent(h->pdev, 
293                                 sizeof(CommandList_struct), c, cmd_dma_handle);
294                         return NULL;
295                 }
296                 memset(c->err_info, 0, sizeof(ErrorInfo_struct));
297         } else /* get it out of the controllers pool */ 
298         {
299                 do {
300                         i = find_first_zero_bit(h->cmd_pool_bits, NR_CMDS);
301                         if (i == NR_CMDS)
302                                 return NULL;
303                 } while(test_and_set_bit(i & (BITS_PER_LONG - 1), h->cmd_pool_bits+(i/BITS_PER_LONG)) != 0);
304 #ifdef CCISS_DEBUG
305                 printk(KERN_DEBUG "cciss: using command buffer %d\n", i);
306 #endif
307                 c = h->cmd_pool + i;
308                 memset(c, 0, sizeof(CommandList_struct));
309                 cmd_dma_handle = h->cmd_pool_dhandle 
310                                         + i*sizeof(CommandList_struct);
311                 c->err_info = h->errinfo_pool + i;
312                 memset(c->err_info, 0, sizeof(ErrorInfo_struct));
313                 err_dma_handle = h->errinfo_pool_dhandle 
314                                         + i*sizeof(ErrorInfo_struct);
315                 h->nr_allocs++;
316         }
317
318         c->busaddr = (__u32) cmd_dma_handle;
319         temp64.val = (__u64) err_dma_handle;    
320         c->ErrDesc.Addr.lower = temp64.val32.lower;
321         c->ErrDesc.Addr.upper = temp64.val32.upper;
322         c->ErrDesc.Len = sizeof(ErrorInfo_struct);
323         
324         c->ctlr = h->ctlr;
325         return c;
326
327
328 }
329
330 /* 
331  * Frees a command block that was previously allocated with cmd_alloc(). 
332  */
333 static void cmd_free(ctlr_info_t *h, CommandList_struct *c, int got_from_pool)
334 {
335         int i;
336         u64bit temp64;
337
338         if( !got_from_pool)
339         { 
340                 temp64.val32.lower = c->ErrDesc.Addr.lower;
341                 temp64.val32.upper = c->ErrDesc.Addr.upper;
342                 pci_free_consistent(h->pdev, sizeof(ErrorInfo_struct), 
343                         c->err_info, (dma_addr_t) temp64.val);
344                 pci_free_consistent(h->pdev, sizeof(CommandList_struct), 
345                         c, (dma_addr_t) c->busaddr);
346         } else 
347         {
348                 i = c - h->cmd_pool;
349                 clear_bit(i&(BITS_PER_LONG-1), h->cmd_pool_bits+(i/BITS_PER_LONG));
350                 h->nr_frees++;
351         }
352 }
353
354 /*
355  * Open.  Make sure the device is really there.
356  */
357 static int cciss_open(struct inode *inode, struct file *filep)
358 {
359         int ctlr = major(inode->i_rdev) - COMPAQ_CISS_MAJOR;
360         int dsk  = minor(inode->i_rdev) >> NWD_SHIFT;
361
362 #ifdef CCISS_DEBUG
363         printk(KERN_DEBUG "cciss_open %x (%x:%x)\n", inode->i_rdev, ctlr, dsk);
364 #endif /* CCISS_DEBUG */ 
365
366         if (ctlr >= MAX_CTLR || hba[ctlr] == NULL)
367                 return -ENXIO;
368         /*
369          * Root is allowed to open raw volume zero even if it's not configured
370          * so array config can still work.  I don't think I really like this,
371          * but I'm already using way to many device nodes to claim another one
372          * for "raw controller".
373          */
374         if (hba[ctlr]->drv[dsk].nr_blocks == 0) {
375                 if (minor(inode->i_rdev) != 0)
376                         return -ENXIO;
377                 if (!capable(CAP_SYS_ADMIN))
378                         return -EPERM;
379         }
380         hba[ctlr]->drv[dsk].usage_count++;
381         hba[ctlr]->usage_count++;
382         return 0;
383 }
384 /*
385  * Close.  Sync first.
386  */
387 static int cciss_release(struct inode *inode, struct file *filep)
388 {
389         int ctlr = major(inode->i_rdev) - COMPAQ_CISS_MAJOR;
390         int dsk  = minor(inode->i_rdev) >> NWD_SHIFT;
391
392 #ifdef CCISS_DEBUG
393         printk(KERN_DEBUG "cciss_release %x (%x:%x)\n", inode->i_rdev, ctlr, dsk);
394 #endif /* CCISS_DEBUG */
395
396         /* fsync_dev(inode->i_rdev); */
397
398         hba[ctlr]->drv[dsk].usage_count--;
399         hba[ctlr]->usage_count--;
400         return 0;
401 }
402
403 /*
404  * ioctl 
405  */
406 static int cciss_ioctl(struct inode *inode, struct file *filep, 
407                 unsigned int cmd, unsigned long arg)
408 {
409         int ctlr = major(inode->i_rdev) - COMPAQ_CISS_MAJOR;
410         int dsk  = minor(inode->i_rdev) >> NWD_SHIFT;
411
412 #ifdef CCISS_DEBUG
413         printk(KERN_DEBUG "cciss_ioctl: Called with cmd=%x %lx\n", cmd, arg);
414 #endif /* CCISS_DEBUG */ 
415         
416         switch(cmd) {
417         case HDIO_GETGEO:
418         {
419                 struct hd_geometry driver_geo;
420                 if (hba[ctlr]->drv[dsk].cylinders) {
421                         driver_geo.heads = hba[ctlr]->drv[dsk].heads;
422                         driver_geo.sectors = hba[ctlr]->drv[dsk].sectors;
423                         driver_geo.cylinders = hba[ctlr]->drv[dsk].cylinders;
424                 } else {
425                         driver_geo.heads = 0xff;
426                         driver_geo.sectors = 0x3f;
427                         driver_geo.cylinders = (int)hba[ctlr]->drv[dsk].nr_blocks / (0xff*0x3f);
428                 }
429                 driver_geo.start= get_start_sect(inode->i_bdev);
430                 if (copy_to_user((void *) arg, &driver_geo,
431                                 sizeof( struct hd_geometry)))
432                         return  -EFAULT;
433                 return(0);
434         }
435
436         case CCISS_GETPCIINFO:
437         {
438                 cciss_pci_info_struct pciinfo;
439
440                 if (!arg) return -EINVAL;
441                 pciinfo.bus = hba[ctlr]->pdev->bus->number;
442                 pciinfo.dev_fn = hba[ctlr]->pdev->devfn;
443                 pciinfo.board_id = hba[ctlr]->board_id;
444                 if (copy_to_user((void *) arg, &pciinfo,  sizeof( cciss_pci_info_struct )))
445                         return  -EFAULT;
446                 return(0);
447         }       
448         case CCISS_GETINTINFO:
449         {
450                 cciss_coalint_struct intinfo;
451                 ctlr_info_t *c = hba[ctlr];
452
453                 if (!arg) return -EINVAL;
454                 intinfo.delay = readl(&c->cfgtable->HostWrite.CoalIntDelay);
455                 intinfo.count = readl(&c->cfgtable->HostWrite.CoalIntCount);
456                 if (copy_to_user((void *) arg, &intinfo, sizeof( cciss_coalint_struct )))
457                         return -EFAULT;
458                 return(0);
459         }
460         case CCISS_SETINTINFO:
461         {
462                 cciss_coalint_struct intinfo;
463                 ctlr_info_t *c = hba[ctlr];
464                 unsigned long flags;
465                 int i;
466
467                 if (!arg) return -EINVAL;       
468                 if (!capable(CAP_SYS_ADMIN)) return -EPERM;
469                 if (copy_from_user(&intinfo, (void *) arg, sizeof( cciss_coalint_struct)))
470                         return -EFAULT;
471                 if ( (intinfo.delay == 0 ) && (intinfo.count == 0))
472
473                 {
474 //                      printk("cciss_ioctl: delay and count cannot be 0\n");
475                         return( -EINVAL);
476                 }
477                 spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
478                 /* Update the field, and then ring the doorbell */ 
479                 writel( intinfo.delay, 
480                         &(c->cfgtable->HostWrite.CoalIntDelay));
481                 writel( intinfo.count, 
482                         &(c->cfgtable->HostWrite.CoalIntCount));
483                 writel( CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
484
485                 for(i=0;i<MAX_IOCTL_CONFIG_WAIT;i++) {
486                         if (!(readl(c->vaddr + SA5_DOORBELL) 
487                                         & CFGTBL_ChangeReq))
488                                 break;
489                         /* delay and try again */
490                         udelay(1000);
491                 }       
492                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
493                 if (i >= MAX_IOCTL_CONFIG_WAIT)
494                         return -EAGAIN;
495                 return(0);
496         }
497         case CCISS_GETNODENAME:
498         {
499                 NodeName_type NodeName;
500                 ctlr_info_t *c = hba[ctlr];
501                 int i; 
502
503                 if (!arg) return -EINVAL;
504                 for(i=0;i<16;i++)
505                         NodeName[i] = readb(&c->cfgtable->ServerName[i]);
506                 if (copy_to_user((void *) arg, NodeName, sizeof( NodeName_type)))
507                         return  -EFAULT;
508                 return(0);
509         }
510         case CCISS_SETNODENAME:
511         {
512                 NodeName_type NodeName;
513                 ctlr_info_t *c = hba[ctlr];
514                 unsigned long flags;
515                 int i;
516
517                 if (!arg) return -EINVAL;
518                 if (!capable(CAP_SYS_ADMIN)) return -EPERM;
519                 
520                 if (copy_from_user(NodeName, (void *) arg, sizeof( NodeName_type)))
521                         return -EFAULT;
522
523                 spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
524
525                         /* Update the field, and then ring the doorbell */ 
526                 for(i=0;i<16;i++)
527                         writeb( NodeName[i], &c->cfgtable->ServerName[i]);
528                         
529                 writel( CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
530
531                 for(i=0;i<MAX_IOCTL_CONFIG_WAIT;i++) {
532                         if (!(readl(c->vaddr + SA5_DOORBELL) 
533                                         & CFGTBL_ChangeReq))
534                                 break;
535                         /* delay and try again */
536                         udelay(1000);
537                 }       
538                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
539                 if (i >= MAX_IOCTL_CONFIG_WAIT)
540                         return -EAGAIN;
541                 return(0);
542         }
543
544         case CCISS_GETHEARTBEAT:
545         {
546                 Heartbeat_type heartbeat;
547                 ctlr_info_t *c = hba[ctlr];
548
549                 if (!arg) return -EINVAL;
550                 heartbeat = readl(&c->cfgtable->HeartBeat);
551                 if (copy_to_user((void *) arg, &heartbeat, sizeof( Heartbeat_type)))
552                         return -EFAULT;
553                 return(0);
554         }
555         case CCISS_GETBUSTYPES:
556         {
557                 BusTypes_type BusTypes;
558                 ctlr_info_t *c = hba[ctlr];
559
560                 if (!arg) return -EINVAL;
561                 BusTypes = readl(&c->cfgtable->BusTypes);
562                 if (copy_to_user((void *) arg, &BusTypes, sizeof( BusTypes_type) ))
563                         return  -EFAULT;
564                 return(0);
565         }
566         case CCISS_GETFIRMVER:
567         {
568                 FirmwareVer_type firmware;
569
570                 if (!arg) return -EINVAL;
571                 memcpy(firmware, hba[ctlr]->firm_ver, 4);
572
573                 if (copy_to_user((void *) arg, firmware, sizeof( FirmwareVer_type)))
574                         return -EFAULT;
575                 return(0);
576         }
577         case CCISS_GETDRIVVER:
578         {
579                 DriverVer_type DriverVer = DRIVER_VERSION;
580
581                 if (!arg) return -EINVAL;
582
583                 if (copy_to_user((void *) arg, &DriverVer, sizeof( DriverVer_type) ))
584                         return -EFAULT;
585                 return(0);
586         }
587
588         case CCISS_REVALIDVOLS:
589                 return( revalidate_allvol(inode->i_rdev));
590
591         case CCISS_GETLUNINFO: {
592                 LogvolInfo_struct luninfo;
593                 struct gendisk *disk = hba[ctlr]->gendisk[dsk];
594                 drive_info_struct *drv = &hba[ctlr]->drv[dsk];
595                 int i;
596                 
597                 luninfo.LunID = drv->LunID;
598                 luninfo.num_opens = drv->usage_count;
599                 luninfo.num_parts = 0;
600                 /* count partitions 1 to 15 with sizes > 0 */
601                 for(i=1; i <MAX_PART; i++) {
602                         if (!disk->part[i])
603                                 continue;
604                         if (disk->part[i]->nr_sects != 0)
605                                 luninfo.num_parts++;
606                 }
607                 if (copy_to_user((void *) arg, &luninfo,
608                                 sizeof(LogvolInfo_struct)))
609                         return -EFAULT;
610                 return(0);
611         }
612         case CCISS_DEREGDISK:
613                 return( deregister_disk(ctlr,dsk));
614
615         case CCISS_REGNEWD:
616         {
617                 return(register_new_disk(ctlr));
618         }       
619         case CCISS_PASSTHRU:
620         {
621                 IOCTL_Command_struct iocommand;
622                 ctlr_info_t *h = hba[ctlr];
623                 CommandList_struct *c;
624                 char    *buff = NULL;
625                 u64bit  temp64;
626                 unsigned long flags;
627                 DECLARE_COMPLETION(wait);
628
629                 if (!arg) return -EINVAL;
630         
631                 if (!capable(CAP_SYS_RAWIO)) return -EPERM;
632
633                 if (copy_from_user(&iocommand, (void *) arg, sizeof( IOCTL_Command_struct) ))
634                         return -EFAULT;
635                 if((iocommand.buf_size < 1) && 
636                                 (iocommand.Request.Type.Direction != XFER_NONE))
637                 {       
638                         return -EINVAL;
639                 } 
640                 /* Check kmalloc limits */
641                 if(iocommand.buf_size > 128000)
642                         return -EINVAL;
643                 if(iocommand.buf_size > 0)
644                 {
645                         buff =  kmalloc(iocommand.buf_size, GFP_KERNEL);
646                         if( buff == NULL) 
647                                 return -EFAULT;
648                 }
649                 if (iocommand.Request.Type.Direction == XFER_WRITE)
650                 {
651                         /* Copy the data into the buffer we created */ 
652                         if (copy_from_user(buff, iocommand.buf, iocommand.buf_size))
653                         {
654                                 kfree(buff);
655                                 return -EFAULT;
656                         }
657                 }
658                 if ((c = cmd_alloc(h , 0)) == NULL)
659                 {
660                         kfree(buff);
661                         return -ENOMEM;
662                 }
663                         // Fill in the command type 
664                 c->cmd_type = CMD_IOCTL_PEND;
665                         // Fill in Command Header 
666                 c->Header.ReplyQueue = 0;  // unused in simple mode
667                 if( iocommand.buf_size > 0)     // buffer to fill 
668                 {
669                         c->Header.SGList = 1;
670                         c->Header.SGTotal= 1;
671                 } else  // no buffers to fill  
672                 {
673                         c->Header.SGList = 0;
674                         c->Header.SGTotal= 0;
675                 }
676                 c->Header.LUN = iocommand.LUN_info;
677                 c->Header.Tag.lower = c->busaddr;  // use the kernel address the cmd block for tag
678                 
679                 // Fill in Request block 
680                 c->Request = iocommand.Request; 
681         
682                 // Fill in the scatter gather information
683                 if (iocommand.buf_size > 0 ) 
684                 {
685                         temp64.val = pci_map_single( h->pdev, buff,
686                                         iocommand.buf_size, 
687                                 PCI_DMA_BIDIRECTIONAL); 
688                         c->SG[0].Addr.lower = temp64.val32.lower;
689                         c->SG[0].Addr.upper = temp64.val32.upper;
690                         c->SG[0].Len = iocommand.buf_size;
691                         c->SG[0].Ext = 0;  // we are not chaining
692                 }
693                 c->waiting = &wait;
694
695                 /* Put the request on the tail of the request queue */
696                 spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
697                 addQ(&h->reqQ, c);
698                 h->Qdepth++;
699                 start_io(h);
700                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
701
702                 wait_for_completion(&wait);
703
704                 /* unlock the buffers from DMA */
705                 temp64.val32.lower = c->SG[0].Addr.lower;
706                 temp64.val32.upper = c->SG[0].Addr.upper;
707                 pci_unmap_single( h->pdev, (dma_addr_t) temp64.val,
708                         iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
709
710                 /* Copy the error information out */ 
711                 iocommand.error_info = *(c->err_info);
712                 if ( copy_to_user((void *) arg, &iocommand, sizeof( IOCTL_Command_struct) ) )
713                 {
714                         kfree(buff);
715                         cmd_free(h, c, 0);
716                         return( -EFAULT);       
717                 }       
718
719                 if (iocommand.Request.Type.Direction == XFER_READ)
720                 {
721                         /* Copy the data out of the buffer we created */
722                         if (copy_to_user(iocommand.buf, buff, iocommand.buf_size))
723                         {
724                                 kfree(buff);
725                                 cmd_free(h, c, 0);
726                                 return -EFAULT;
727                         }
728                 }
729                 kfree(buff);
730                 cmd_free(h, c, 0);
731                 return(0);
732         } 
733         case CCISS_BIG_PASSTHRU: {
734                 BIG_IOCTL_Command_struct *ioc;
735                 ctlr_info_t *h = hba[ctlr];
736                 CommandList_struct *c;
737                 unsigned char **buff = NULL;
738                 int     *buff_size = NULL;
739                 u64bit  temp64;
740                 unsigned long flags;
741                 BYTE sg_used = 0;
742                 int status = 0;
743                 int i;
744                 DECLARE_COMPLETION(wait);
745                 __u32   left;
746                 __u32   sz;
747                 BYTE    *data_ptr;
748
749                 if (!arg)
750                         return -EINVAL;
751                 if (!capable(CAP_SYS_RAWIO))
752                         return -EPERM;
753                 ioc = (BIG_IOCTL_Command_struct *) 
754                         kmalloc(sizeof(*ioc), GFP_KERNEL);
755                 if (!ioc) {
756                         status = -ENOMEM;
757                         goto cleanup1;
758                 }
759                 if (copy_from_user(ioc, (void *) arg, sizeof(*ioc)))
760                         return -EFAULT;
761                 if ((ioc->buf_size < 1) &&
762                         (ioc->Request.Type.Direction != XFER_NONE))
763                                 return -EINVAL;
764                 /* Check kmalloc limits  using all SGs */
765                 if (ioc->malloc_size > MAX_KMALLOC_SIZE)
766                         return -EINVAL;
767                 if (ioc->buf_size > ioc->malloc_size * MAXSGENTRIES)
768                         return -EINVAL;
769                 buff = (unsigned char **) kmalloc(MAXSGENTRIES * 
770                                 sizeof(char *), GFP_KERNEL);
771                 if (!buff) {
772                         status = -ENOMEM;
773                         goto cleanup1;
774                 }
775                 memset(buff, 0, MAXSGENTRIES);
776                 buff_size = (int *) kmalloc(MAXSGENTRIES * sizeof(int), 
777                                         GFP_KERNEL);
778                 if (!buff_size) {
779                         status = -ENOMEM;
780                         goto cleanup1;
781                 }
782                 left = ioc->buf_size;
783                 data_ptr = (BYTE *) ioc->buf;
784                 while (left) {
785                         sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
786                         buff_size[sg_used] = sz;
787                         buff[sg_used] = kmalloc(sz, GFP_KERNEL);
788                         if (buff[sg_used] == NULL) {
789                                 status = -ENOMEM;
790                                 goto cleanup1;
791                         }
792                         if (ioc->Request.Type.Direction == XFER_WRITE &&
793                                 copy_from_user(buff[sg_used], data_ptr, sz)) {
794                                         status = -ENOMEM;
795                                         goto cleanup1;                  
796                         }
797                         left -= sz;
798                         data_ptr += sz;
799                         sg_used++;
800                 }
801                 if ((c = cmd_alloc(h , 0)) == NULL) {
802                         status = -ENOMEM;
803                         goto cleanup1;  
804                 }
805                 c->cmd_type = CMD_IOCTL_PEND;
806                 c->Header.ReplyQueue = 0;
807                 
808                 if( ioc->buf_size > 0) {
809                         c->Header.SGList = sg_used;
810                         c->Header.SGTotal= sg_used;
811                 } else { 
812                         c->Header.SGList = 0;
813                         c->Header.SGTotal= 0;
814                 }
815                 c->Header.LUN = ioc->LUN_info;
816                 c->Header.Tag.lower = c->busaddr;
817                 
818                 c->Request = ioc->Request;
819                 if (ioc->buf_size > 0 ) {
820                         int i;
821                         for(i=0; i<sg_used; i++) {
822                                 temp64.val = pci_map_single( h->pdev, buff[i],
823                                         buff_size[i],
824                                         PCI_DMA_BIDIRECTIONAL);
825                                 c->SG[i].Addr.lower = temp64.val32.lower;
826                                 c->SG[i].Addr.upper = temp64.val32.upper;
827                                 c->SG[i].Len = buff_size[i];
828                                 c->SG[i].Ext = 0;  /* we are not chaining */
829                         }
830                 }
831                 c->waiting = &wait;
832                 /* Put the request on the tail of the request queue */
833                 spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
834                 addQ(&h->reqQ, c);
835                 h->Qdepth++;
836                 start_io(h);
837                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
838                 wait_for_completion(&wait);
839                 /* unlock the buffers from DMA */
840                 for(i=0; i<sg_used; i++) {
841                         temp64.val32.lower = c->SG[i].Addr.lower;
842                         temp64.val32.upper = c->SG[i].Addr.upper;
843                         pci_unmap_single( h->pdev, (dma_addr_t) temp64.val,
844                                 buff_size[i], PCI_DMA_BIDIRECTIONAL);
845                 }
846                 /* Copy the error information out */
847                 ioc->error_info = *(c->err_info);
848                 if (copy_to_user((void *) arg, ioc, sizeof(*ioc))) {
849                         cmd_free(h, c, 0);
850                         status = -EFAULT;
851                         goto cleanup1;
852                 }
853                 if (ioc->Request.Type.Direction == XFER_READ) {
854                         /* Copy the data out of the buffer we created */
855                         BYTE *ptr = (BYTE  *) ioc->buf;
856                         for(i=0; i< sg_used; i++) {
857                                 if (copy_to_user(ptr, buff[i], buff_size[i])) {
858                                         cmd_free(h, c, 0);
859                                         status = -EFAULT;
860                                         goto cleanup1;
861                                 }
862                                 ptr += buff_size[i];
863                         }
864                 }
865                 cmd_free(h, c, 0);
866                 status = 0;
867 cleanup1:
868                 if (buff) {
869                         for(i=0; i<sg_used; i++)
870                                 if(buff[i] != NULL)
871                                         kfree(buff[i]);
872                         kfree(buff);
873                 }
874                 if (buff_size)
875                         kfree(buff_size);
876                 if (ioc)
877                         kfree(ioc);
878                 return(status);
879         }
880         default:
881                 return -EBADRQC;
882         }
883         
884 }
885
886 static int cciss_revalidate(struct gendisk *disk)
887 {
888         drive_info_struct *drv = disk->private_data;
889         set_capacity(disk, drv->nr_blocks);
890         return 0;
891 }
892
893 /*
894  * revalidate_allvol is for online array config utilities.  After a
895  * utility reconfigures the drives in the array, it can use this function
896  * (through an ioctl) to make the driver zap any previous disk structs for
897  * that controller and get new ones.
898  *
899  * Right now I'm using the getgeometry() function to do this, but this
900  * function should probably be finer grained and allow you to revalidate one
901  * particualar logical volume (instead of all of them on a particular
902  * controller).
903  */
904 static int revalidate_allvol(kdev_t dev)
905 {
906         int ctlr, i;
907         unsigned long flags;
908
909         ctlr = major(dev) - COMPAQ_CISS_MAJOR;
910         if (minor(dev) != 0)
911                 return -ENXIO;
912
913         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
914         if (hba[ctlr]->usage_count > 1) {
915                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
916                 printk(KERN_WARNING "cciss: Device busy for volume"
917                         " revalidation (usage=%d)\n", hba[ctlr]->usage_count);
918                 return -EBUSY;
919         }
920         hba[ctlr]->usage_count++;
921         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
922
923         for(i=0; i< NWD; i++) {
924                 struct gendisk *disk = hba[ctlr]->gendisk[i];
925                 if (disk->flags & GENHD_FL_UP)
926                         del_gendisk(disk);
927         }
928
929         /*
930          * Set the partition and block size structures for all volumes
931          * on this controller to zero.  We will reread all of this data
932          */
933         memset(hba[ctlr]->drv,        0, sizeof(drive_info_struct)
934                                                 * CISS_MAX_LUN);
935         /*
936          * Tell the array controller not to give us any interrupts while
937          * we check the new geometry.  Then turn interrupts back on when
938          * we're done.
939          */
940         hba[ctlr]->access.set_intr_mask(hba[ctlr], CCISS_INTR_OFF);
941         cciss_getgeometry(ctlr);
942         hba[ctlr]->access.set_intr_mask(hba[ctlr], CCISS_INTR_ON);
943
944         /* Loop through each real device */ 
945         for (i = 0; i < NWD; i++) {
946                 struct gendisk *disk = hba[ctlr]->gendisk[i];
947                 drive_info_struct *drv = &(hba[ctlr]->drv[i]);
948                 if (!drv->nr_blocks)
949                         continue;
950                 hba[ctlr]->queue.hardsect_size = drv->block_size;
951                 set_capacity(disk, drv->nr_blocks);
952                 add_disk(disk);
953         }
954         hba[ctlr]->usage_count--;
955         return 0;
956 }
957
958 static int deregister_disk(int ctlr, int logvol)
959 {
960         unsigned long flags;
961         struct gendisk *disk = hba[ctlr]->gendisk[logvol];
962         ctlr_info_t  *h = hba[ctlr];
963
964         if (!capable(CAP_SYS_RAWIO))
965                 return -EPERM;
966
967         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
968         /* make sure logical volume is NOT is use */
969         if( h->drv[logvol].usage_count > 1) {
970                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
971                 return -EBUSY;
972         }
973         h->drv[logvol].usage_count++;
974         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
975
976         /* invalidate the devices and deregister the disk */ 
977         if (disk->flags & GENHD_FL_UP)
978                 del_gendisk(disk);
979         /* check to see if it was the last disk */
980         if (logvol == h->highest_lun) {
981                 /* if so, find the new hightest lun */
982                 int i, newhighest =-1;
983                 for(i=0; i<h->highest_lun; i++) {
984                         /* if the disk has size > 0, it is available */
985                         if (h->drv[i].nr_blocks)
986                                 newhighest = i;
987                 }
988                 h->highest_lun = newhighest;
989                                 
990         }
991         --h->num_luns;
992         /* zero out the disk size info */ 
993         h->drv[logvol].nr_blocks = 0;
994         h->drv[logvol].block_size = 0;
995         h->drv[logvol].cylinders = 0;
996         h->drv[logvol].LunID = 0;
997         return(0);
998 }
999 static int fill_cmd(CommandList_struct *c, __u8 cmd, int ctlr, void *buff,
1000         size_t size,
1001         unsigned int use_unit_num, /* 0: address the controller,
1002                                       1: address logical volume log_unit,
1003                                       2: periph device address is scsi3addr */
1004         unsigned int log_unit, __u8 page_code, unsigned char *scsi3addr,
1005         int cmd_type)
1006 {
1007         ctlr_info_t *h= hba[ctlr];
1008         u64bit buff_dma_handle;
1009         int status = IO_OK;
1010
1011         c->cmd_type = CMD_IOCTL_PEND;
1012         c->Header.ReplyQueue = 0;
1013         if( buff != NULL) {
1014                 c->Header.SGList = 1;
1015                 c->Header.SGTotal= 1;
1016         } else {
1017                 c->Header.SGList = 0;
1018                 c->Header.SGTotal= 0;
1019         }
1020         c->Header.Tag.lower = c->busaddr;
1021
1022         c->Request.Type.Type = cmd_type;
1023         if (cmd_type == TYPE_CMD) {
1024                 switch(cmd) {
1025                 case  CISS_INQUIRY:
1026                         /* If the logical unit number is 0 then, this is going
1027                         to controller so It's a physical command
1028                         mode = 0 target = 0.  So we have nothing to write.
1029                         otherwise, if use_unit_num == 1,
1030                         mode = 1(volume set addressing) target = LUNID
1031                         otherwise, if use_unit_num == 2,
1032                         mode = 0(periph dev addr) target = scsi3addr */
1033                         if (use_unit_num == 1) {
1034                                 c->Header.LUN.LogDev.VolId=
1035                                         h->drv[log_unit].LunID;
1036                                 c->Header.LUN.LogDev.Mode = 1;
1037                         } else if (use_unit_num == 2) {
1038                                 memcpy(c->Header.LUN.LunAddrBytes,scsi3addr,8);
1039                                 c->Header.LUN.LogDev.Mode = 0;
1040                         }
1041                         /* are we trying to read a vital product page */
1042                         if(page_code != 0) {
1043                                 c->Request.CDB[1] = 0x01;
1044                                 c->Request.CDB[2] = page_code;
1045                         }
1046                         c->Request.CDBLen = 6;
1047                         c->Request.Type.Attribute = ATTR_SIMPLE;  
1048                         c->Request.Type.Direction = XFER_READ;
1049                         c->Request.Timeout = 0;
1050                         c->Request.CDB[0] =  CISS_INQUIRY;
1051                         c->Request.CDB[4] = size  & 0xFF;  
1052                 break;
1053                 case CISS_REPORT_LOG:
1054                 case CISS_REPORT_PHYS:
1055                         /* Talking to controller so It's a physical command
1056                            mode = 00 target = 0.  Nothing to write.
1057                         */
1058                         c->Request.CDBLen = 12;
1059                         c->Request.Type.Attribute = ATTR_SIMPLE;
1060                         c->Request.Type.Direction = XFER_READ;
1061                         c->Request.Timeout = 0;
1062                         c->Request.CDB[0] = cmd;
1063                         c->Request.CDB[6] = (size >> 24) & 0xFF;  //MSB
1064                         c->Request.CDB[7] = (size >> 16) & 0xFF;
1065                         c->Request.CDB[8] = (size >> 8) & 0xFF;
1066                         c->Request.CDB[9] = size & 0xFF;
1067                         break;
1068
1069                 case CCISS_READ_CAPACITY:
1070                         c->Header.LUN.LogDev.VolId = h->drv[log_unit].LunID;
1071                         c->Header.LUN.LogDev.Mode = 1;
1072                         c->Request.CDBLen = 10;
1073                         c->Request.Type.Attribute = ATTR_SIMPLE;
1074                         c->Request.Type.Direction = XFER_READ;
1075                         c->Request.Timeout = 0;
1076                         c->Request.CDB[0] = cmd;
1077                 break;
1078                 case CCISS_CACHE_FLUSH:
1079                         c->Request.CDBLen = 12;
1080                         c->Request.Type.Attribute = ATTR_SIMPLE;
1081                         c->Request.Type.Direction = XFER_WRITE;
1082                         c->Request.Timeout = 0;
1083                         c->Request.CDB[0] = BMIC_WRITE;
1084                         c->Request.CDB[6] = BMIC_CACHE_FLUSH;
1085                 break;
1086                 default:
1087                         printk(KERN_WARNING
1088                                 "cciss%d:  Unknown Command 0x%c\n", ctlr, cmd);
1089                         return(IO_ERROR);
1090                 }
1091         } else if (cmd_type == TYPE_MSG) {
1092                 switch (cmd) {
1093                 case 3: /* No-Op message */
1094                         c->Request.CDBLen = 1;
1095                         c->Request.Type.Attribute = ATTR_SIMPLE;
1096                         c->Request.Type.Direction = XFER_WRITE;
1097                         c->Request.Timeout = 0;
1098                         c->Request.CDB[0] = cmd;
1099                         break;
1100                 default:
1101                         printk(KERN_WARNING
1102                                 "cciss%d: unknown message type %d\n",
1103                                 ctlr, cmd);
1104                         return IO_ERROR;
1105                 }
1106         } else {
1107                 printk(KERN_WARNING
1108                         "cciss%d: unknown command type %d\n", ctlr, cmd_type);
1109                 return IO_ERROR;
1110         }
1111         /* Fill in the scatter gather information */
1112         if (size > 0) {
1113                 buff_dma_handle.val = (__u64) pci_map_single(h->pdev,
1114                         buff, size, PCI_DMA_BIDIRECTIONAL);
1115                 c->SG[0].Addr.lower = buff_dma_handle.val32.lower;
1116                 c->SG[0].Addr.upper = buff_dma_handle.val32.upper;
1117                 c->SG[0].Len = size;
1118                 c->SG[0].Ext = 0;  /* we are not chaining */
1119         }
1120         return status;
1121 }
1122 static int sendcmd_withirq(__u8 cmd,
1123         int     ctlr,
1124         void    *buff,
1125         size_t  size,
1126         unsigned int use_unit_num,
1127         unsigned int log_unit,
1128         __u8    page_code,
1129         int cmd_type)
1130 {
1131         ctlr_info_t *h = hba[ctlr];
1132         CommandList_struct *c;
1133         u64bit  buff_dma_handle;
1134         unsigned long flags;
1135         int return_status;
1136         DECLARE_COMPLETION(wait);
1137         
1138         if ((c = cmd_alloc(h , 0)) == NULL)
1139                 return -ENOMEM;
1140         return_status = fill_cmd(c, cmd, ctlr, buff, size, use_unit_num,
1141                 log_unit, page_code, NULL, cmd_type);
1142         if (return_status != IO_OK) {
1143                 cmd_free(h, c, 0);
1144                 return return_status;
1145         }
1146 resend_cmd2:
1147         c->waiting = &wait;
1148         
1149         /* Put the request on the tail of the queue and send it */
1150         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1151         addQ(&h->reqQ, c);
1152         h->Qdepth++;
1153         start_io(h);
1154         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1155         
1156         wait_for_completion(&wait);
1157
1158         if(c->err_info->CommandStatus != 0) 
1159         { /* an error has occurred */ 
1160                 switch(c->err_info->CommandStatus)
1161                 {
1162                         case CMD_TARGET_STATUS:
1163                                 printk(KERN_WARNING "cciss: cmd %p has "
1164                                         " completed with errors\n", c);
1165                                 if( c->err_info->ScsiStatus)
1166                                 {
1167                                         printk(KERN_WARNING "cciss: cmd %p "
1168                                         "has SCSI Status = %x\n",
1169                                                 c,  
1170                                                 c->err_info->ScsiStatus);
1171                                 }
1172
1173                         break;
1174                         case CMD_DATA_UNDERRUN:
1175                         case CMD_DATA_OVERRUN:
1176                         /* expected for inquire and report lun commands */
1177                         break;
1178                         case CMD_INVALID:
1179                                 printk(KERN_WARNING "cciss: Cmd %p is "
1180                                         "reported invalid\n", c);
1181                                 return_status = IO_ERROR;
1182                         break;
1183                         case CMD_PROTOCOL_ERR:
1184                                 printk(KERN_WARNING "cciss: cmd %p has "
1185                                         "protocol error \n", c);
1186                                 return_status = IO_ERROR;
1187                         break;
1188 case CMD_HARDWARE_ERR:
1189                                 printk(KERN_WARNING "cciss: cmd %p had " 
1190                                         " hardware error\n", c);
1191                                 return_status = IO_ERROR;
1192                         break;
1193                         case CMD_CONNECTION_LOST:
1194                                 printk(KERN_WARNING "cciss: cmd %p had "
1195                                         "connection lost\n", c);
1196                                 return_status = IO_ERROR;
1197                         break;
1198                         case CMD_ABORTED:
1199                                 printk(KERN_WARNING "cciss: cmd %p was "
1200                                         "aborted\n", c);
1201                                 return_status = IO_ERROR;
1202                         break;
1203                         case CMD_ABORT_FAILED:
1204                                 printk(KERN_WARNING "cciss: cmd %p reports "
1205                                         "abort failed\n", c);
1206                                 return_status = IO_ERROR;
1207                         break;
1208                         case CMD_UNSOLICITED_ABORT:
1209                                 printk(KERN_WARNING 
1210                                         "cciss%d: unsolicited abort %p\n",
1211                                         ctlr, c);
1212                                 if (c->retry_count < MAX_CMD_RETRIES) {
1213                                         printk(KERN_WARNING 
1214                                                 "cciss%d: retrying %p\n", 
1215                                                 ctlr, c);
1216                                         c->retry_count++;
1217                                         /* erase the old error information */
1218                                         memset(c->err_info, 0,
1219                                                 sizeof(ErrorInfo_struct));
1220                                         return_status = IO_OK;
1221                                         INIT_COMPLETION(wait);
1222                                         goto resend_cmd2;
1223                                 }
1224                                 return_status = IO_ERROR;
1225                         break;
1226                         default:
1227                                 printk(KERN_WARNING "cciss: cmd %p returned "
1228                                         "unknown status %x\n", c, 
1229                                                 c->err_info->CommandStatus); 
1230                                 return_status = IO_ERROR;
1231                 }
1232         }       
1233         /* unlock the buffers from DMA */
1234         pci_unmap_single( h->pdev, (dma_addr_t) buff_dma_handle.val,
1235                         size, PCI_DMA_BIDIRECTIONAL);
1236         cmd_free(h, c, 0);
1237         return(return_status);
1238
1239 }
1240 static void cciss_geometry_inquiry(int ctlr, int logvol,
1241                         int withirq, unsigned int total_size,
1242                         unsigned int block_size, InquiryData_struct *inq_buff,
1243                         drive_info_struct *drv)
1244 {
1245         int return_code;
1246         memset(inq_buff, 0, sizeof(InquiryData_struct));
1247         if (withirq)
1248                 return_code = sendcmd_withirq(CISS_INQUIRY, ctlr,
1249                         inq_buff, sizeof(*inq_buff), 1, logvol ,0xC1, TYPE_CMD);
1250         else
1251                 return_code = sendcmd(CISS_INQUIRY, ctlr, inq_buff,
1252                         sizeof(*inq_buff), 1, logvol ,0xC1, NULL, TYPE_CMD);
1253         if (return_code == IO_OK) {
1254                 if(inq_buff->data_byte[8] == 0xFF) {
1255                         printk(KERN_WARNING
1256                                 "cciss: reading geometry failed, volume "
1257                                 "does not support reading geometry\n");
1258                         drv->block_size = block_size;
1259                         drv->nr_blocks = total_size;
1260                         drv->heads = 255;
1261                         drv->sectors = 32; // Sectors per track
1262                         drv->cylinders = total_size / 255 / 32;
1263                 } else {
1264                         drv->block_size = block_size;
1265                         drv->nr_blocks = total_size;
1266                         drv->heads = inq_buff->data_byte[6];
1267                         drv->sectors = inq_buff->data_byte[7];
1268                         drv->cylinders = (inq_buff->data_byte[4] & 0xff) << 8;
1269                         drv->cylinders += inq_buff->data_byte[5];
1270                 }
1271         } else { /* Get geometry failed */
1272                 printk(KERN_WARNING "cciss: reading geometry failed, "
1273                         "continuing with default geometry\n");
1274                 drv->block_size = block_size;
1275                 drv->nr_blocks = total_size;
1276                 drv->heads = 255;
1277                 drv->sectors = 32; // Sectors per track
1278                 drv->cylinders = total_size / 255 / 32;
1279         }
1280         printk(KERN_INFO "      heads= %d, sectors= %d, cylinders= %d\n\n",
1281                 drv->heads, drv->sectors, drv->cylinders);
1282 }
1283 static void
1284 cciss_read_capacity(int ctlr, int logvol, ReadCapdata_struct *buf,
1285                 int withirq, unsigned int *total_size, unsigned int *block_size)
1286 {
1287         int return_code;
1288         memset(buf, 0, sizeof(*buf));
1289         if (withirq)
1290                 return_code = sendcmd_withirq(CCISS_READ_CAPACITY,
1291                         ctlr, buf, sizeof(*buf), 1, logvol, 0, TYPE_CMD);
1292         else
1293                 return_code = sendcmd(CCISS_READ_CAPACITY,
1294                         ctlr, buf, sizeof(*buf), 1, logvol, 0, NULL, TYPE_CMD);
1295         if (return_code == IO_OK) {
1296                 *total_size = be32_to_cpu(*((__u32 *) &buf->total_size[0]))+1;
1297                 *block_size = be32_to_cpu(*((__u32 *) &buf->block_size[0]));
1298         } else { /* read capacity command failed */
1299                 printk(KERN_WARNING "cciss: read capacity failed\n");
1300                 *total_size = 0;
1301                 *block_size = BLOCK_SIZE;
1302         }
1303         printk(KERN_INFO "      blocks= %d block_size= %d\n",
1304                 *total_size, *block_size);
1305         return;
1306 }
1307 static int register_new_disk(int ctlr)
1308 {
1309         struct gendisk *disk;
1310         ctlr_info_t  *h = hba[ctlr];
1311         int i;
1312         int num_luns;
1313         int logvol;
1314         int new_lun_found = 0;
1315         int new_lun_index = 0;
1316         int free_index_found = 0;
1317         int free_index = 0;
1318         ReportLunData_struct *ld_buff = NULL;
1319         ReadCapdata_struct *size_buff = NULL;
1320         InquiryData_struct *inq_buff = NULL;
1321         int return_code;
1322         int listlength = 0;
1323         __u32 lunid = 0;
1324         unsigned int block_size;
1325         unsigned int total_size;
1326
1327         if (!capable(CAP_SYS_RAWIO))
1328                 return -EPERM;
1329         /* if we have no space in our disk array left to add anything */
1330         if(  h->num_luns >= CISS_MAX_LUN)
1331                 return -EINVAL;
1332         
1333         ld_buff = kmalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
1334         if (ld_buff == NULL)
1335                 goto mem_msg;
1336         memset(ld_buff, 0, sizeof(ReportLunData_struct));
1337         size_buff = kmalloc(sizeof( ReadCapdata_struct), GFP_KERNEL);
1338         if (size_buff == NULL)
1339                 goto mem_msg;
1340         inq_buff = kmalloc(sizeof( InquiryData_struct), GFP_KERNEL);
1341         if (inq_buff == NULL)
1342                 goto mem_msg;
1343         
1344         return_code = sendcmd_withirq(CISS_REPORT_LOG, ctlr, ld_buff, 
1345                         sizeof(ReportLunData_struct), 0, 0, 0, TYPE_CMD);
1346
1347         if( return_code == IO_OK)
1348         {
1349                 
1350                 // printk("LUN Data\n--------------------------\n");
1351
1352                 listlength |= (0xff & (unsigned int)(ld_buff->LUNListLength[0])) << 24;
1353                 listlength |= (0xff & (unsigned int)(ld_buff->LUNListLength[1])) << 16;
1354                 listlength |= (0xff & (unsigned int)(ld_buff->LUNListLength[2])) << 8;  
1355                 listlength |= 0xff & (unsigned int)(ld_buff->LUNListLength[3]);
1356         } else /* reading number of logical volumes failed */
1357         {
1358                 printk(KERN_WARNING "cciss: report logical volume"
1359                         " command failed\n");
1360                 listlength = 0;
1361                 goto free_err;
1362         }
1363         num_luns = listlength / 8; // 8 bytes pre entry
1364         if (num_luns > CISS_MAX_LUN)
1365         {
1366                 num_luns = CISS_MAX_LUN;
1367         }
1368 #ifdef CCISS_DEBUG
1369         printk(KERN_DEBUG "Length = %x %x %x %x = %d\n", ld_buff->LUNListLength[0],
1370                 ld_buff->LUNListLength[1], ld_buff->LUNListLength[2],
1371                 ld_buff->LUNListLength[3],  num_luns);
1372 #endif 
1373         for(i=0; i<  num_luns; i++)
1374         {
1375                 int j;
1376                 int lunID_found = 0;
1377
1378                 lunid = (0xff & (unsigned int)(ld_buff->LUN[i][3])) << 24;
1379                 lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][2])) << 16;
1380                 lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][1])) << 8;
1381                 lunid |= 0xff & (unsigned int)(ld_buff->LUN[i][0]);
1382                 
1383                 /* check to see if this is a new lun */ 
1384                 for(j=0; j <= h->highest_lun; j++)
1385                 {
1386 #ifdef CCISS_DEBUG
1387                         printk("Checking %d %x against %x\n", j,h->drv[j].LunID,
1388                                                 lunid);
1389 #endif /* CCISS_DEBUG */
1390                         if (h->drv[j].LunID == lunid)
1391                         {
1392                                 lunID_found = 1;
1393                                 break;
1394                         }
1395                         
1396                 }
1397                 if( lunID_found == 1)
1398                         continue;
1399                 else
1400                 {       /* It is the new lun we have been looking for */
1401 #ifdef CCISS_DEBUG
1402                         printk("new lun found at %d\n", i);
1403 #endif /* CCISS_DEBUG */
1404                         new_lun_index = i;
1405                         new_lun_found = 1;
1406                         break;  
1407                 }
1408          }
1409          if (!new_lun_found)
1410          {
1411                 printk(KERN_WARNING "cciss:  New Logical Volume not found\n");
1412                 goto free_err;
1413          }
1414          /* Now find the free index     */
1415         for(i=0; i <CISS_MAX_LUN; i++)
1416         {
1417 #ifdef CCISS_DEBUG
1418                 printk("Checking Index %d\n", i);
1419 #endif /* CCISS_DEBUG */
1420                 if(hba[ctlr]->drv[i].LunID == 0)
1421                 {
1422 #ifdef CCISS_DEBUG
1423                         printk("free index found at %d\n", i);
1424 #endif /* CCISS_DEBUG */
1425                         free_index_found = 1;
1426                         free_index = i;
1427                         break;
1428                 }
1429         }
1430         if (!free_index_found)
1431         {
1432                 printk(KERN_WARNING "cciss: unable to find free slot for disk\n");
1433                 goto free_err;
1434          }
1435
1436         logvol = free_index;
1437         hba[ctlr]->drv[logvol].LunID = lunid;
1438                 /* there could be gaps in lun numbers, track hightest */
1439         if(hba[ctlr]->highest_lun < lunid)
1440                 hba[ctlr]->highest_lun = logvol;
1441         cciss_read_capacity(ctlr, logvol, size_buff, 1,
1442                 &total_size, &block_size);
1443         cciss_geometry_inquiry(ctlr, logvol, 1, total_size, block_size,
1444                         inq_buff, &hba[ctlr]->drv[logvol]);
1445         hba[ctlr]->drv[logvol].usage_count = 0;
1446         ++hba[ctlr]->num_luns;
1447         /* setup partitions per disk */
1448         disk = hba[ctlr]->gendisk[logvol];
1449         set_capacity(disk, hba[ctlr]->drv[logvol].nr_blocks);
1450         add_disk(disk);
1451 freeret:
1452         kfree(ld_buff);
1453         kfree(size_buff);
1454         kfree(inq_buff);
1455         return (logvol);
1456 mem_msg:
1457         printk(KERN_ERR "cciss: out of memory\n");
1458 free_err:
1459         logvol = -1;
1460         goto freeret;
1461 }
1462 /*
1463  *   Wait polling for a command to complete.
1464  *   The memory mapped FIFO is polled for the completion.
1465  *   Used only at init time, interrupts from the HBA are disabled.
1466  */
1467 static unsigned long pollcomplete(int ctlr)
1468 {
1469         unsigned long done;
1470         int i;
1471
1472         /* Wait (up to 20 seconds) for a command to complete */
1473
1474         for (i = 20 * HZ; i > 0; i--) {
1475                 done = hba[ctlr]->access.command_completed(hba[ctlr]);
1476                 if (done == FIFO_EMPTY) {
1477                         set_current_state(TASK_UNINTERRUPTIBLE);
1478                         schedule_timeout(1);
1479                 } else
1480                         return (done);
1481         }
1482         /* Invalid address to tell caller we ran out of time */
1483         return 1;
1484 }
1485 /*
1486  * Send a command to the controller, and wait for it to complete.  
1487  * Only used at init time. 
1488  */
1489 static int sendcmd(
1490         __u8    cmd,
1491         int     ctlr,
1492         void    *buff,
1493         size_t  size,
1494         unsigned int use_unit_num, /* 0: address the controller,
1495                                       1: address logical volume log_unit, 
1496                                       2: periph device address is scsi3addr */
1497         unsigned int log_unit,
1498         __u8    page_code,
1499         unsigned char *scsi3addr,
1500         int cmd_type)
1501 {
1502         CommandList_struct *c;
1503         int i;
1504         unsigned long complete;
1505         ctlr_info_t *info_p= hba[ctlr];
1506         u64bit buff_dma_handle;
1507         int status;
1508
1509         if ((c = cmd_alloc(info_p, 1)) == NULL) {
1510                 printk(KERN_WARNING "cciss: unable to get memory");
1511                 return(IO_ERROR);
1512         }
1513         status = fill_cmd(c, cmd, ctlr, buff, size, use_unit_num,
1514                 log_unit, page_code, scsi3addr, cmd_type);
1515         if (status != IO_OK) {
1516                 cmd_free(info_p, c, 1);
1517                 return status;
1518         }
1519 resend_cmd1:
1520         /*
1521          * Disable interrupt
1522          */
1523 #ifdef CCISS_DEBUG
1524         printk(KERN_DEBUG "cciss: turning intr off\n");
1525 #endif /* CCISS_DEBUG */ 
1526         info_p->access.set_intr_mask(info_p, CCISS_INTR_OFF);
1527         
1528         /* Make sure there is room in the command FIFO */
1529         /* Actually it should be completely empty at this time. */
1530         for (i = 200000; i > 0; i--) 
1531         {
1532                 /* if fifo isn't full go */
1533                 if (!(info_p->access.fifo_full(info_p))) 
1534                 {
1535                         
1536                         break;
1537                 }
1538                 udelay(10);
1539                 printk(KERN_WARNING "cciss cciss%d: SendCmd FIFO full,"
1540                         " waiting!\n", ctlr);
1541         }
1542         /*
1543          * Send the cmd
1544          */
1545         info_p->access.submit_command(info_p, c);
1546         complete = pollcomplete(ctlr);
1547
1548 #ifdef CCISS_DEBUG
1549         printk(KERN_DEBUG "cciss: command completed\n");
1550 #endif /* CCISS_DEBUG */
1551
1552         if (complete != 1) {
1553                 if ( (complete & CISS_ERROR_BIT)
1554                      && (complete & ~CISS_ERROR_BIT) == c->busaddr)
1555                      {
1556                         /* if data overrun or underun on Report command 
1557                                 ignore it 
1558                         */
1559                         if (((c->Request.CDB[0] == CISS_REPORT_LOG) ||
1560                              (c->Request.CDB[0] == CISS_REPORT_PHYS) ||
1561                              (c->Request.CDB[0] == CISS_INQUIRY)) &&
1562                                 ((c->err_info->CommandStatus == 
1563                                         CMD_DATA_OVERRUN) || 
1564                                  (c->err_info->CommandStatus == 
1565                                         CMD_DATA_UNDERRUN)
1566                                 ))
1567                         {
1568                                 complete = c->busaddr;
1569                         } else {
1570                                 if (c->err_info->CommandStatus ==
1571                                                 CMD_UNSOLICITED_ABORT) {
1572                                         printk(KERN_WARNING "cciss%d: "
1573                                                 "unsolicited abort %p\n",
1574                                                 ctlr, c);
1575                                         if (c->retry_count < MAX_CMD_RETRIES) {
1576                                                 printk(KERN_WARNING
1577                                                    "cciss%d: retrying %p\n",
1578                                                    ctlr, c);
1579                                                 c->retry_count++;
1580                                                 /* erase the old error */
1581                                                 /* information */
1582                                                 memset(c->err_info, 0,
1583                                                    sizeof(ErrorInfo_struct));
1584                                                 goto resend_cmd1;
1585                                         } else {
1586                                                 printk(KERN_WARNING
1587                                                    "cciss%d: retried %p too "
1588                                                    "many times\n", ctlr, c);
1589                                                 status = IO_ERROR;
1590                                                 goto cleanup1;
1591                                         }
1592                                 }
1593                                 printk(KERN_WARNING "ciss ciss%d: sendcmd"
1594                                 " Error %x \n", ctlr, 
1595                                         c->err_info->CommandStatus); 
1596                                 printk(KERN_WARNING "ciss ciss%d: sendcmd"
1597                                 " offensive info\n"
1598                                 "  size %x\n   num %x   value %x\n", ctlr,
1599                                   c->err_info->MoreErrInfo.Invalid_Cmd.offense_size,
1600                                   c->err_info->MoreErrInfo.Invalid_Cmd.offense_num,
1601                                   c->err_info->MoreErrInfo.Invalid_Cmd.offense_value);
1602                                 status = IO_ERROR;
1603                                 goto cleanup1;
1604                         }
1605                 }
1606                 if (complete != c->busaddr) {
1607                         printk( KERN_WARNING "cciss cciss%d: SendCmd "
1608                       "Invalid command list address returned! (%lx)\n",
1609                                 ctlr, complete);
1610                         status = IO_ERROR;
1611                         goto cleanup1;
1612                 }
1613         } else {
1614                 printk( KERN_WARNING
1615                         "cciss cciss%d: SendCmd Timeout out, "
1616                         "No command list address returned!\n",
1617                         ctlr);
1618                 status = IO_ERROR;
1619         }
1620                 
1621 cleanup1:       
1622         /* unlock the data buffer from DMA */
1623         pci_unmap_single(info_p->pdev, (dma_addr_t) buff_dma_handle.val,
1624                                 size, PCI_DMA_BIDIRECTIONAL);
1625         cmd_free(info_p, c, 1);
1626         return (status);
1627
1628 /*
1629  * Map (physical) PCI mem into (virtual) kernel space
1630  */
1631 static ulong remap_pci_mem(ulong base, ulong size)
1632 {
1633         ulong page_base        = ((ulong) base) & PAGE_MASK;
1634         ulong page_offs        = ((ulong) base) - page_base;
1635         ulong page_remapped    = (ulong) ioremap(page_base, page_offs+size);
1636
1637         return (ulong) (page_remapped ? (page_remapped + page_offs) : 0UL);
1638 }
1639
1640 /*
1641  * Enqueuing and dequeuing functions for cmdlists.
1642  */
1643 static inline void addQ(CommandList_struct **Qptr, CommandList_struct *c)
1644 {
1645         if (*Qptr == NULL) {
1646                 *Qptr = c;
1647                 c->next = c->prev = c;
1648         } else {
1649                 c->prev = (*Qptr)->prev;
1650                 c->next = (*Qptr);
1651                 (*Qptr)->prev->next = c;
1652                 (*Qptr)->prev = c;
1653         }
1654 }
1655
1656 static inline CommandList_struct *removeQ(CommandList_struct **Qptr, 
1657                                                 CommandList_struct *c)
1658 {
1659         if (c && c->next != c) {
1660                 if (*Qptr == c) *Qptr = c->next;
1661                 c->prev->next = c->next;
1662                 c->next->prev = c->prev;
1663         } else {
1664                 *Qptr = NULL;
1665         }
1666         return c;
1667 }
1668
1669 /* 
1670  * Takes jobs of the Q and sends them to the hardware, then puts it on 
1671  * the Q to wait for completion. 
1672  */ 
1673 static void start_io( ctlr_info_t *h)
1674 {
1675         CommandList_struct *c;
1676         
1677         while(( c = h->reqQ) != NULL )
1678         {
1679                 /* can't do anything if fifo is full */
1680                 if ((h->access.fifo_full(h))) {
1681                         printk(KERN_WARNING "cciss: fifo full\n");
1682                         break;
1683                 }
1684
1685                 /* Get the frist entry from the Request Q */ 
1686                 removeQ(&(h->reqQ), c);
1687                 h->Qdepth--;
1688         
1689                 /* Tell the controller execute command */ 
1690                 h->access.submit_command(h, c);
1691                 
1692                 /* Put job onto the completed Q */ 
1693                 addQ (&(h->cmpQ), c); 
1694         }
1695 }
1696
1697 static inline void complete_buffers(struct bio *bio, int status)
1698 {
1699         while (bio) {
1700                 struct bio *xbh = bio->bi_next; 
1701                 int nr_sectors = bio_sectors(bio);
1702
1703                 bio->bi_next = NULL; 
1704                 blk_finished_io(len);
1705                 bio_endio(bio, nr_sectors << 9, status ? 0 : -EIO);
1706                 bio = xbh;
1707         }
1708
1709
1710 /* Assumes that CCISS_LOCK(h->ctlr) is held. */
1711 /* Zeros out the error record and then resends the command back */
1712 /* to the controller */
1713 static inline void resend_cciss_cmd( ctlr_info_t *h, CommandList_struct *c)
1714 {
1715         /* erase the old error information */
1716         memset(c->err_info, 0, sizeof(ErrorInfo_struct));
1717
1718         /* add it to software queue and then send it to the controller */
1719         addQ(&(h->reqQ),c);
1720         h->Qdepth++;
1721         if(h->Qdepth > h->maxQsinceinit)
1722                 h->maxQsinceinit = h->Qdepth;
1723
1724         start_io(h);
1725 }
1726 /* checks the status of the job and calls complete buffers to mark all 
1727  * buffers for the completed job. 
1728  */ 
1729 static inline void complete_command( ctlr_info_t *h, CommandList_struct *cmd,
1730                 int timeout)
1731 {
1732         int status = 1;
1733         int i;
1734         int retry_cmd = 0;
1735         u64bit temp64;
1736                 
1737         if (timeout)
1738                 status = 0; 
1739
1740         if(cmd->err_info->CommandStatus != 0) 
1741         { /* an error has occurred */ 
1742                 switch(cmd->err_info->CommandStatus)
1743                 {
1744                         unsigned char sense_key;
1745                         case CMD_TARGET_STATUS:
1746                                 status = 0;
1747                         
1748                                 if( cmd->err_info->ScsiStatus == 0x02)
1749                                 {
1750                                         printk(KERN_WARNING "cciss: cmd %p "
1751                                                 "has CHECK CONDITION "
1752                                                 " byte 2 = 0x%x\n", cmd,
1753                                                 cmd->err_info->SenseInfo[2]
1754                                         );
1755                                         /* check the sense key */
1756                                         sense_key = 0xf & 
1757                                                 cmd->err_info->SenseInfo[2];
1758                                         /* no status or recovered error */
1759                                         if((sense_key == 0x0) ||
1760                                             (sense_key == 0x1))
1761                                         {
1762                                                         status = 1;
1763                                         }
1764                                 } else
1765                                 {
1766                                         printk(KERN_WARNING "cciss: cmd %p "
1767                                                 "has SCSI Status 0x%x\n",
1768                                                 cmd, cmd->err_info->ScsiStatus);
1769                                 }
1770                         break;
1771                         case CMD_DATA_UNDERRUN:
1772                                 printk(KERN_WARNING "cciss: cmd %p has"
1773                                         " completed with data underrun "
1774                                         "reported\n", cmd);
1775                         break;
1776                         case CMD_DATA_OVERRUN:
1777                                 printk(KERN_WARNING "cciss: cmd %p has"
1778                                         " completed with data overrun "
1779                                         "reported\n", cmd);
1780                         break;
1781                         case CMD_INVALID:
1782                                 printk(KERN_WARNING "cciss: cmd %p is "
1783                                         "reported invalid\n", cmd);
1784                                 status = 0;
1785                         break;
1786                         case CMD_PROTOCOL_ERR:
1787                                 printk(KERN_WARNING "cciss: cmd %p has "
1788                                         "protocol error \n", cmd);
1789                                 status = 0;
1790                         break;
1791                         case CMD_HARDWARE_ERR:
1792                                 printk(KERN_WARNING "cciss: cmd %p had " 
1793                                         " hardware error\n", cmd);
1794                                 status = 0;
1795                         break;
1796                         case CMD_CONNECTION_LOST:
1797                                 printk(KERN_WARNING "cciss: cmd %p had "
1798                                         "connection lost\n", cmd);
1799                                 status=0;
1800                         break;
1801                         case CMD_ABORTED:
1802                                 printk(KERN_WARNING "cciss: cmd %p was "
1803                                         "aborted\n", cmd);
1804                                 status=0;
1805                         break;
1806                         case CMD_ABORT_FAILED:
1807                                 printk(KERN_WARNING "cciss: cmd %p reports "
1808                                         "abort failed\n", cmd);
1809                                 status=0;
1810                         break;
1811                         case CMD_UNSOLICITED_ABORT:
1812                                 printk(KERN_WARNING "cciss%d: unsolicited "
1813                                         "abort %p\n", h->ctlr, cmd);
1814                                 if (cmd->retry_count < MAX_CMD_RETRIES) {
1815                                         retry_cmd=1;
1816                                         printk(KERN_WARNING
1817                                                 "cciss%d: retrying %p\n",
1818                                                 h->ctlr, cmd);
1819                                         cmd->retry_count++;
1820                                 } else
1821                                         printk(KERN_WARNING
1822                                                 "cciss%d: %p retried too "
1823                                                 "many times\n", h->ctlr, cmd);
1824                                 status=0;
1825                         break;
1826                         case CMD_TIMEOUT:
1827                                 printk(KERN_WARNING "cciss: cmd %p timedout\n",
1828                                         cmd);
1829                                 status=0;
1830                         break;
1831                         default:
1832                                 printk(KERN_WARNING "cciss: cmd %p returned "
1833                                         "unknown status %x\n", cmd, 
1834                                                 cmd->err_info->CommandStatus); 
1835                                 status=0;
1836                 }
1837         }
1838         /* We need to return this command */
1839         if(retry_cmd) {
1840                 resend_cciss_cmd(h,cmd);
1841                 return;
1842         }       
1843         /* command did not need to be retried */
1844         /* unmap the DMA mapping for all the scatter gather elements */
1845         for(i=0; i<cmd->Header.SGList; i++) {
1846                 temp64.val32.lower = cmd->SG[i].Addr.lower;
1847                 temp64.val32.upper = cmd->SG[i].Addr.upper;
1848                 pci_unmap_page(hba[cmd->ctlr]->pdev,
1849                         temp64.val, cmd->SG[i].Len,
1850                         (cmd->Request.Type.Direction == XFER_READ) ?
1851                                 PCI_DMA_FROMDEVICE : PCI_DMA_TODEVICE);
1852         }
1853         complete_buffers(cmd->rq->bio, status);
1854
1855 #ifdef CCISS_DEBUG
1856         printk("Done with %p\n", cmd->rq);
1857 #endif /* CCISS_DEBUG */ 
1858
1859         end_that_request_last(cmd->rq);
1860         cmd_free(h,cmd,1);
1861 }
1862
1863 /* 
1864  * Get a request and submit it to the controller. 
1865  */
1866 static void do_cciss_request(request_queue_t *q)
1867 {
1868         ctlr_info_t *h= q->queuedata; 
1869         CommandList_struct *c;
1870         int start_blk, seg;
1871         struct request *creq;
1872         u64bit temp64;
1873         struct scatterlist tmp_sg[MAXSGENTRIES];
1874         drive_info_struct *drv;
1875         int i, dir;
1876
1877         if (blk_queue_plugged(q))
1878                 goto startio;
1879
1880 queue:
1881         creq = elv_next_request(q);
1882         if (!creq)
1883                 goto startio;
1884
1885         if (creq->nr_phys_segments > MAXSGENTRIES)
1886                 BUG();
1887
1888         if (( c = cmd_alloc(h, 1)) == NULL)
1889                 goto full;
1890
1891         blkdev_dequeue_request(creq);
1892
1893         spin_unlock_irq(q->queue_lock);
1894
1895         c->cmd_type = CMD_RWREQ;
1896         c->rq = creq;
1897         
1898         /* fill in the request */ 
1899         drv = creq->rq_disk->private_data;
1900         c->Header.ReplyQueue = 0;  // unused in simple mode
1901         c->Header.Tag.lower = c->busaddr;  // use the physical address the cmd block for tag
1902         c->Header.LUN.LogDev.VolId= drv->LunID;
1903         c->Header.LUN.LogDev.Mode = 1;
1904         c->Request.CDBLen = 10; // 12 byte commands not in FW yet;
1905         c->Request.Type.Type =  TYPE_CMD; // It is a command. 
1906         c->Request.Type.Attribute = ATTR_SIMPLE; 
1907         c->Request.Type.Direction = 
1908                 (rq_data_dir(creq) == READ) ? XFER_READ: XFER_WRITE; 
1909         c->Request.Timeout = 0; // Don't time out       
1910         c->Request.CDB[0] = (rq_data_dir(creq) == READ) ? CCISS_READ : CCISS_WRITE;
1911         start_blk = creq->sector;
1912 #ifdef CCISS_DEBUG
1913         printk(KERN_DEBUG "ciss: sector =%d nr_sectors=%d\n",(int) creq->sector,
1914                 (int) creq->nr_sectors);        
1915 #endif /* CCISS_DEBUG */
1916
1917         seg = blk_rq_map_sg(q, creq, tmp_sg);
1918
1919         /* get the DMA records for the setup */ 
1920         if (c->Request.Type.Direction == XFER_READ)
1921                 dir = PCI_DMA_FROMDEVICE;
1922         else
1923                 dir = PCI_DMA_TODEVICE;
1924
1925         for (i=0; i<seg; i++)
1926         {
1927                 c->SG[i].Len = tmp_sg[i].length;
1928                 temp64.val = (__u64) pci_map_page(h->pdev, tmp_sg[i].page,
1929                                           tmp_sg[i].offset, tmp_sg[i].length,
1930                                           dir);
1931                 c->SG[i].Addr.lower = temp64.val32.lower;
1932                 c->SG[i].Addr.upper = temp64.val32.upper;
1933                 c->SG[i].Ext = 0;  // we are not chaining
1934         }
1935         /* track how many SG entries we are using */ 
1936         if( seg > h->maxSG)
1937                 h->maxSG = seg; 
1938
1939 #ifdef CCISS_DEBUG
1940         printk(KERN_DEBUG "cciss: Submitting %d sectors in %d segments\n", creq->nr_sectors, seg);
1941 #endif /* CCISS_DEBUG */
1942
1943         c->Header.SGList = c->Header.SGTotal = seg;
1944         c->Request.CDB[1]= 0;
1945         c->Request.CDB[2]= (start_blk >> 24) & 0xff;    //MSB
1946         c->Request.CDB[3]= (start_blk >> 16) & 0xff;
1947         c->Request.CDB[4]= (start_blk >>  8) & 0xff;
1948         c->Request.CDB[5]= start_blk & 0xff;
1949         c->Request.CDB[6]= 0; // (sect >> 24) & 0xff; MSB
1950         c->Request.CDB[7]= (creq->nr_sectors >>  8) & 0xff; 
1951         c->Request.CDB[8]= creq->nr_sectors & 0xff; 
1952         c->Request.CDB[9] = c->Request.CDB[11] = c->Request.CDB[12] = 0;
1953
1954         spin_lock_irq(q->queue_lock);
1955
1956         addQ(&(h->reqQ),c);
1957         h->Qdepth++;
1958         if(h->Qdepth > h->maxQsinceinit)
1959                 h->maxQsinceinit = h->Qdepth; 
1960
1961         goto queue;
1962 full:
1963         blk_stop_queue(q);
1964 startio:
1965         start_io(h);
1966 }
1967
1968 static irqreturn_t do_cciss_intr(int irq, void *dev_id, struct pt_regs *regs)
1969 {
1970         ctlr_info_t *h = dev_id;
1971         CommandList_struct *c;
1972         unsigned long flags;
1973         __u32 a, a1;
1974
1975
1976         /* Is this interrupt for us? */
1977         if ( h->access.intr_pending(h) == 0)
1978                 return IRQ_NONE;
1979
1980         /*
1981          * If there are completed commands in the completion queue,
1982          * we had better do something about it.
1983          */
1984         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
1985         while( h->access.intr_pending(h))
1986         {
1987                 while((a = h->access.command_completed(h)) != FIFO_EMPTY) 
1988                 {
1989                         a1 = a;
1990                         a &= ~3;
1991                         if ((c = h->cmpQ) == NULL)
1992                         {  
1993                                 printk(KERN_WARNING "cciss: Completion of %08lx ignored\n", (unsigned long)a1);
1994                                 continue;       
1995                         } 
1996                         while(c->busaddr != a) {
1997                                 c = c->next;
1998                                 if (c == h->cmpQ) 
1999                                         break;
2000                         }
2001                         /*
2002                          * If we've found the command, take it off the
2003                          * completion Q and free it
2004                          */
2005                          if (c->busaddr == a) {
2006                                 removeQ(&h->cmpQ, c);
2007                                 if (c->cmd_type == CMD_RWREQ) {
2008                                         complete_command(h, c, 0);
2009                                 } else if (c->cmd_type == CMD_IOCTL_PEND) {
2010                                         complete(c->waiting);
2011                                 }
2012 #                               ifdef CONFIG_CISS_SCSI_TAPE
2013                                 else if (c->cmd_type == CMD_SCSI)
2014                                         complete_scsi_command(c, 0, a1);
2015 #                               endif
2016                                 continue;
2017                         }
2018                 }
2019         }
2020
2021         /*
2022          * See if we can queue up some more IO
2023          */
2024         blk_start_queue(&h->queue);
2025         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
2026         return IRQ_HANDLED;
2027 }
2028 /* 
2029  *  We cannot read the structure directly, for portablity we must use 
2030  *   the io functions.
2031  *   This is for debug only. 
2032  */
2033 #ifdef CCISS_DEBUG
2034 static void print_cfg_table( CfgTable_struct *tb)
2035 {
2036         int i;
2037         char temp_name[17];
2038
2039         printk("Controller Configuration information\n");
2040         printk("------------------------------------\n");
2041         for(i=0;i<4;i++)
2042                 temp_name[i] = readb(&(tb->Signature[i]));
2043         temp_name[4]='\0';
2044         printk("   Signature = %s\n", temp_name); 
2045         printk("   Spec Number = %d\n", readl(&(tb->SpecValence)));
2046         printk("   Transport methods supported = 0x%x\n", 
2047                                 readl(&(tb-> TransportSupport)));
2048         printk("   Transport methods active = 0x%x\n", 
2049                                 readl(&(tb->TransportActive)));
2050         printk("   Requested transport Method = 0x%x\n", 
2051                         readl(&(tb->HostWrite.TransportRequest)));
2052         printk("   Coalese Interrupt Delay = 0x%x\n", 
2053                         readl(&(tb->HostWrite.CoalIntDelay)));
2054         printk("   Coalese Interrupt Count = 0x%x\n", 
2055                         readl(&(tb->HostWrite.CoalIntCount)));
2056         printk("   Max outstanding commands = 0x%d\n", 
2057                         readl(&(tb->CmdsOutMax)));
2058         printk("   Bus Types = 0x%x\n", readl(&(tb-> BusTypes)));
2059         for(i=0;i<16;i++)
2060                 temp_name[i] = readb(&(tb->ServerName[i]));
2061         temp_name[16] = '\0';
2062         printk("   Server Name = %s\n", temp_name);
2063         printk("   Heartbeat Counter = 0x%x\n\n\n", 
2064                         readl(&(tb->HeartBeat)));
2065 }
2066 #endif /* CCISS_DEBUG */ 
2067
2068 static void release_io_mem(ctlr_info_t *c)
2069 {
2070         /* if IO mem was not protected do nothing */
2071         if( c->io_mem_addr == 0)
2072                 return;
2073         release_region(c->io_mem_addr, c->io_mem_length);
2074         c->io_mem_addr = 0;
2075         c->io_mem_length = 0;
2076 }
2077 static int cciss_pci_init(ctlr_info_t *c, struct pci_dev *pdev)
2078 {
2079         ushort vendor_id, device_id, command;
2080         unchar cache_line_size, latency_timer;
2081         unchar irq, revision;
2082         uint addr[6];
2083         __u32 board_id, scratchpad = 0;
2084         int cfg_offset;
2085         int cfg_base_addr;
2086         int cfg_base_addr_index;
2087         int i;
2088
2089         if (pci_enable_device(pdev))
2090         {
2091                 printk(KERN_ERR "cciss: Unable to Enable PCI device\n");
2092                 return( -1);
2093         }
2094         if (pci_set_dma_mask(pdev, CCISS_DMA_MASK ) != 0)
2095         {
2096                 printk(KERN_ERR "cciss:  Unable to set DMA mask\n");
2097                 return(-1);
2098         }
2099
2100         vendor_id = pdev->vendor;
2101         device_id = pdev->device;
2102         irq = pdev->irq;
2103
2104         for(i=0; i<6; i++)
2105                 addr[i] = pdev->resource[i].start;
2106
2107         (void) pci_read_config_word(pdev, PCI_COMMAND,&command);
2108         (void) pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
2109         (void) pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE,
2110                                                 &cache_line_size);
2111         (void) pci_read_config_byte(pdev, PCI_LATENCY_TIMER,
2112                                                 &latency_timer);
2113         (void) pci_read_config_dword(pdev, PCI_SUBSYSTEM_VENDOR_ID, 
2114                                                 &board_id);
2115
2116         /* check to see if controller has been disabled */
2117         if(!(command & 0x02))
2118         {
2119                 printk(KERN_WARNING "cciss: controller appears to be disabled\n");
2120                 return(-1);
2121         }
2122
2123         /* search for our IO range so we can protect it */
2124         for(i=0; i<6; i++)
2125         {
2126                 /* is this an IO range */ 
2127                 if( pdev->resource[i].flags & 0x01 )
2128                 {
2129                         c->io_mem_addr = pdev->resource[i].start;
2130                         c->io_mem_length = pdev->resource[i].end -
2131                                 pdev->resource[i].start +1; 
2132 #ifdef CCISS_DEBUG
2133                         printk("IO value found base_addr[%d] %lx %lx\n", i,
2134                                 c->io_mem_addr, c->io_mem_length);
2135 #endif /* CCISS_DEBUG */
2136                         /* register the IO range */ 
2137                         if(!request_region( c->io_mem_addr,
2138                                         c->io_mem_length, "cciss"))
2139                         {
2140                                 printk(KERN_WARNING "cciss I/O memory range already in use addr=%lx length=%ld\n",
2141                                 c->io_mem_addr, c->io_mem_length);
2142                                 c->io_mem_addr= 0;
2143                                 c->io_mem_length = 0;
2144                         } 
2145                         break;
2146                 }
2147         }
2148
2149 #ifdef CCISS_DEBUG
2150         printk("vendor_id = %x\n", vendor_id);
2151         printk("device_id = %x\n", device_id);
2152         printk("command = %x\n", command);
2153         for(i=0; i<6; i++)
2154                 printk("addr[%d] = %x\n", i, addr[i]);
2155         printk("revision = %x\n", revision);
2156         printk("irq = %x\n", irq);
2157         printk("cache_line_size = %x\n", cache_line_size);
2158         printk("latency_timer = %x\n", latency_timer);
2159         printk("board_id = %x\n", board_id);
2160 #endif /* CCISS_DEBUG */ 
2161
2162         c->intr = irq;
2163
2164         /*
2165          * Memory base addr is first addr , the second points to the config
2166          *   table
2167          */
2168
2169         c->paddr = addr[0] ; /* addressing mode bits already removed */
2170 #ifdef CCISS_DEBUG
2171         printk("address 0 = %x\n", c->paddr);
2172 #endif /* CCISS_DEBUG */ 
2173         c->vaddr = remap_pci_mem(c->paddr, 200);
2174
2175         /* Wait for the board to become ready.  (PCI hotplug needs this.)
2176          * We poll for up to 120 secs, once per 100ms. */
2177         for (i=0; i < 1200; i++) {
2178                 scratchpad = readl(c->vaddr + SA5_SCRATCHPAD_OFFSET);
2179                 if (scratchpad == CCISS_FIRMWARE_READY)
2180                         break;
2181                 set_current_state(TASK_INTERRUPTIBLE);
2182                 schedule_timeout(HZ / 10); /* wait 100ms */
2183         }
2184         if (scratchpad != CCISS_FIRMWARE_READY) {
2185                 printk(KERN_WARNING "cciss: Board not ready.  Timed out.\n");
2186                 return -1;
2187         }
2188
2189         /* get the address index number */
2190         cfg_base_addr = readl(c->vaddr + SA5_CTCFG_OFFSET);
2191         /* I am not prepared to deal with a 64 bit address value */
2192         cfg_base_addr &= 0xffff;
2193 #ifdef CCISS_DEBUG
2194         printk("cfg base address = %x\n", cfg_base_addr);
2195 #endif /* CCISS_DEBUG */
2196         cfg_base_addr_index = (cfg_base_addr  - PCI_BASE_ADDRESS_0)/4;
2197 #ifdef CCISS_DEBUG
2198         printk("cfg base address index = %x\n", cfg_base_addr_index);
2199 #endif /* CCISS_DEBUG */
2200
2201         cfg_offset = readl(c->vaddr + SA5_CTMEM_OFFSET);
2202 #ifdef CCISS_DEBUG
2203         printk("cfg offset = %x\n", cfg_offset);
2204 #endif /* CCISS_DEBUG */
2205         c->cfgtable = (CfgTable_struct *) 
2206                 remap_pci_mem((addr[cfg_base_addr_index] & 0xfffffff0)
2207                                 + cfg_offset, sizeof(CfgTable_struct));
2208         c->board_id = board_id;
2209
2210 #ifdef CCISS_DEBUG
2211         print_cfg_table(c->cfgtable); 
2212 #endif /* CCISS_DEBUG */
2213
2214         for(i=0; i<NR_PRODUCTS; i++) {
2215                 if (board_id == products[i].board_id) {
2216                         c->product_name = products[i].product_name;
2217                         c->access = *(products[i].access);
2218                         break;
2219                 }
2220         }
2221         if (i == NR_PRODUCTS) {
2222                 printk(KERN_WARNING "cciss: Sorry, I don't know how"
2223                         " to access the Smart Array controller %08lx\n", 
2224                                 (unsigned long)board_id);
2225                 return -1;
2226         }
2227         if (  (readb(&c->cfgtable->Signature[0]) != 'C') ||
2228               (readb(&c->cfgtable->Signature[1]) != 'I') ||
2229               (readb(&c->cfgtable->Signature[2]) != 'S') ||
2230               (readb(&c->cfgtable->Signature[3]) != 'S') )
2231         {
2232                 printk("Does not appear to be a valid CISS config table\n");
2233                 return -1;
2234         }
2235 #ifdef CCISS_DEBUG
2236         printk("Trying to put board into Simple mode\n");
2237 #endif /* CCISS_DEBUG */ 
2238         c->max_commands = readl(&(c->cfgtable->CmdsOutMax));
2239         /* Update the field, and then ring the doorbell */ 
2240         writel( CFGTBL_Trans_Simple, 
2241                 &(c->cfgtable->HostWrite.TransportRequest));
2242         writel( CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
2243
2244         /* under certain very rare conditions, this can take awhile.
2245          * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
2246          * as we enter this code.) */
2247         for(i=0;i<MAX_CONFIG_WAIT;i++) {
2248                 if (!(readl(c->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
2249                         break;
2250                 /* delay and try again */
2251                 set_current_state(TASK_INTERRUPTIBLE);
2252                 schedule_timeout(10);
2253         }       
2254
2255 #ifdef CCISS_DEBUG
2256         printk(KERN_DEBUG "I counter got to %d %x\n", i, readl(c->vaddr + SA5_DOORBELL));
2257 #endif /* CCISS_DEBUG */
2258 #ifdef CCISS_DEBUG
2259         print_cfg_table(c->cfgtable);   
2260 #endif /* CCISS_DEBUG */ 
2261
2262         if (!(readl(&(c->cfgtable->TransportActive)) & CFGTBL_Trans_Simple))
2263         {
2264                 printk(KERN_WARNING "cciss: unable to get board into"
2265                                         " simple mode\n");
2266                 return -1;
2267         }
2268         return 0;
2269
2270 }
2271
2272 /* 
2273  * Gets information about the local volumes attached to the controller. 
2274  */ 
2275 static void cciss_getgeometry(int cntl_num)
2276 {
2277         ReportLunData_struct *ld_buff;
2278         ReadCapdata_struct *size_buff;
2279         InquiryData_struct *inq_buff;
2280         int return_code;
2281         int i;
2282         int listlength = 0;
2283         __u32 lunid = 0;
2284         int block_size;
2285         int total_size; 
2286
2287         ld_buff = kmalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
2288         if (ld_buff == NULL)
2289         {
2290                 printk(KERN_ERR "cciss: out of memory\n");
2291                 return;
2292         }
2293         memset(ld_buff, 0, sizeof(ReportLunData_struct));
2294         size_buff = kmalloc(sizeof( ReadCapdata_struct), GFP_KERNEL);
2295         if (size_buff == NULL)
2296         {
2297                 printk(KERN_ERR "cciss: out of memory\n");
2298                 kfree(ld_buff);
2299                 return;
2300         }
2301         inq_buff = kmalloc(sizeof( InquiryData_struct), GFP_KERNEL);
2302         if (inq_buff == NULL)
2303         {
2304                 printk(KERN_ERR "cciss: out of memory\n");
2305                 kfree(ld_buff);
2306                 kfree(size_buff);
2307                 return;
2308         }
2309         /* Get the firmware version */ 
2310         return_code = sendcmd(CISS_INQUIRY, cntl_num, inq_buff, 
2311                 sizeof(InquiryData_struct), 0, 0 ,0, NULL, TYPE_CMD);
2312         if (return_code == IO_OK)
2313         {
2314                 hba[cntl_num]->firm_ver[0] = inq_buff->data_byte[32];
2315                 hba[cntl_num]->firm_ver[1] = inq_buff->data_byte[33];
2316                 hba[cntl_num]->firm_ver[2] = inq_buff->data_byte[34];
2317                 hba[cntl_num]->firm_ver[3] = inq_buff->data_byte[35];
2318         } else /* send command failed */
2319         {
2320                 printk(KERN_WARNING "cciss: unable to determine firmware"
2321                         " version of controller\n");
2322         }
2323         /* Get the number of logical volumes */ 
2324         return_code = sendcmd(CISS_REPORT_LOG, cntl_num, ld_buff, 
2325                         sizeof(ReportLunData_struct), 0, 0, 0, NULL, TYPE_CMD);
2326
2327         if( return_code == IO_OK)
2328         {
2329 #ifdef CCISS_DEBUG
2330                 printk("LUN Data\n--------------------------\n");
2331 #endif /* CCISS_DEBUG */ 
2332
2333                 listlength |= (0xff & (unsigned int)(ld_buff->LUNListLength[0])) << 24;
2334                 listlength |= (0xff & (unsigned int)(ld_buff->LUNListLength[1])) << 16;
2335                 listlength |= (0xff & (unsigned int)(ld_buff->LUNListLength[2])) << 8;  
2336                 listlength |= 0xff & (unsigned int)(ld_buff->LUNListLength[3]);
2337         } else /* reading number of logical volumes failed */
2338         {
2339                 printk(KERN_WARNING "cciss: report logical volume"
2340                         " command failed\n");
2341                 listlength = 0;
2342         }
2343         hba[cntl_num]->num_luns = listlength / 8; // 8 bytes pre entry
2344         if (hba[cntl_num]->num_luns > CISS_MAX_LUN)
2345         {
2346                 printk(KERN_ERR "ciss:  only %d number of logical volumes supported\n",
2347                         CISS_MAX_LUN);
2348                 hba[cntl_num]->num_luns = CISS_MAX_LUN;
2349         }
2350 #ifdef CCISS_DEBUG
2351         printk(KERN_DEBUG "Length = %x %x %x %x = %d\n", ld_buff->LUNListLength[0],
2352                 ld_buff->LUNListLength[1], ld_buff->LUNListLength[2],
2353                 ld_buff->LUNListLength[3],  hba[cntl_num]->num_luns);
2354 #endif /* CCISS_DEBUG */
2355
2356         hba[cntl_num]->highest_lun = hba[cntl_num]->num_luns-1;
2357         for(i=0; i<  hba[cntl_num]->num_luns; i++)
2358         {
2359
2360                 lunid = (0xff & (unsigned int)(ld_buff->LUN[i][3])) << 24;
2361                 lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][2])) << 16;
2362                 lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][1])) << 8;
2363                 lunid |= 0xff & (unsigned int)(ld_buff->LUN[i][0]);
2364                 
2365                 hba[cntl_num]->drv[i].LunID = lunid;
2366
2367
2368 #ifdef CCISS_DEBUG
2369                 printk(KERN_DEBUG "LUN[%d]:  %x %x %x %x = %x\n", i, 
2370                 ld_buff->LUN[i][0], ld_buff->LUN[i][1],ld_buff->LUN[i][2], 
2371                 ld_buff->LUN[i][3], hba[cntl_num]->drv[i].LunID);
2372 #endif /* CCISS_DEBUG */
2373                 cciss_read_capacity(cntl_num, i, size_buff, 0,
2374                         &total_size, &block_size);
2375                 cciss_geometry_inquiry(cntl_num, i, 0, total_size, block_size,
2376                         inq_buff, &hba[cntl_num]->drv[i]);
2377         }
2378         kfree(ld_buff);
2379         kfree(size_buff);
2380         kfree(inq_buff);
2381 }       
2382
2383 /* Function to find the first free pointer into our hba[] array */
2384 /* Returns -1 if no free entries are left.  */
2385 static int alloc_cciss_hba(void)
2386 {
2387         struct gendisk *disk[NWD];
2388         int i, n;
2389         for (n = 0; n < NWD; n++) {
2390                 disk[n] = alloc_disk(1 << NWD_SHIFT);
2391                 if (!disk[n])
2392                         goto out;
2393         }
2394
2395         for(i=0; i< MAX_CTLR; i++) {
2396                 if (!hba[i]) {
2397                         ctlr_info_t *p;
2398                         p = kmalloc(sizeof(ctlr_info_t), GFP_KERNEL);
2399                         if (!p)
2400                                 goto Enomem;
2401                         memset(p, 0, sizeof(ctlr_info_t));
2402                         for (n = 0; n < NWD; n++)
2403                                 p->gendisk[n] = disk[n];
2404                         hba[i] = p;
2405                         return i;
2406                 }
2407         }
2408         printk(KERN_WARNING "cciss: This driver supports a maximum"
2409                 " of 8 controllers.\n");
2410         goto out;
2411 Enomem:
2412         printk(KERN_ERR "cciss: out of memory.\n");
2413 out:
2414         while (n--)
2415                 put_disk(disk[n]);
2416         return -1;
2417 }
2418
2419 static void free_hba(int i)
2420 {
2421         ctlr_info_t *p = hba[i];
2422         int n;
2423
2424         hba[i] = NULL;
2425         for (n = 0; n < NWD; n++)
2426                 put_disk(p->gendisk[n]);
2427         kfree(p);
2428 }
2429
2430 /*
2431  *  This is it.  Find all the controllers and register them.  I really hate
2432  *  stealing all these major device numbers.
2433  *  returns the number of block devices registered.
2434  */
2435 static int __init cciss_init_one(struct pci_dev *pdev,
2436         const struct pci_device_id *ent)
2437 {
2438         request_queue_t *q;
2439         int i;
2440         int j;
2441
2442         printk(KERN_DEBUG "cciss: Device 0x%x has been found at"
2443                         " bus %d dev %d func %d\n",
2444                 pdev->device, pdev->bus->number, PCI_SLOT(pdev->devfn),
2445                         PCI_FUNC(pdev->devfn));
2446         i = alloc_cciss_hba();
2447         if( i < 0 ) 
2448                 return (-1);
2449         if (cciss_pci_init(hba[i], pdev) != 0)
2450         {
2451                 release_io_mem(hba[i]);
2452                 free_hba(i);
2453                 return (-1);
2454         }
2455         sprintf(hba[i]->devname, "cciss%d", i);
2456         hba[i]->ctlr = i;
2457         hba[i]->pdev = pdev;
2458
2459         /* configure PCI DMA stuff */
2460         if (!pci_set_dma_mask(pdev, (u64) 0xffffffffffffffff))
2461                 printk("cciss: using DAC cycles\n");
2462         else if (!pci_set_dma_mask(pdev, 0xffffffff))
2463                 printk("cciss: not using DAC cycles\n");
2464         else {
2465                 printk("cciss: no suitable DMA available\n");
2466                 free_hba(i);
2467                 return -ENODEV;
2468         }
2469
2470         if (register_blkdev(COMPAQ_CISS_MAJOR+i, hba[i]->devname)) {
2471                 release_io_mem(hba[i]);
2472                 free_hba(i);
2473                 return -1;
2474         }
2475
2476         /* make sure the board interrupts are off */
2477         hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_OFF);
2478         if( request_irq(hba[i]->intr, do_cciss_intr, 
2479                 SA_INTERRUPT | SA_SHIRQ | SA_SAMPLE_RANDOM, 
2480                         hba[i]->devname, hba[i]))
2481         {
2482                 printk(KERN_ERR "ciss: Unable to get irq %d for %s\n",
2483                         hba[i]->intr, hba[i]->devname);
2484                 unregister_blkdev( COMPAQ_CISS_MAJOR+i, hba[i]->devname);
2485                 release_io_mem(hba[i]);
2486                 free_hba(i);
2487                 return(-1);
2488         }
2489         hba[i]->cmd_pool_bits = kmalloc(((NR_CMDS+BITS_PER_LONG-1)/BITS_PER_LONG)*sizeof(unsigned long), GFP_KERNEL);
2490         hba[i]->cmd_pool = (CommandList_struct *)pci_alloc_consistent(
2491                 hba[i]->pdev, NR_CMDS * sizeof(CommandList_struct), 
2492                 &(hba[i]->cmd_pool_dhandle));
2493         hba[i]->errinfo_pool = (ErrorInfo_struct *)pci_alloc_consistent(
2494                 hba[i]->pdev, NR_CMDS * sizeof( ErrorInfo_struct), 
2495                 &(hba[i]->errinfo_pool_dhandle));
2496         if((hba[i]->cmd_pool_bits == NULL) 
2497                 || (hba[i]->cmd_pool == NULL)
2498                 || (hba[i]->errinfo_pool == NULL))
2499         {
2500                 if(hba[i]->cmd_pool_bits)
2501                         kfree(hba[i]->cmd_pool_bits);
2502                 if(hba[i]->cmd_pool)
2503                         pci_free_consistent(hba[i]->pdev,  
2504                                 NR_CMDS * sizeof(CommandList_struct), 
2505                                 hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);    
2506                 if(hba[i]->errinfo_pool)
2507                         pci_free_consistent(hba[i]->pdev,
2508                                 NR_CMDS * sizeof( ErrorInfo_struct),
2509                                 hba[i]->errinfo_pool, 
2510                                 hba[i]->errinfo_pool_dhandle);
2511                 free_irq(hba[i]->intr, hba[i]);
2512                 unregister_blkdev(COMPAQ_CISS_MAJOR+i, hba[i]->devname);
2513                 release_io_mem(hba[i]);
2514                 free_hba(i);
2515                 printk( KERN_ERR "cciss: out of memory");
2516                 return(-1);
2517         }
2518
2519         /* Initialize the pdev driver private data. 
2520                 have it point to hba[i].  */
2521         pci_set_drvdata(pdev, hba[i]);
2522         /* command and error info recs zeroed out before 
2523                         they are used */
2524         memset(hba[i]->cmd_pool_bits, 0, ((NR_CMDS+BITS_PER_LONG-1)/BITS_PER_LONG)*sizeof(unsigned long));
2525
2526 #ifdef CCISS_DEBUG      
2527         printk(KERN_DEBUG "Scanning for drives on controller cciss%d\n",i);
2528 #endif /* CCISS_DEBUG */
2529
2530         cciss_getgeometry(i);
2531
2532         cciss_scsi_setup(i);
2533
2534         /* Turn the interrupts on so we can service requests */
2535         hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_ON);
2536
2537         cciss_procinit(i);
2538
2539         q = &hba[i]->queue;
2540         q->queuedata = hba[i];
2541         spin_lock_init(&hba[i]->lock);
2542         blk_init_queue(q, do_cciss_request, &hba[i]->lock);
2543         blk_queue_bounce_limit(q, hba[i]->pdev->dma_mask);
2544
2545         /* This is a hardware imposed limit. */
2546         blk_queue_max_hw_segments(q, MAXSGENTRIES);
2547
2548         /* This is a limit in the driver and could be eliminated. */
2549         blk_queue_max_phys_segments(q, MAXSGENTRIES);
2550
2551         blk_queue_max_sectors(q, 512);
2552
2553
2554         for(j=0; j<NWD; j++) {
2555                 drive_info_struct *drv = &(hba[i]->drv[j]);
2556                 struct gendisk *disk = hba[i]->gendisk[j];
2557
2558                 sprintf(disk->disk_name, "cciss/c%dd%d", i, j);
2559                 disk->major = COMPAQ_CISS_MAJOR + i;
2560                 disk->first_minor = j << NWD_SHIFT;
2561                 disk->fops = &cciss_fops;
2562                 disk->queue = &hba[i]->queue;
2563                 disk->private_data = drv;
2564                 if( !(drv->nr_blocks))
2565                         continue;
2566                 hba[i]->queue.hardsect_size = drv->block_size;
2567                 set_capacity(disk, drv->nr_blocks);
2568                 add_disk(disk);
2569         }
2570         return(1);
2571 }
2572
2573 static void __devexit cciss_remove_one (struct pci_dev *pdev)
2574 {
2575         ctlr_info_t *tmp_ptr;
2576         int i, j;
2577         char flush_buf[4];
2578         int return_code; 
2579
2580         if (pci_get_drvdata(pdev) == NULL)
2581         {
2582                 printk( KERN_ERR "cciss: Unable to remove device \n");
2583                 return;
2584         }
2585         tmp_ptr = pci_get_drvdata(pdev);
2586         i = tmp_ptr->ctlr;
2587         if (hba[i] == NULL) 
2588         {
2589                 printk(KERN_ERR "cciss: device appears to "
2590                         "already be removed \n");
2591                 return;
2592         }
2593         /* Turn board interrupts off  and send the flush cache command */
2594         /* sendcmd will turn off interrupt, and send the flush...
2595         * To write all data in the battery backed cache to disks */
2596         memset(flush_buf, 0, 4);
2597         return_code = sendcmd(CCISS_CACHE_FLUSH, i, flush_buf, 4, 0, 0, 0, NULL,
2598                                 TYPE_CMD);
2599         if(return_code != IO_OK)
2600         {
2601                 printk(KERN_WARNING "Error Flushing cache on controller %d\n", 
2602                         i);
2603         }
2604         free_irq(hba[i]->intr, hba[i]);
2605         pci_set_drvdata(pdev, NULL);
2606         iounmap((void*)hba[i]->vaddr);
2607         cciss_unregister_scsi(i);  /* unhook from SCSI subsystem */
2608         unregister_blkdev(COMPAQ_CISS_MAJOR+i, hba[i]->devname);
2609         remove_proc_entry(hba[i]->devname, proc_cciss); 
2610         
2611         /* remove it from the disk list */
2612         for (j = 0; j < NWD; j++) {
2613                 struct gendisk *disk = hba[i]->gendisk[j];
2614                 if (disk->flags & GENHD_FL_UP)
2615                         del_gendisk(disk);
2616         }
2617
2618         pci_free_consistent(hba[i]->pdev, NR_CMDS * sizeof(CommandList_struct),
2619                             hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
2620         pci_free_consistent(hba[i]->pdev, NR_CMDS * sizeof( ErrorInfo_struct),
2621                 hba[i]->errinfo_pool, hba[i]->errinfo_pool_dhandle);
2622         kfree(hba[i]->cmd_pool_bits);
2623         release_io_mem(hba[i]);
2624         free_hba(i);
2625 }       
2626
2627 static struct pci_driver cciss_pci_driver = {
2628         .name =         "cciss",
2629         .probe =        cciss_init_one,
2630         .remove =       __devexit_p(cciss_remove_one),
2631         .id_table =     cciss_pci_device_id, /* id_table */
2632 };
2633
2634 /*
2635  *  This is it.  Register the PCI driver information for the cards we control
2636  *  the OS will call our registered routines when it finds one of our cards. 
2637  */
2638 int __init cciss_init(void)
2639 {
2640         printk(KERN_INFO DRIVER_NAME "\n");
2641
2642         /* Register for our PCI devices */
2643         return pci_register_driver(&cciss_pci_driver);
2644 }
2645
2646 static int __init init_cciss_module(void)
2647 {
2648         return ( cciss_init());
2649 }
2650
2651 static void __exit cleanup_cciss_module(void)
2652 {
2653         int i;
2654
2655         pci_unregister_driver(&cciss_pci_driver);
2656         /* double check that all controller entrys have been removed */
2657         for (i=0; i< MAX_CTLR; i++) 
2658         {
2659                 if (hba[i] != NULL)
2660                 {
2661                         printk(KERN_WARNING "cciss: had to remove"
2662                                         " controller %d\n", i);
2663                         cciss_remove_one(hba[i]->pdev);
2664                 }
2665         }
2666         remove_proc_entry("cciss", proc_root_driver);
2667 }
2668
2669 module_init(init_cciss_module);
2670 module_exit(cleanup_cciss_module);