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