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