04036ef8ea5a206b2c850be6855ebfff65016e43
[safe/jmp/linux-2.6] / drivers / block / cciss.c
1 /*
2  *    Disk Array driver for HP Smart Array controllers.
3  *    (C) Copyright 2000, 2007 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; version 2 of the License.
8  *
9  *    This program is distributed in the hope that it will be useful,
10  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  *    General Public License for more details.
13  *
14  *    You should have received a copy of the GNU General Public License
15  *    along with this program; if not, write to the Free Software
16  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17  *    02111-1307, USA.
18  *
19  *    Questions/Comments/Bugfixes to iss_storagedev@hp.com
20  *
21  */
22
23 #include <linux/module.h>
24 #include <linux/interrupt.h>
25 #include <linux/types.h>
26 #include <linux/pci.h>
27 #include <linux/kernel.h>
28 #include <linux/slab.h>
29 #include <linux/smp_lock.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/seq_file.h>
38 #include <linux/init.h>
39 #include <linux/jiffies.h>
40 #include <linux/hdreg.h>
41 #include <linux/spinlock.h>
42 #include <linux/compat.h>
43 #include <linux/mutex.h>
44 #include <asm/uaccess.h>
45 #include <asm/io.h>
46
47 #include <linux/dma-mapping.h>
48 #include <linux/blkdev.h>
49 #include <linux/genhd.h>
50 #include <linux/completion.h>
51 #include <scsi/scsi.h>
52 #include <scsi/sg.h>
53 #include <scsi/scsi_ioctl.h>
54 #include <linux/cdrom.h>
55 #include <linux/scatterlist.h>
56 #include <linux/kthread.h>
57
58 #define CCISS_DRIVER_VERSION(maj,min,submin) ((maj<<16)|(min<<8)|(submin))
59 #define DRIVER_NAME "HP CISS Driver (v 3.6.20)"
60 #define DRIVER_VERSION CCISS_DRIVER_VERSION(3, 6, 20)
61
62 /* Embedded module documentation macros - see modules.h */
63 MODULE_AUTHOR("Hewlett-Packard Company");
64 MODULE_DESCRIPTION("Driver for HP Smart Array Controllers");
65 MODULE_SUPPORTED_DEVICE("HP SA5i SA5i+ SA532 SA5300 SA5312 SA641 SA642 SA6400"
66                         " SA6i P600 P800 P400 P400i E200 E200i E500 P700m"
67                         " Smart Array G2 Series SAS/SATA Controllers");
68 MODULE_VERSION("3.6.20");
69 MODULE_LICENSE("GPL");
70
71 #include "cciss_cmd.h"
72 #include "cciss.h"
73 #include <linux/cciss_ioctl.h>
74
75 /* define the PCI info for the cards we can control */
76 static const struct pci_device_id cciss_pci_device_id[] = {
77         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISS,  0x0E11, 0x4070},
78         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4080},
79         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4082},
80         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4083},
81         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x4091},
82         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409A},
83         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409B},
84         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409C},
85         {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409D},
86         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSA,     0x103C, 0x3225},
87         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3223},
88         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3234},
89         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3235},
90         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3211},
91         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3212},
92         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3213},
93         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3214},
94         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3215},
95         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3237},
96         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x323D},
97         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3241},
98         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3243},
99         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3245},
100         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3247},
101         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3249},
102         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324A},
103         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324B},
104         {PCI_VENDOR_ID_HP,     PCI_ANY_ID,      PCI_ANY_ID, PCI_ANY_ID,
105                 PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
106         {0,}
107 };
108
109 MODULE_DEVICE_TABLE(pci, cciss_pci_device_id);
110
111 /*  board_id = Subsystem Device ID & Vendor ID
112  *  product = Marketing Name for the board
113  *  access = Address of the struct of function pointers
114  */
115 static struct board_type products[] = {
116         {0x40700E11, "Smart Array 5300", &SA5_access},
117         {0x40800E11, "Smart Array 5i", &SA5B_access},
118         {0x40820E11, "Smart Array 532", &SA5B_access},
119         {0x40830E11, "Smart Array 5312", &SA5B_access},
120         {0x409A0E11, "Smart Array 641", &SA5_access},
121         {0x409B0E11, "Smart Array 642", &SA5_access},
122         {0x409C0E11, "Smart Array 6400", &SA5_access},
123         {0x409D0E11, "Smart Array 6400 EM", &SA5_access},
124         {0x40910E11, "Smart Array 6i", &SA5_access},
125         {0x3225103C, "Smart Array P600", &SA5_access},
126         {0x3223103C, "Smart Array P800", &SA5_access},
127         {0x3234103C, "Smart Array P400", &SA5_access},
128         {0x3235103C, "Smart Array P400i", &SA5_access},
129         {0x3211103C, "Smart Array E200i", &SA5_access},
130         {0x3212103C, "Smart Array E200", &SA5_access},
131         {0x3213103C, "Smart Array E200i", &SA5_access},
132         {0x3214103C, "Smart Array E200i", &SA5_access},
133         {0x3215103C, "Smart Array E200i", &SA5_access},
134         {0x3237103C, "Smart Array E500", &SA5_access},
135         {0x323D103C, "Smart Array P700m", &SA5_access},
136         {0x3241103C, "Smart Array P212", &SA5_access},
137         {0x3243103C, "Smart Array P410", &SA5_access},
138         {0x3245103C, "Smart Array P410i", &SA5_access},
139         {0x3247103C, "Smart Array P411", &SA5_access},
140         {0x3249103C, "Smart Array P812", &SA5_access},
141         {0x324A103C, "Smart Array P712m", &SA5_access},
142         {0x324B103C, "Smart Array P711m", &SA5_access},
143         {0xFFFF103C, "Unknown Smart Array", &SA5_access},
144 };
145
146 /* How long to wait (in milliseconds) for board to go into simple mode */
147 #define MAX_CONFIG_WAIT 30000
148 #define MAX_IOCTL_CONFIG_WAIT 1000
149
150 /*define how many times we will try a command because of bus resets */
151 #define MAX_CMD_RETRIES 3
152
153 #define MAX_CTLR        32
154
155 /* Originally cciss driver only supports 8 major numbers */
156 #define MAX_CTLR_ORIG   8
157
158 static ctlr_info_t *hba[MAX_CTLR];
159
160 static struct task_struct *cciss_scan_thread;
161 static DEFINE_MUTEX(scan_mutex);
162 static LIST_HEAD(scan_q);
163
164 static void do_cciss_request(struct request_queue *q);
165 static irqreturn_t do_cciss_intr(int irq, void *dev_id);
166 static int cciss_open(struct block_device *bdev, fmode_t mode);
167 static int cciss_release(struct gendisk *disk, fmode_t mode);
168 static int cciss_ioctl(struct block_device *bdev, fmode_t mode,
169                        unsigned int cmd, unsigned long arg);
170 static int cciss_getgeo(struct block_device *bdev, struct hd_geometry *geo);
171
172 static int cciss_revalidate(struct gendisk *disk);
173 static int rebuild_lun_table(ctlr_info_t *h, int first_time, int via_ioctl);
174 static int deregister_disk(ctlr_info_t *h, int drv_index,
175                            int clear_all, int via_ioctl);
176
177 static void cciss_read_capacity(int ctlr, int logvol, int withirq,
178                         sector_t *total_size, unsigned int *block_size);
179 static void cciss_read_capacity_16(int ctlr, int logvol, int withirq,
180                         sector_t *total_size, unsigned int *block_size);
181 static void cciss_geometry_inquiry(int ctlr, int logvol,
182                         int withirq, sector_t total_size,
183                         unsigned int block_size, InquiryData_struct *inq_buff,
184                                    drive_info_struct *drv);
185 static void __devinit cciss_interrupt_mode(ctlr_info_t *, struct pci_dev *,
186                                            __u32);
187 static void start_io(ctlr_info_t *h);
188 static int sendcmd(__u8 cmd, int ctlr, void *buff, size_t size,
189                    __u8 page_code, unsigned char *scsi3addr, int cmd_type);
190 static int sendcmd_withirq(__u8 cmd, int ctlr, void *buff, size_t size,
191                         __u8 page_code, unsigned char scsi3addr[],
192                         int cmd_type);
193 static int sendcmd_withirq_core(ctlr_info_t *h, CommandList_struct *c,
194         int attempt_retry);
195 static int process_sendcmd_error(ctlr_info_t *h, CommandList_struct *c);
196
197 static void fail_all_cmds(unsigned long ctlr);
198 static int add_to_scan_list(struct ctlr_info *h);
199 static int scan_thread(void *data);
200 static int check_for_unit_attention(ctlr_info_t *h, CommandList_struct *c);
201 static void cciss_hba_release(struct device *dev);
202 static void cciss_device_release(struct device *dev);
203 static void cciss_free_gendisk(ctlr_info_t *h, int drv_index);
204 static void cciss_free_drive_info(ctlr_info_t *h, int drv_index);
205
206 #ifdef CONFIG_PROC_FS
207 static void cciss_procinit(int i);
208 #else
209 static void cciss_procinit(int i)
210 {
211 }
212 #endif                          /* CONFIG_PROC_FS */
213
214 #ifdef CONFIG_COMPAT
215 static int cciss_compat_ioctl(struct block_device *, fmode_t,
216                               unsigned, unsigned long);
217 #endif
218
219 static const struct block_device_operations cciss_fops = {
220         .owner = THIS_MODULE,
221         .open = cciss_open,
222         .release = cciss_release,
223         .locked_ioctl = cciss_ioctl,
224         .getgeo = cciss_getgeo,
225 #ifdef CONFIG_COMPAT
226         .compat_ioctl = cciss_compat_ioctl,
227 #endif
228         .revalidate_disk = cciss_revalidate,
229 };
230
231 /*
232  * Enqueuing and dequeuing functions for cmdlists.
233  */
234 static inline void addQ(struct hlist_head *list, CommandList_struct *c)
235 {
236         hlist_add_head(&c->list, list);
237 }
238
239 static inline void removeQ(CommandList_struct *c)
240 {
241         /*
242          * After kexec/dump some commands might still
243          * be in flight, which the firmware will try
244          * to complete. Resetting the firmware doesn't work
245          * with old fw revisions, so we have to mark
246          * them off as 'stale' to prevent the driver from
247          * falling over.
248          */
249         if (WARN_ON(hlist_unhashed(&c->list))) {
250                 c->cmd_type = CMD_MSG_STALE;
251                 return;
252         }
253
254         hlist_del_init(&c->list);
255 }
256
257 #include "cciss_scsi.c"         /* For SCSI tape support */
258
259 #ifdef CONFIG_PROC_FS
260
261 /*
262  * Report information about this controller.
263  */
264 #define ENG_GIG 1000000000
265 #define ENG_GIG_FACTOR (ENG_GIG/512)
266 #define ENGAGE_SCSI     "engage scsi"
267 static const char *raid_label[] = { "0", "4", "1(1+0)", "5", "5+1", "ADG",
268         "UNKNOWN"
269 };
270 #define RAID_UNKNOWN (sizeof(raid_label) / sizeof(raid_label[0])-1)
271
272 static struct proc_dir_entry *proc_cciss;
273
274 static void cciss_seq_show_header(struct seq_file *seq)
275 {
276         ctlr_info_t *h = seq->private;
277
278         seq_printf(seq, "%s: HP %s Controller\n"
279                 "Board ID: 0x%08lx\n"
280                 "Firmware Version: %c%c%c%c\n"
281                 "IRQ: %d\n"
282                 "Logical drives: %d\n"
283                 "Current Q depth: %d\n"
284                 "Current # commands on controller: %d\n"
285                 "Max Q depth since init: %d\n"
286                 "Max # commands on controller since init: %d\n"
287                 "Max SG entries since init: %d\n",
288                 h->devname,
289                 h->product_name,
290                 (unsigned long)h->board_id,
291                 h->firm_ver[0], h->firm_ver[1], h->firm_ver[2],
292                 h->firm_ver[3], (unsigned int)h->intr[SIMPLE_MODE_INT],
293                 h->num_luns,
294                 h->Qdepth, h->commands_outstanding,
295                 h->maxQsinceinit, h->max_outstanding, h->maxSG);
296
297 #ifdef CONFIG_CISS_SCSI_TAPE
298         cciss_seq_tape_report(seq, h->ctlr);
299 #endif /* CONFIG_CISS_SCSI_TAPE */
300 }
301
302 static void *cciss_seq_start(struct seq_file *seq, loff_t *pos)
303 {
304         ctlr_info_t *h = seq->private;
305         unsigned ctlr = h->ctlr;
306         unsigned long flags;
307
308         /* prevent displaying bogus info during configuration
309          * or deconfiguration of a logical volume
310          */
311         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
312         if (h->busy_configuring) {
313                 spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
314                 return ERR_PTR(-EBUSY);
315         }
316         h->busy_configuring = 1;
317         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
318
319         if (*pos == 0)
320                 cciss_seq_show_header(seq);
321
322         return pos;
323 }
324
325 static int cciss_seq_show(struct seq_file *seq, void *v)
326 {
327         sector_t vol_sz, vol_sz_frac;
328         ctlr_info_t *h = seq->private;
329         unsigned ctlr = h->ctlr;
330         loff_t *pos = v;
331         drive_info_struct *drv = h->drv[*pos];
332
333         if (*pos > h->highest_lun)
334                 return 0;
335
336         if (drv->heads == 0)
337                 return 0;
338
339         vol_sz = drv->nr_blocks;
340         vol_sz_frac = sector_div(vol_sz, ENG_GIG_FACTOR);
341         vol_sz_frac *= 100;
342         sector_div(vol_sz_frac, ENG_GIG_FACTOR);
343
344         if (drv->raid_level < 0 || drv->raid_level > RAID_UNKNOWN)
345                 drv->raid_level = RAID_UNKNOWN;
346         seq_printf(seq, "cciss/c%dd%d:"
347                         "\t%4u.%02uGB\tRAID %s\n",
348                         ctlr, (int) *pos, (int)vol_sz, (int)vol_sz_frac,
349                         raid_label[drv->raid_level]);
350         return 0;
351 }
352
353 static void *cciss_seq_next(struct seq_file *seq, void *v, loff_t *pos)
354 {
355         ctlr_info_t *h = seq->private;
356
357         if (*pos > h->highest_lun)
358                 return NULL;
359         *pos += 1;
360
361         return pos;
362 }
363
364 static void cciss_seq_stop(struct seq_file *seq, void *v)
365 {
366         ctlr_info_t *h = seq->private;
367
368         /* Only reset h->busy_configuring if we succeeded in setting
369          * it during cciss_seq_start. */
370         if (v == ERR_PTR(-EBUSY))
371                 return;
372
373         h->busy_configuring = 0;
374 }
375
376 static const struct seq_operations cciss_seq_ops = {
377         .start = cciss_seq_start,
378         .show  = cciss_seq_show,
379         .next  = cciss_seq_next,
380         .stop  = cciss_seq_stop,
381 };
382
383 static int cciss_seq_open(struct inode *inode, struct file *file)
384 {
385         int ret = seq_open(file, &cciss_seq_ops);
386         struct seq_file *seq = file->private_data;
387
388         if (!ret)
389                 seq->private = PDE(inode)->data;
390
391         return ret;
392 }
393
394 static ssize_t
395 cciss_proc_write(struct file *file, const char __user *buf,
396                  size_t length, loff_t *ppos)
397 {
398         int err;
399         char *buffer;
400
401 #ifndef CONFIG_CISS_SCSI_TAPE
402         return -EINVAL;
403 #endif
404
405         if (!buf || length > PAGE_SIZE - 1)
406                 return -EINVAL;
407
408         buffer = (char *)__get_free_page(GFP_KERNEL);
409         if (!buffer)
410                 return -ENOMEM;
411
412         err = -EFAULT;
413         if (copy_from_user(buffer, buf, length))
414                 goto out;
415         buffer[length] = '\0';
416
417 #ifdef CONFIG_CISS_SCSI_TAPE
418         if (strncmp(ENGAGE_SCSI, buffer, sizeof ENGAGE_SCSI - 1) == 0) {
419                 struct seq_file *seq = file->private_data;
420                 ctlr_info_t *h = seq->private;
421                 int rc;
422
423                 rc = cciss_engage_scsi(h->ctlr);
424                 if (rc != 0)
425                         err = -rc;
426                 else
427                         err = length;
428         } else
429 #endif /* CONFIG_CISS_SCSI_TAPE */
430                 err = -EINVAL;
431         /* might be nice to have "disengage" too, but it's not
432            safely possible. (only 1 module use count, lock issues.) */
433
434 out:
435         free_page((unsigned long)buffer);
436         return err;
437 }
438
439 static struct file_operations cciss_proc_fops = {
440         .owner   = THIS_MODULE,
441         .open    = cciss_seq_open,
442         .read    = seq_read,
443         .llseek  = seq_lseek,
444         .release = seq_release,
445         .write   = cciss_proc_write,
446 };
447
448 static void __devinit cciss_procinit(int i)
449 {
450         struct proc_dir_entry *pde;
451
452         if (proc_cciss == NULL)
453                 proc_cciss = proc_mkdir("driver/cciss", NULL);
454         if (!proc_cciss)
455                 return;
456         pde = proc_create_data(hba[i]->devname, S_IWUSR | S_IRUSR | S_IRGRP |
457                                         S_IROTH, proc_cciss,
458                                         &cciss_proc_fops, hba[i]);
459 }
460 #endif                          /* CONFIG_PROC_FS */
461
462 #define MAX_PRODUCT_NAME_LEN 19
463
464 #define to_hba(n) container_of(n, struct ctlr_info, dev)
465 #define to_drv(n) container_of(n, drive_info_struct, dev)
466
467 static ssize_t host_store_rescan(struct device *dev,
468                                  struct device_attribute *attr,
469                                  const char *buf, size_t count)
470 {
471         struct ctlr_info *h = to_hba(dev);
472
473         add_to_scan_list(h);
474         wake_up_process(cciss_scan_thread);
475         wait_for_completion_interruptible(&h->scan_wait);
476
477         return count;
478 }
479 DEVICE_ATTR(rescan, S_IWUSR, NULL, host_store_rescan);
480
481 static ssize_t dev_show_unique_id(struct device *dev,
482                                  struct device_attribute *attr,
483                                  char *buf)
484 {
485         drive_info_struct *drv = to_drv(dev);
486         struct ctlr_info *h = to_hba(drv->dev.parent);
487         __u8 sn[16];
488         unsigned long flags;
489         int ret = 0;
490
491         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
492         if (h->busy_configuring)
493                 ret = -EBUSY;
494         else
495                 memcpy(sn, drv->serial_no, sizeof(sn));
496         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
497
498         if (ret)
499                 return ret;
500         else
501                 return snprintf(buf, 16 * 2 + 2,
502                                 "%02X%02X%02X%02X%02X%02X%02X%02X"
503                                 "%02X%02X%02X%02X%02X%02X%02X%02X\n",
504                                 sn[0], sn[1], sn[2], sn[3],
505                                 sn[4], sn[5], sn[6], sn[7],
506                                 sn[8], sn[9], sn[10], sn[11],
507                                 sn[12], sn[13], sn[14], sn[15]);
508 }
509 DEVICE_ATTR(unique_id, S_IRUGO, dev_show_unique_id, NULL);
510
511 static ssize_t dev_show_vendor(struct device *dev,
512                                struct device_attribute *attr,
513                                char *buf)
514 {
515         drive_info_struct *drv = to_drv(dev);
516         struct ctlr_info *h = to_hba(drv->dev.parent);
517         char vendor[VENDOR_LEN + 1];
518         unsigned long flags;
519         int ret = 0;
520
521         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
522         if (h->busy_configuring)
523                 ret = -EBUSY;
524         else
525                 memcpy(vendor, drv->vendor, VENDOR_LEN + 1);
526         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
527
528         if (ret)
529                 return ret;
530         else
531                 return snprintf(buf, sizeof(vendor) + 1, "%s\n", drv->vendor);
532 }
533 DEVICE_ATTR(vendor, S_IRUGO, dev_show_vendor, NULL);
534
535 static ssize_t dev_show_model(struct device *dev,
536                               struct device_attribute *attr,
537                               char *buf)
538 {
539         drive_info_struct *drv = to_drv(dev);
540         struct ctlr_info *h = to_hba(drv->dev.parent);
541         char model[MODEL_LEN + 1];
542         unsigned long flags;
543         int ret = 0;
544
545         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
546         if (h->busy_configuring)
547                 ret = -EBUSY;
548         else
549                 memcpy(model, drv->model, MODEL_LEN + 1);
550         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
551
552         if (ret)
553                 return ret;
554         else
555                 return snprintf(buf, sizeof(model) + 1, "%s\n", drv->model);
556 }
557 DEVICE_ATTR(model, S_IRUGO, dev_show_model, NULL);
558
559 static ssize_t dev_show_rev(struct device *dev,
560                             struct device_attribute *attr,
561                             char *buf)
562 {
563         drive_info_struct *drv = to_drv(dev);
564         struct ctlr_info *h = to_hba(drv->dev.parent);
565         char rev[REV_LEN + 1];
566         unsigned long flags;
567         int ret = 0;
568
569         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
570         if (h->busy_configuring)
571                 ret = -EBUSY;
572         else
573                 memcpy(rev, drv->rev, REV_LEN + 1);
574         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
575
576         if (ret)
577                 return ret;
578         else
579                 return snprintf(buf, sizeof(rev) + 1, "%s\n", drv->rev);
580 }
581 DEVICE_ATTR(rev, S_IRUGO, dev_show_rev, NULL);
582
583 static ssize_t cciss_show_lunid(struct device *dev,
584                                 struct device_attribute *attr, char *buf)
585 {
586         drive_info_struct *drv = to_drv(dev);
587         struct ctlr_info *h = to_hba(drv->dev.parent);
588         unsigned long flags;
589         unsigned char lunid[8];
590
591         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
592         if (h->busy_configuring) {
593                 spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
594                 return -EBUSY;
595         }
596         if (!drv->heads) {
597                 spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
598                 return -ENOTTY;
599         }
600         memcpy(lunid, drv->LunID, sizeof(lunid));
601         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
602         return snprintf(buf, 20, "0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
603                 lunid[0], lunid[1], lunid[2], lunid[3],
604                 lunid[4], lunid[5], lunid[6], lunid[7]);
605 }
606 DEVICE_ATTR(lunid, S_IRUGO, cciss_show_lunid, NULL);
607
608 static ssize_t cciss_show_raid_level(struct device *dev,
609                                      struct device_attribute *attr, char *buf)
610 {
611         drive_info_struct *drv = to_drv(dev);
612         struct ctlr_info *h = to_hba(drv->dev.parent);
613         int raid;
614         unsigned long flags;
615
616         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
617         if (h->busy_configuring) {
618                 spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
619                 return -EBUSY;
620         }
621         raid = drv->raid_level;
622         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
623         if (raid < 0 || raid > RAID_UNKNOWN)
624                 raid = RAID_UNKNOWN;
625
626         return snprintf(buf, strlen(raid_label[raid]) + 7, "RAID %s\n",
627                         raid_label[raid]);
628 }
629 DEVICE_ATTR(raid_level, S_IRUGO, cciss_show_raid_level, NULL);
630
631 static ssize_t cciss_show_usage_count(struct device *dev,
632                                       struct device_attribute *attr, char *buf)
633 {
634         drive_info_struct *drv = to_drv(dev);
635         struct ctlr_info *h = to_hba(drv->dev.parent);
636         unsigned long flags;
637         int count;
638
639         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
640         if (h->busy_configuring) {
641                 spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
642                 return -EBUSY;
643         }
644         count = drv->usage_count;
645         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
646         return snprintf(buf, 20, "%d\n", count);
647 }
648 DEVICE_ATTR(usage_count, S_IRUGO, cciss_show_usage_count, NULL);
649
650 static struct attribute *cciss_host_attrs[] = {
651         &dev_attr_rescan.attr,
652         NULL
653 };
654
655 static struct attribute_group cciss_host_attr_group = {
656         .attrs = cciss_host_attrs,
657 };
658
659 static struct attribute_group *cciss_host_attr_groups[] = {
660         &cciss_host_attr_group,
661         NULL
662 };
663
664 static struct device_type cciss_host_type = {
665         .name           = "cciss_host",
666         .groups         = cciss_host_attr_groups,
667         .release        = cciss_hba_release,
668 };
669
670 static struct attribute *cciss_dev_attrs[] = {
671         &dev_attr_unique_id.attr,
672         &dev_attr_model.attr,
673         &dev_attr_vendor.attr,
674         &dev_attr_rev.attr,
675         &dev_attr_lunid.attr,
676         &dev_attr_raid_level.attr,
677         &dev_attr_usage_count.attr,
678         NULL
679 };
680
681 static struct attribute_group cciss_dev_attr_group = {
682         .attrs = cciss_dev_attrs,
683 };
684
685 static const struct attribute_group *cciss_dev_attr_groups[] = {
686         &cciss_dev_attr_group,
687         NULL
688 };
689
690 static struct device_type cciss_dev_type = {
691         .name           = "cciss_device",
692         .groups         = cciss_dev_attr_groups,
693         .release        = cciss_device_release,
694 };
695
696 static struct bus_type cciss_bus_type = {
697         .name           = "cciss",
698 };
699
700 /*
701  * cciss_hba_release is called when the reference count
702  * of h->dev goes to zero.
703  */
704 static void cciss_hba_release(struct device *dev)
705 {
706         /*
707          * nothing to do, but need this to avoid a warning
708          * about not having a release handler from lib/kref.c.
709          */
710 }
711
712 /*
713  * Initialize sysfs entry for each controller.  This sets up and registers
714  * the 'cciss#' directory for each individual controller under
715  * /sys/bus/pci/devices/<dev>/.
716  */
717 static int cciss_create_hba_sysfs_entry(struct ctlr_info *h)
718 {
719         device_initialize(&h->dev);
720         h->dev.type = &cciss_host_type;
721         h->dev.bus = &cciss_bus_type;
722         dev_set_name(&h->dev, "%s", h->devname);
723         h->dev.parent = &h->pdev->dev;
724
725         return device_add(&h->dev);
726 }
727
728 /*
729  * Remove sysfs entries for an hba.
730  */
731 static void cciss_destroy_hba_sysfs_entry(struct ctlr_info *h)
732 {
733         device_del(&h->dev);
734         put_device(&h->dev); /* final put. */
735 }
736
737 /* cciss_device_release is called when the reference count
738  * of h->drv[x]dev goes to zero.
739  */
740 static void cciss_device_release(struct device *dev)
741 {
742         drive_info_struct *drv = to_drv(dev);
743         kfree(drv);
744 }
745
746 /*
747  * Initialize sysfs for each logical drive.  This sets up and registers
748  * the 'c#d#' directory for each individual logical drive under
749  * /sys/bus/pci/devices/<dev/ccis#/. We also create a link from
750  * /sys/block/cciss!c#d# to this entry.
751  */
752 static long cciss_create_ld_sysfs_entry(struct ctlr_info *h,
753                                        int drv_index)
754 {
755         struct device *dev;
756
757         if (h->drv[drv_index]->device_initialized)
758                 return 0;
759
760         dev = &h->drv[drv_index]->dev;
761         device_initialize(dev);
762         dev->type = &cciss_dev_type;
763         dev->bus = &cciss_bus_type;
764         dev_set_name(dev, "c%dd%d", h->ctlr, drv_index);
765         dev->parent = &h->dev;
766         h->drv[drv_index]->device_initialized = 1;
767         return device_add(dev);
768 }
769
770 /*
771  * Remove sysfs entries for a logical drive.
772  */
773 static void cciss_destroy_ld_sysfs_entry(struct ctlr_info *h, int drv_index,
774         int ctlr_exiting)
775 {
776         struct device *dev = &h->drv[drv_index]->dev;
777
778         /* special case for c*d0, we only destroy it on controller exit */
779         if (drv_index == 0 && !ctlr_exiting)
780                 return;
781
782         device_del(dev);
783         put_device(dev); /* the "final" put. */
784         h->drv[drv_index] = NULL;
785 }
786
787 /*
788  * For operations that cannot sleep, a command block is allocated at init,
789  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
790  * which ones are free or in use.  For operations that can wait for kmalloc
791  * to possible sleep, this routine can be called with get_from_pool set to 0.
792  * cmd_free() MUST be called with a got_from_pool set to 0 if cmd_alloc was.
793  */
794 static CommandList_struct *cmd_alloc(ctlr_info_t *h, int get_from_pool)
795 {
796         CommandList_struct *c;
797         int i;
798         u64bit temp64;
799         dma_addr_t cmd_dma_handle, err_dma_handle;
800
801         if (!get_from_pool) {
802                 c = (CommandList_struct *) pci_alloc_consistent(h->pdev,
803                         sizeof(CommandList_struct), &cmd_dma_handle);
804                 if (c == NULL)
805                         return NULL;
806                 memset(c, 0, sizeof(CommandList_struct));
807
808                 c->cmdindex = -1;
809
810                 c->err_info = (ErrorInfo_struct *)
811                     pci_alloc_consistent(h->pdev, sizeof(ErrorInfo_struct),
812                             &err_dma_handle);
813
814                 if (c->err_info == NULL) {
815                         pci_free_consistent(h->pdev,
816                                 sizeof(CommandList_struct), c, cmd_dma_handle);
817                         return NULL;
818                 }
819                 memset(c->err_info, 0, sizeof(ErrorInfo_struct));
820         } else {                /* get it out of the controllers pool */
821
822                 do {
823                         i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
824                         if (i == h->nr_cmds)
825                                 return NULL;
826                 } while (test_and_set_bit
827                          (i & (BITS_PER_LONG - 1),
828                           h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
829 #ifdef CCISS_DEBUG
830                 printk(KERN_DEBUG "cciss: using command buffer %d\n", i);
831 #endif
832                 c = h->cmd_pool + i;
833                 memset(c, 0, sizeof(CommandList_struct));
834                 cmd_dma_handle = h->cmd_pool_dhandle
835                     + i * sizeof(CommandList_struct);
836                 c->err_info = h->errinfo_pool + i;
837                 memset(c->err_info, 0, sizeof(ErrorInfo_struct));
838                 err_dma_handle = h->errinfo_pool_dhandle
839                     + i * sizeof(ErrorInfo_struct);
840                 h->nr_allocs++;
841
842                 c->cmdindex = i;
843         }
844
845         INIT_HLIST_NODE(&c->list);
846         c->busaddr = (__u32) cmd_dma_handle;
847         temp64.val = (__u64) err_dma_handle;
848         c->ErrDesc.Addr.lower = temp64.val32.lower;
849         c->ErrDesc.Addr.upper = temp64.val32.upper;
850         c->ErrDesc.Len = sizeof(ErrorInfo_struct);
851
852         c->ctlr = h->ctlr;
853         return c;
854 }
855
856 /*
857  * Frees a command block that was previously allocated with cmd_alloc().
858  */
859 static void cmd_free(ctlr_info_t *h, CommandList_struct *c, int got_from_pool)
860 {
861         int i;
862         u64bit temp64;
863
864         if (!got_from_pool) {
865                 temp64.val32.lower = c->ErrDesc.Addr.lower;
866                 temp64.val32.upper = c->ErrDesc.Addr.upper;
867                 pci_free_consistent(h->pdev, sizeof(ErrorInfo_struct),
868                                     c->err_info, (dma_addr_t) temp64.val);
869                 pci_free_consistent(h->pdev, sizeof(CommandList_struct),
870                                     c, (dma_addr_t) c->busaddr);
871         } else {
872                 i = c - h->cmd_pool;
873                 clear_bit(i & (BITS_PER_LONG - 1),
874                           h->cmd_pool_bits + (i / BITS_PER_LONG));
875                 h->nr_frees++;
876         }
877 }
878
879 static inline ctlr_info_t *get_host(struct gendisk *disk)
880 {
881         return disk->queue->queuedata;
882 }
883
884 static inline drive_info_struct *get_drv(struct gendisk *disk)
885 {
886         return disk->private_data;
887 }
888
889 /*
890  * Open.  Make sure the device is really there.
891  */
892 static int cciss_open(struct block_device *bdev, fmode_t mode)
893 {
894         ctlr_info_t *host = get_host(bdev->bd_disk);
895         drive_info_struct *drv = get_drv(bdev->bd_disk);
896
897 #ifdef CCISS_DEBUG
898         printk(KERN_DEBUG "cciss_open %s\n", bdev->bd_disk->disk_name);
899 #endif                          /* CCISS_DEBUG */
900
901         if (drv->busy_configuring)
902                 return -EBUSY;
903         /*
904          * Root is allowed to open raw volume zero even if it's not configured
905          * so array config can still work. Root is also allowed to open any
906          * volume that has a LUN ID, so it can issue IOCTL to reread the
907          * disk information.  I don't think I really like this
908          * but I'm already using way to many device nodes to claim another one
909          * for "raw controller".
910          */
911         if (drv->heads == 0) {
912                 if (MINOR(bdev->bd_dev) != 0) { /* not node 0? */
913                         /* if not node 0 make sure it is a partition = 0 */
914                         if (MINOR(bdev->bd_dev) & 0x0f) {
915                                 return -ENXIO;
916                                 /* if it is, make sure we have a LUN ID */
917                         } else if (memcmp(drv->LunID, CTLR_LUNID,
918                                 sizeof(drv->LunID))) {
919                                 return -ENXIO;
920                         }
921                 }
922                 if (!capable(CAP_SYS_ADMIN))
923                         return -EPERM;
924         }
925         drv->usage_count++;
926         host->usage_count++;
927         return 0;
928 }
929
930 /*
931  * Close.  Sync first.
932  */
933 static int cciss_release(struct gendisk *disk, fmode_t mode)
934 {
935         ctlr_info_t *host = get_host(disk);
936         drive_info_struct *drv = get_drv(disk);
937
938 #ifdef CCISS_DEBUG
939         printk(KERN_DEBUG "cciss_release %s\n", disk->disk_name);
940 #endif                          /* CCISS_DEBUG */
941
942         drv->usage_count--;
943         host->usage_count--;
944         return 0;
945 }
946
947 #ifdef CONFIG_COMPAT
948
949 static int do_ioctl(struct block_device *bdev, fmode_t mode,
950                     unsigned cmd, unsigned long arg)
951 {
952         int ret;
953         lock_kernel();
954         ret = cciss_ioctl(bdev, mode, cmd, arg);
955         unlock_kernel();
956         return ret;
957 }
958
959 static int cciss_ioctl32_passthru(struct block_device *bdev, fmode_t mode,
960                                   unsigned cmd, unsigned long arg);
961 static int cciss_ioctl32_big_passthru(struct block_device *bdev, fmode_t mode,
962                                       unsigned cmd, unsigned long arg);
963
964 static int cciss_compat_ioctl(struct block_device *bdev, fmode_t mode,
965                               unsigned cmd, unsigned long arg)
966 {
967         switch (cmd) {
968         case CCISS_GETPCIINFO:
969         case CCISS_GETINTINFO:
970         case CCISS_SETINTINFO:
971         case CCISS_GETNODENAME:
972         case CCISS_SETNODENAME:
973         case CCISS_GETHEARTBEAT:
974         case CCISS_GETBUSTYPES:
975         case CCISS_GETFIRMVER:
976         case CCISS_GETDRIVVER:
977         case CCISS_REVALIDVOLS:
978         case CCISS_DEREGDISK:
979         case CCISS_REGNEWDISK:
980         case CCISS_REGNEWD:
981         case CCISS_RESCANDISK:
982         case CCISS_GETLUNINFO:
983                 return do_ioctl(bdev, mode, cmd, arg);
984
985         case CCISS_PASSTHRU32:
986                 return cciss_ioctl32_passthru(bdev, mode, cmd, arg);
987         case CCISS_BIG_PASSTHRU32:
988                 return cciss_ioctl32_big_passthru(bdev, mode, cmd, arg);
989
990         default:
991                 return -ENOIOCTLCMD;
992         }
993 }
994
995 static int cciss_ioctl32_passthru(struct block_device *bdev, fmode_t mode,
996                                   unsigned cmd, unsigned long arg)
997 {
998         IOCTL32_Command_struct __user *arg32 =
999             (IOCTL32_Command_struct __user *) arg;
1000         IOCTL_Command_struct arg64;
1001         IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
1002         int err;
1003         u32 cp;
1004
1005         err = 0;
1006         err |=
1007             copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
1008                            sizeof(arg64.LUN_info));
1009         err |=
1010             copy_from_user(&arg64.Request, &arg32->Request,
1011                            sizeof(arg64.Request));
1012         err |=
1013             copy_from_user(&arg64.error_info, &arg32->error_info,
1014                            sizeof(arg64.error_info));
1015         err |= get_user(arg64.buf_size, &arg32->buf_size);
1016         err |= get_user(cp, &arg32->buf);
1017         arg64.buf = compat_ptr(cp);
1018         err |= copy_to_user(p, &arg64, sizeof(arg64));
1019
1020         if (err)
1021                 return -EFAULT;
1022
1023         err = do_ioctl(bdev, mode, CCISS_PASSTHRU, (unsigned long)p);
1024         if (err)
1025                 return err;
1026         err |=
1027             copy_in_user(&arg32->error_info, &p->error_info,
1028                          sizeof(arg32->error_info));
1029         if (err)
1030                 return -EFAULT;
1031         return err;
1032 }
1033
1034 static int cciss_ioctl32_big_passthru(struct block_device *bdev, fmode_t mode,
1035                                       unsigned cmd, unsigned long arg)
1036 {
1037         BIG_IOCTL32_Command_struct __user *arg32 =
1038             (BIG_IOCTL32_Command_struct __user *) arg;
1039         BIG_IOCTL_Command_struct arg64;
1040         BIG_IOCTL_Command_struct __user *p =
1041             compat_alloc_user_space(sizeof(arg64));
1042         int err;
1043         u32 cp;
1044
1045         err = 0;
1046         err |=
1047             copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
1048                            sizeof(arg64.LUN_info));
1049         err |=
1050             copy_from_user(&arg64.Request, &arg32->Request,
1051                            sizeof(arg64.Request));
1052         err |=
1053             copy_from_user(&arg64.error_info, &arg32->error_info,
1054                            sizeof(arg64.error_info));
1055         err |= get_user(arg64.buf_size, &arg32->buf_size);
1056         err |= get_user(arg64.malloc_size, &arg32->malloc_size);
1057         err |= get_user(cp, &arg32->buf);
1058         arg64.buf = compat_ptr(cp);
1059         err |= copy_to_user(p, &arg64, sizeof(arg64));
1060
1061         if (err)
1062                 return -EFAULT;
1063
1064         err = do_ioctl(bdev, mode, CCISS_BIG_PASSTHRU, (unsigned long)p);
1065         if (err)
1066                 return err;
1067         err |=
1068             copy_in_user(&arg32->error_info, &p->error_info,
1069                          sizeof(arg32->error_info));
1070         if (err)
1071                 return -EFAULT;
1072         return err;
1073 }
1074 #endif
1075
1076 static int cciss_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1077 {
1078         drive_info_struct *drv = get_drv(bdev->bd_disk);
1079
1080         if (!drv->cylinders)
1081                 return -ENXIO;
1082
1083         geo->heads = drv->heads;
1084         geo->sectors = drv->sectors;
1085         geo->cylinders = drv->cylinders;
1086         return 0;
1087 }
1088
1089 static void check_ioctl_unit_attention(ctlr_info_t *host, CommandList_struct *c)
1090 {
1091         if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
1092                         c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
1093                 (void)check_for_unit_attention(host, c);
1094 }
1095 /*
1096  * ioctl
1097  */
1098 static int cciss_ioctl(struct block_device *bdev, fmode_t mode,
1099                        unsigned int cmd, unsigned long arg)
1100 {
1101         struct gendisk *disk = bdev->bd_disk;
1102         ctlr_info_t *host = get_host(disk);
1103         drive_info_struct *drv = get_drv(disk);
1104         int ctlr = host->ctlr;
1105         void __user *argp = (void __user *)arg;
1106
1107 #ifdef CCISS_DEBUG
1108         printk(KERN_DEBUG "cciss_ioctl: Called with cmd=%x %lx\n", cmd, arg);
1109 #endif                          /* CCISS_DEBUG */
1110
1111         switch (cmd) {
1112         case CCISS_GETPCIINFO:
1113                 {
1114                         cciss_pci_info_struct pciinfo;
1115
1116                         if (!arg)
1117                                 return -EINVAL;
1118                         pciinfo.domain = pci_domain_nr(host->pdev->bus);
1119                         pciinfo.bus = host->pdev->bus->number;
1120                         pciinfo.dev_fn = host->pdev->devfn;
1121                         pciinfo.board_id = host->board_id;
1122                         if (copy_to_user
1123                             (argp, &pciinfo, sizeof(cciss_pci_info_struct)))
1124                                 return -EFAULT;
1125                         return 0;
1126                 }
1127         case CCISS_GETINTINFO:
1128                 {
1129                         cciss_coalint_struct intinfo;
1130                         if (!arg)
1131                                 return -EINVAL;
1132                         intinfo.delay =
1133                             readl(&host->cfgtable->HostWrite.CoalIntDelay);
1134                         intinfo.count =
1135                             readl(&host->cfgtable->HostWrite.CoalIntCount);
1136                         if (copy_to_user
1137                             (argp, &intinfo, sizeof(cciss_coalint_struct)))
1138                                 return -EFAULT;
1139                         return 0;
1140                 }
1141         case CCISS_SETINTINFO:
1142                 {
1143                         cciss_coalint_struct intinfo;
1144                         unsigned long flags;
1145                         int i;
1146
1147                         if (!arg)
1148                                 return -EINVAL;
1149                         if (!capable(CAP_SYS_ADMIN))
1150                                 return -EPERM;
1151                         if (copy_from_user
1152                             (&intinfo, argp, sizeof(cciss_coalint_struct)))
1153                                 return -EFAULT;
1154                         if ((intinfo.delay == 0) && (intinfo.count == 0))
1155                         {
1156 //                      printk("cciss_ioctl: delay and count cannot be 0\n");
1157                                 return -EINVAL;
1158                         }
1159                         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1160                         /* Update the field, and then ring the doorbell */
1161                         writel(intinfo.delay,
1162                                &(host->cfgtable->HostWrite.CoalIntDelay));
1163                         writel(intinfo.count,
1164                                &(host->cfgtable->HostWrite.CoalIntCount));
1165                         writel(CFGTBL_ChangeReq, host->vaddr + SA5_DOORBELL);
1166
1167                         for (i = 0; i < MAX_IOCTL_CONFIG_WAIT; i++) {
1168                                 if (!(readl(host->vaddr + SA5_DOORBELL)
1169                                       & CFGTBL_ChangeReq))
1170                                         break;
1171                                 /* delay and try again */
1172                                 udelay(1000);
1173                         }
1174                         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1175                         if (i >= MAX_IOCTL_CONFIG_WAIT)
1176                                 return -EAGAIN;
1177                         return 0;
1178                 }
1179         case CCISS_GETNODENAME:
1180                 {
1181                         NodeName_type NodeName;
1182                         int i;
1183
1184                         if (!arg)
1185                                 return -EINVAL;
1186                         for (i = 0; i < 16; i++)
1187                                 NodeName[i] =
1188                                     readb(&host->cfgtable->ServerName[i]);
1189                         if (copy_to_user(argp, NodeName, sizeof(NodeName_type)))
1190                                 return -EFAULT;
1191                         return 0;
1192                 }
1193         case CCISS_SETNODENAME:
1194                 {
1195                         NodeName_type NodeName;
1196                         unsigned long flags;
1197                         int i;
1198
1199                         if (!arg)
1200                                 return -EINVAL;
1201                         if (!capable(CAP_SYS_ADMIN))
1202                                 return -EPERM;
1203
1204                         if (copy_from_user
1205                             (NodeName, argp, sizeof(NodeName_type)))
1206                                 return -EFAULT;
1207
1208                         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1209
1210                         /* Update the field, and then ring the doorbell */
1211                         for (i = 0; i < 16; i++)
1212                                 writeb(NodeName[i],
1213                                        &host->cfgtable->ServerName[i]);
1214
1215                         writel(CFGTBL_ChangeReq, host->vaddr + SA5_DOORBELL);
1216
1217                         for (i = 0; i < MAX_IOCTL_CONFIG_WAIT; i++) {
1218                                 if (!(readl(host->vaddr + SA5_DOORBELL)
1219                                       & CFGTBL_ChangeReq))
1220                                         break;
1221                                 /* delay and try again */
1222                                 udelay(1000);
1223                         }
1224                         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1225                         if (i >= MAX_IOCTL_CONFIG_WAIT)
1226                                 return -EAGAIN;
1227                         return 0;
1228                 }
1229
1230         case CCISS_GETHEARTBEAT:
1231                 {
1232                         Heartbeat_type heartbeat;
1233
1234                         if (!arg)
1235                                 return -EINVAL;
1236                         heartbeat = readl(&host->cfgtable->HeartBeat);
1237                         if (copy_to_user
1238                             (argp, &heartbeat, sizeof(Heartbeat_type)))
1239                                 return -EFAULT;
1240                         return 0;
1241                 }
1242         case CCISS_GETBUSTYPES:
1243                 {
1244                         BusTypes_type BusTypes;
1245
1246                         if (!arg)
1247                                 return -EINVAL;
1248                         BusTypes = readl(&host->cfgtable->BusTypes);
1249                         if (copy_to_user
1250                             (argp, &BusTypes, sizeof(BusTypes_type)))
1251                                 return -EFAULT;
1252                         return 0;
1253                 }
1254         case CCISS_GETFIRMVER:
1255                 {
1256                         FirmwareVer_type firmware;
1257
1258                         if (!arg)
1259                                 return -EINVAL;
1260                         memcpy(firmware, host->firm_ver, 4);
1261
1262                         if (copy_to_user
1263                             (argp, firmware, sizeof(FirmwareVer_type)))
1264                                 return -EFAULT;
1265                         return 0;
1266                 }
1267         case CCISS_GETDRIVVER:
1268                 {
1269                         DriverVer_type DriverVer = DRIVER_VERSION;
1270
1271                         if (!arg)
1272                                 return -EINVAL;
1273
1274                         if (copy_to_user
1275                             (argp, &DriverVer, sizeof(DriverVer_type)))
1276                                 return -EFAULT;
1277                         return 0;
1278                 }
1279
1280         case CCISS_DEREGDISK:
1281         case CCISS_REGNEWD:
1282         case CCISS_REVALIDVOLS:
1283                 return rebuild_lun_table(host, 0, 1);
1284
1285         case CCISS_GETLUNINFO:{
1286                         LogvolInfo_struct luninfo;
1287
1288                         memcpy(&luninfo.LunID, drv->LunID,
1289                                 sizeof(luninfo.LunID));
1290                         luninfo.num_opens = drv->usage_count;
1291                         luninfo.num_parts = 0;
1292                         if (copy_to_user(argp, &luninfo,
1293                                          sizeof(LogvolInfo_struct)))
1294                                 return -EFAULT;
1295                         return 0;
1296                 }
1297         case CCISS_PASSTHRU:
1298                 {
1299                         IOCTL_Command_struct iocommand;
1300                         CommandList_struct *c;
1301                         char *buff = NULL;
1302                         u64bit temp64;
1303                         unsigned long flags;
1304                         DECLARE_COMPLETION_ONSTACK(wait);
1305
1306                         if (!arg)
1307                                 return -EINVAL;
1308
1309                         if (!capable(CAP_SYS_RAWIO))
1310                                 return -EPERM;
1311
1312                         if (copy_from_user
1313                             (&iocommand, argp, sizeof(IOCTL_Command_struct)))
1314                                 return -EFAULT;
1315                         if ((iocommand.buf_size < 1) &&
1316                             (iocommand.Request.Type.Direction != XFER_NONE)) {
1317                                 return -EINVAL;
1318                         }
1319 #if 0                           /* 'buf_size' member is 16-bits, and always smaller than kmalloc limit */
1320                         /* Check kmalloc limits */
1321                         if (iocommand.buf_size > 128000)
1322                                 return -EINVAL;
1323 #endif
1324                         if (iocommand.buf_size > 0) {
1325                                 buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
1326                                 if (buff == NULL)
1327                                         return -EFAULT;
1328                         }
1329                         if (iocommand.Request.Type.Direction == XFER_WRITE) {
1330                                 /* Copy the data into the buffer we created */
1331                                 if (copy_from_user
1332                                     (buff, iocommand.buf, iocommand.buf_size)) {
1333                                         kfree(buff);
1334                                         return -EFAULT;
1335                                 }
1336                         } else {
1337                                 memset(buff, 0, iocommand.buf_size);
1338                         }
1339                         if ((c = cmd_alloc(host, 0)) == NULL) {
1340                                 kfree(buff);
1341                                 return -ENOMEM;
1342                         }
1343                         // Fill in the command type
1344                         c->cmd_type = CMD_IOCTL_PEND;
1345                         // Fill in Command Header
1346                         c->Header.ReplyQueue = 0;       // unused in simple mode
1347                         if (iocommand.buf_size > 0)     // buffer to fill
1348                         {
1349                                 c->Header.SGList = 1;
1350                                 c->Header.SGTotal = 1;
1351                         } else  // no buffers to fill
1352                         {
1353                                 c->Header.SGList = 0;
1354                                 c->Header.SGTotal = 0;
1355                         }
1356                         c->Header.LUN = iocommand.LUN_info;
1357                         c->Header.Tag.lower = c->busaddr;       // use the kernel address the cmd block for tag
1358
1359                         // Fill in Request block
1360                         c->Request = iocommand.Request;
1361
1362                         // Fill in the scatter gather information
1363                         if (iocommand.buf_size > 0) {
1364                                 temp64.val = pci_map_single(host->pdev, buff,
1365                                         iocommand.buf_size,
1366                                         PCI_DMA_BIDIRECTIONAL);
1367                                 c->SG[0].Addr.lower = temp64.val32.lower;
1368                                 c->SG[0].Addr.upper = temp64.val32.upper;
1369                                 c->SG[0].Len = iocommand.buf_size;
1370                                 c->SG[0].Ext = 0;       // we are not chaining
1371                         }
1372                         c->waiting = &wait;
1373
1374                         /* Put the request on the tail of the request queue */
1375                         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1376                         addQ(&host->reqQ, c);
1377                         host->Qdepth++;
1378                         start_io(host);
1379                         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1380
1381                         wait_for_completion(&wait);
1382
1383                         /* unlock the buffers from DMA */
1384                         temp64.val32.lower = c->SG[0].Addr.lower;
1385                         temp64.val32.upper = c->SG[0].Addr.upper;
1386                         pci_unmap_single(host->pdev, (dma_addr_t) temp64.val,
1387                                          iocommand.buf_size,
1388                                          PCI_DMA_BIDIRECTIONAL);
1389
1390                         check_ioctl_unit_attention(host, c);
1391
1392                         /* Copy the error information out */
1393                         iocommand.error_info = *(c->err_info);
1394                         if (copy_to_user
1395                             (argp, &iocommand, sizeof(IOCTL_Command_struct))) {
1396                                 kfree(buff);
1397                                 cmd_free(host, c, 0);
1398                                 return -EFAULT;
1399                         }
1400
1401                         if (iocommand.Request.Type.Direction == XFER_READ) {
1402                                 /* Copy the data out of the buffer we created */
1403                                 if (copy_to_user
1404                                     (iocommand.buf, buff, iocommand.buf_size)) {
1405                                         kfree(buff);
1406                                         cmd_free(host, c, 0);
1407                                         return -EFAULT;
1408                                 }
1409                         }
1410                         kfree(buff);
1411                         cmd_free(host, c, 0);
1412                         return 0;
1413                 }
1414         case CCISS_BIG_PASSTHRU:{
1415                         BIG_IOCTL_Command_struct *ioc;
1416                         CommandList_struct *c;
1417                         unsigned char **buff = NULL;
1418                         int *buff_size = NULL;
1419                         u64bit temp64;
1420                         unsigned long flags;
1421                         BYTE sg_used = 0;
1422                         int status = 0;
1423                         int i;
1424                         DECLARE_COMPLETION_ONSTACK(wait);
1425                         __u32 left;
1426                         __u32 sz;
1427                         BYTE __user *data_ptr;
1428
1429                         if (!arg)
1430                                 return -EINVAL;
1431                         if (!capable(CAP_SYS_RAWIO))
1432                                 return -EPERM;
1433                         ioc = (BIG_IOCTL_Command_struct *)
1434                             kmalloc(sizeof(*ioc), GFP_KERNEL);
1435                         if (!ioc) {
1436                                 status = -ENOMEM;
1437                                 goto cleanup1;
1438                         }
1439                         if (copy_from_user(ioc, argp, sizeof(*ioc))) {
1440                                 status = -EFAULT;
1441                                 goto cleanup1;
1442                         }
1443                         if ((ioc->buf_size < 1) &&
1444                             (ioc->Request.Type.Direction != XFER_NONE)) {
1445                                 status = -EINVAL;
1446                                 goto cleanup1;
1447                         }
1448                         /* Check kmalloc limits  using all SGs */
1449                         if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
1450                                 status = -EINVAL;
1451                                 goto cleanup1;
1452                         }
1453                         if (ioc->buf_size > ioc->malloc_size * MAXSGENTRIES) {
1454                                 status = -EINVAL;
1455                                 goto cleanup1;
1456                         }
1457                         buff =
1458                             kzalloc(MAXSGENTRIES * sizeof(char *), GFP_KERNEL);
1459                         if (!buff) {
1460                                 status = -ENOMEM;
1461                                 goto cleanup1;
1462                         }
1463                         buff_size = kmalloc(MAXSGENTRIES * sizeof(int),
1464                                                    GFP_KERNEL);
1465                         if (!buff_size) {
1466                                 status = -ENOMEM;
1467                                 goto cleanup1;
1468                         }
1469                         left = ioc->buf_size;
1470                         data_ptr = ioc->buf;
1471                         while (left) {
1472                                 sz = (left >
1473                                       ioc->malloc_size) ? ioc->
1474                                     malloc_size : left;
1475                                 buff_size[sg_used] = sz;
1476                                 buff[sg_used] = kmalloc(sz, GFP_KERNEL);
1477                                 if (buff[sg_used] == NULL) {
1478                                         status = -ENOMEM;
1479                                         goto cleanup1;
1480                                 }
1481                                 if (ioc->Request.Type.Direction == XFER_WRITE) {
1482                                         if (copy_from_user
1483                                             (buff[sg_used], data_ptr, sz)) {
1484                                                 status = -EFAULT;
1485                                                 goto cleanup1;
1486                                         }
1487                                 } else {
1488                                         memset(buff[sg_used], 0, sz);
1489                                 }
1490                                 left -= sz;
1491                                 data_ptr += sz;
1492                                 sg_used++;
1493                         }
1494                         if ((c = cmd_alloc(host, 0)) == NULL) {
1495                                 status = -ENOMEM;
1496                                 goto cleanup1;
1497                         }
1498                         c->cmd_type = CMD_IOCTL_PEND;
1499                         c->Header.ReplyQueue = 0;
1500
1501                         if (ioc->buf_size > 0) {
1502                                 c->Header.SGList = sg_used;
1503                                 c->Header.SGTotal = sg_used;
1504                         } else {
1505                                 c->Header.SGList = 0;
1506                                 c->Header.SGTotal = 0;
1507                         }
1508                         c->Header.LUN = ioc->LUN_info;
1509                         c->Header.Tag.lower = c->busaddr;
1510
1511                         c->Request = ioc->Request;
1512                         if (ioc->buf_size > 0) {
1513                                 int i;
1514                                 for (i = 0; i < sg_used; i++) {
1515                                         temp64.val =
1516                                             pci_map_single(host->pdev, buff[i],
1517                                                     buff_size[i],
1518                                                     PCI_DMA_BIDIRECTIONAL);
1519                                         c->SG[i].Addr.lower =
1520                                             temp64.val32.lower;
1521                                         c->SG[i].Addr.upper =
1522                                             temp64.val32.upper;
1523                                         c->SG[i].Len = buff_size[i];
1524                                         c->SG[i].Ext = 0;       /* we are not chaining */
1525                                 }
1526                         }
1527                         c->waiting = &wait;
1528                         /* Put the request on the tail of the request queue */
1529                         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1530                         addQ(&host->reqQ, c);
1531                         host->Qdepth++;
1532                         start_io(host);
1533                         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1534                         wait_for_completion(&wait);
1535                         /* unlock the buffers from DMA */
1536                         for (i = 0; i < sg_used; i++) {
1537                                 temp64.val32.lower = c->SG[i].Addr.lower;
1538                                 temp64.val32.upper = c->SG[i].Addr.upper;
1539                                 pci_unmap_single(host->pdev,
1540                                         (dma_addr_t) temp64.val, buff_size[i],
1541                                         PCI_DMA_BIDIRECTIONAL);
1542                         }
1543                         check_ioctl_unit_attention(host, c);
1544                         /* Copy the error information out */
1545                         ioc->error_info = *(c->err_info);
1546                         if (copy_to_user(argp, ioc, sizeof(*ioc))) {
1547                                 cmd_free(host, c, 0);
1548                                 status = -EFAULT;
1549                                 goto cleanup1;
1550                         }
1551                         if (ioc->Request.Type.Direction == XFER_READ) {
1552                                 /* Copy the data out of the buffer we created */
1553                                 BYTE __user *ptr = ioc->buf;
1554                                 for (i = 0; i < sg_used; i++) {
1555                                         if (copy_to_user
1556                                             (ptr, buff[i], buff_size[i])) {
1557                                                 cmd_free(host, c, 0);
1558                                                 status = -EFAULT;
1559                                                 goto cleanup1;
1560                                         }
1561                                         ptr += buff_size[i];
1562                                 }
1563                         }
1564                         cmd_free(host, c, 0);
1565                         status = 0;
1566                       cleanup1:
1567                         if (buff) {
1568                                 for (i = 0; i < sg_used; i++)
1569                                         kfree(buff[i]);
1570                                 kfree(buff);
1571                         }
1572                         kfree(buff_size);
1573                         kfree(ioc);
1574                         return status;
1575                 }
1576
1577         /* scsi_cmd_ioctl handles these, below, though some are not */
1578         /* very meaningful for cciss.  SG_IO is the main one people want. */
1579
1580         case SG_GET_VERSION_NUM:
1581         case SG_SET_TIMEOUT:
1582         case SG_GET_TIMEOUT:
1583         case SG_GET_RESERVED_SIZE:
1584         case SG_SET_RESERVED_SIZE:
1585         case SG_EMULATED_HOST:
1586         case SG_IO:
1587         case SCSI_IOCTL_SEND_COMMAND:
1588                 return scsi_cmd_ioctl(disk->queue, disk, mode, cmd, argp);
1589
1590         /* scsi_cmd_ioctl would normally handle these, below, but */
1591         /* they aren't a good fit for cciss, as CD-ROMs are */
1592         /* not supported, and we don't have any bus/target/lun */
1593         /* which we present to the kernel. */
1594
1595         case CDROM_SEND_PACKET:
1596         case CDROMCLOSETRAY:
1597         case CDROMEJECT:
1598         case SCSI_IOCTL_GET_IDLUN:
1599         case SCSI_IOCTL_GET_BUS_NUMBER:
1600         default:
1601                 return -ENOTTY;
1602         }
1603 }
1604
1605 static void cciss_check_queues(ctlr_info_t *h)
1606 {
1607         int start_queue = h->next_to_run;
1608         int i;
1609
1610         /* check to see if we have maxed out the number of commands that can
1611          * be placed on the queue.  If so then exit.  We do this check here
1612          * in case the interrupt we serviced was from an ioctl and did not
1613          * free any new commands.
1614          */
1615         if ((find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds)) == h->nr_cmds)
1616                 return;
1617
1618         /* We have room on the queue for more commands.  Now we need to queue
1619          * them up.  We will also keep track of the next queue to run so
1620          * that every queue gets a chance to be started first.
1621          */
1622         for (i = 0; i < h->highest_lun + 1; i++) {
1623                 int curr_queue = (start_queue + i) % (h->highest_lun + 1);
1624                 /* make sure the disk has been added and the drive is real
1625                  * because this can be called from the middle of init_one.
1626                  */
1627                 if (!h->drv[curr_queue])
1628                         continue;
1629                 if (!(h->drv[curr_queue]->queue) ||
1630                         !(h->drv[curr_queue]->heads))
1631                         continue;
1632                 blk_start_queue(h->gendisk[curr_queue]->queue);
1633
1634                 /* check to see if we have maxed out the number of commands
1635                  * that can be placed on the queue.
1636                  */
1637                 if ((find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds)) == h->nr_cmds) {
1638                         if (curr_queue == start_queue) {
1639                                 h->next_to_run =
1640                                     (start_queue + 1) % (h->highest_lun + 1);
1641                                 break;
1642                         } else {
1643                                 h->next_to_run = curr_queue;
1644                                 break;
1645                         }
1646                 }
1647         }
1648 }
1649
1650 static void cciss_softirq_done(struct request *rq)
1651 {
1652         CommandList_struct *cmd = rq->completion_data;
1653         ctlr_info_t *h = hba[cmd->ctlr];
1654         unsigned long flags;
1655         u64bit temp64;
1656         int i, ddir;
1657
1658         if (cmd->Request.Type.Direction == XFER_READ)
1659                 ddir = PCI_DMA_FROMDEVICE;
1660         else
1661                 ddir = PCI_DMA_TODEVICE;
1662
1663         /* command did not need to be retried */
1664         /* unmap the DMA mapping for all the scatter gather elements */
1665         for (i = 0; i < cmd->Header.SGList; i++) {
1666                 temp64.val32.lower = cmd->SG[i].Addr.lower;
1667                 temp64.val32.upper = cmd->SG[i].Addr.upper;
1668                 pci_unmap_page(h->pdev, temp64.val, cmd->SG[i].Len, ddir);
1669         }
1670
1671 #ifdef CCISS_DEBUG
1672         printk("Done with %p\n", rq);
1673 #endif                          /* CCISS_DEBUG */
1674
1675         /* set the residual count for pc requests */
1676         if (blk_pc_request(rq))
1677                 rq->resid_len = cmd->err_info->ResidualCnt;
1678
1679         blk_end_request_all(rq, (rq->errors == 0) ? 0 : -EIO);
1680
1681         spin_lock_irqsave(&h->lock, flags);
1682         cmd_free(h, cmd, 1);
1683         cciss_check_queues(h);
1684         spin_unlock_irqrestore(&h->lock, flags);
1685 }
1686
1687 static inline void log_unit_to_scsi3addr(ctlr_info_t *h,
1688         unsigned char scsi3addr[], uint32_t log_unit)
1689 {
1690         memcpy(scsi3addr, h->drv[log_unit]->LunID,
1691                 sizeof(h->drv[log_unit]->LunID));
1692 }
1693
1694 /* This function gets the SCSI vendor, model, and revision of a logical drive
1695  * via the inquiry page 0.  Model, vendor, and rev are set to empty strings if
1696  * they cannot be read.
1697  */
1698 static void cciss_get_device_descr(int ctlr, int logvol, int withirq,
1699                                    char *vendor, char *model, char *rev)
1700 {
1701         int rc;
1702         InquiryData_struct *inq_buf;
1703         unsigned char scsi3addr[8];
1704
1705         *vendor = '\0';
1706         *model = '\0';
1707         *rev = '\0';
1708
1709         inq_buf = kzalloc(sizeof(InquiryData_struct), GFP_KERNEL);
1710         if (!inq_buf)
1711                 return;
1712
1713         log_unit_to_scsi3addr(hba[ctlr], scsi3addr, logvol);
1714         if (withirq)
1715                 rc = sendcmd_withirq(CISS_INQUIRY, ctlr, inq_buf,
1716                              sizeof(InquiryData_struct), 0,
1717                                 scsi3addr, TYPE_CMD);
1718         else
1719                 rc = sendcmd(CISS_INQUIRY, ctlr, inq_buf,
1720                              sizeof(InquiryData_struct), 0,
1721                                 scsi3addr, TYPE_CMD);
1722         if (rc == IO_OK) {
1723                 memcpy(vendor, &inq_buf->data_byte[8], VENDOR_LEN);
1724                 vendor[VENDOR_LEN] = '\0';
1725                 memcpy(model, &inq_buf->data_byte[16], MODEL_LEN);
1726                 model[MODEL_LEN] = '\0';
1727                 memcpy(rev, &inq_buf->data_byte[32], REV_LEN);
1728                 rev[REV_LEN] = '\0';
1729         }
1730
1731         kfree(inq_buf);
1732         return;
1733 }
1734
1735 /* This function gets the serial number of a logical drive via
1736  * inquiry page 0x83.  Serial no. is 16 bytes.  If the serial
1737  * number cannot be had, for whatever reason, 16 bytes of 0xff
1738  * are returned instead.
1739  */
1740 static void cciss_get_serial_no(int ctlr, int logvol, int withirq,
1741                                 unsigned char *serial_no, int buflen)
1742 {
1743 #define PAGE_83_INQ_BYTES 64
1744         int rc;
1745         unsigned char *buf;
1746         unsigned char scsi3addr[8];
1747
1748         if (buflen > 16)
1749                 buflen = 16;
1750         memset(serial_no, 0xff, buflen);
1751         buf = kzalloc(PAGE_83_INQ_BYTES, GFP_KERNEL);
1752         if (!buf)
1753                 return;
1754         memset(serial_no, 0, buflen);
1755         log_unit_to_scsi3addr(hba[ctlr], scsi3addr, logvol);
1756         if (withirq)
1757                 rc = sendcmd_withirq(CISS_INQUIRY, ctlr, buf,
1758                         PAGE_83_INQ_BYTES, 0x83, scsi3addr, TYPE_CMD);
1759         else
1760                 rc = sendcmd(CISS_INQUIRY, ctlr, buf,
1761                         PAGE_83_INQ_BYTES, 0x83, scsi3addr, TYPE_CMD);
1762         if (rc == IO_OK)
1763                 memcpy(serial_no, &buf[8], buflen);
1764         kfree(buf);
1765         return;
1766 }
1767
1768 /*
1769  * cciss_add_disk sets up the block device queue for a logical drive
1770  */
1771 static int cciss_add_disk(ctlr_info_t *h, struct gendisk *disk,
1772                                 int drv_index)
1773 {
1774         disk->queue = blk_init_queue(do_cciss_request, &h->lock);
1775         if (!disk->queue)
1776                 goto init_queue_failure;
1777         sprintf(disk->disk_name, "cciss/c%dd%d", h->ctlr, drv_index);
1778         disk->major = h->major;
1779         disk->first_minor = drv_index << NWD_SHIFT;
1780         disk->fops = &cciss_fops;
1781         if (cciss_create_ld_sysfs_entry(h, drv_index))
1782                 goto cleanup_queue;
1783         disk->private_data = h->drv[drv_index];
1784         disk->driverfs_dev = &h->drv[drv_index]->dev;
1785
1786         /* Set up queue information */
1787         blk_queue_bounce_limit(disk->queue, h->pdev->dma_mask);
1788
1789         /* This is a hardware imposed limit. */
1790         blk_queue_max_hw_segments(disk->queue, MAXSGENTRIES);
1791
1792         /* This is a limit in the driver and could be eliminated. */
1793         blk_queue_max_phys_segments(disk->queue, MAXSGENTRIES);
1794
1795         blk_queue_max_sectors(disk->queue, h->cciss_max_sectors);
1796
1797         blk_queue_softirq_done(disk->queue, cciss_softirq_done);
1798
1799         disk->queue->queuedata = h;
1800
1801         blk_queue_logical_block_size(disk->queue,
1802                                      h->drv[drv_index]->block_size);
1803
1804         /* Make sure all queue data is written out before */
1805         /* setting h->drv[drv_index]->queue, as setting this */
1806         /* allows the interrupt handler to start the queue */
1807         wmb();
1808         h->drv[drv_index]->queue = disk->queue;
1809         add_disk(disk);
1810         return 0;
1811
1812 cleanup_queue:
1813         blk_cleanup_queue(disk->queue);
1814         disk->queue = NULL;
1815 init_queue_failure:
1816         return -1;
1817 }
1818
1819 /* This function will check the usage_count of the drive to be updated/added.
1820  * If the usage_count is zero and it is a heretofore unknown drive, or,
1821  * the drive's capacity, geometry, or serial number has changed,
1822  * then the drive information will be updated and the disk will be
1823  * re-registered with the kernel.  If these conditions don't hold,
1824  * then it will be left alone for the next reboot.  The exception to this
1825  * is disk 0 which will always be left registered with the kernel since it
1826  * is also the controller node.  Any changes to disk 0 will show up on
1827  * the next reboot.
1828  */
1829 static void cciss_update_drive_info(int ctlr, int drv_index, int first_time,
1830         int via_ioctl)
1831 {
1832         ctlr_info_t *h = hba[ctlr];
1833         struct gendisk *disk;
1834         InquiryData_struct *inq_buff = NULL;
1835         unsigned int block_size;
1836         sector_t total_size;
1837         unsigned long flags = 0;
1838         int ret = 0;
1839         drive_info_struct *drvinfo;
1840
1841         /* Get information about the disk and modify the driver structure */
1842         inq_buff = kmalloc(sizeof(InquiryData_struct), GFP_KERNEL);
1843         drvinfo = kzalloc(sizeof(*drvinfo), GFP_KERNEL);
1844         if (inq_buff == NULL || drvinfo == NULL)
1845                 goto mem_msg;
1846
1847         /* testing to see if 16-byte CDBs are already being used */
1848         if (h->cciss_read == CCISS_READ_16) {
1849                 cciss_read_capacity_16(h->ctlr, drv_index, 1,
1850                         &total_size, &block_size);
1851
1852         } else {
1853                 cciss_read_capacity(ctlr, drv_index, 1,
1854                                     &total_size, &block_size);
1855
1856                 /* if read_capacity returns all F's this volume is >2TB */
1857                 /* in size so we switch to 16-byte CDB's for all */
1858                 /* read/write ops */
1859                 if (total_size == 0xFFFFFFFFULL) {
1860                         cciss_read_capacity_16(ctlr, drv_index, 1,
1861                         &total_size, &block_size);
1862                         h->cciss_read = CCISS_READ_16;
1863                         h->cciss_write = CCISS_WRITE_16;
1864                 } else {
1865                         h->cciss_read = CCISS_READ_10;
1866                         h->cciss_write = CCISS_WRITE_10;
1867                 }
1868         }
1869
1870         cciss_geometry_inquiry(ctlr, drv_index, 1, total_size, block_size,
1871                                inq_buff, drvinfo);
1872         drvinfo->block_size = block_size;
1873         drvinfo->nr_blocks = total_size + 1;
1874
1875         cciss_get_device_descr(ctlr, drv_index, 1, drvinfo->vendor,
1876                                 drvinfo->model, drvinfo->rev);
1877         cciss_get_serial_no(ctlr, drv_index, 1, drvinfo->serial_no,
1878                         sizeof(drvinfo->serial_no));
1879         /* Save the lunid in case we deregister the disk, below. */
1880         memcpy(drvinfo->LunID, h->drv[drv_index]->LunID,
1881                 sizeof(drvinfo->LunID));
1882
1883         /* Is it the same disk we already know, and nothing's changed? */
1884         if (h->drv[drv_index]->raid_level != -1 &&
1885                 ((memcmp(drvinfo->serial_no,
1886                                 h->drv[drv_index]->serial_no, 16) == 0) &&
1887                 drvinfo->block_size == h->drv[drv_index]->block_size &&
1888                 drvinfo->nr_blocks == h->drv[drv_index]->nr_blocks &&
1889                 drvinfo->heads == h->drv[drv_index]->heads &&
1890                 drvinfo->sectors == h->drv[drv_index]->sectors &&
1891                 drvinfo->cylinders == h->drv[drv_index]->cylinders))
1892                         /* The disk is unchanged, nothing to update */
1893                         goto freeret;
1894
1895         /* If we get here it's not the same disk, or something's changed,
1896          * so we need to * deregister it, and re-register it, if it's not
1897          * in use.
1898          * If the disk already exists then deregister it before proceeding
1899          * (unless it's the first disk (for the controller node).
1900          */
1901         if (h->drv[drv_index]->raid_level != -1 && drv_index != 0) {
1902                 printk(KERN_WARNING "disk %d has changed.\n", drv_index);
1903                 spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
1904                 h->drv[drv_index]->busy_configuring = 1;
1905                 spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
1906
1907                 /* deregister_disk sets h->drv[drv_index]->queue = NULL
1908                  * which keeps the interrupt handler from starting
1909                  * the queue.
1910                  */
1911                 ret = deregister_disk(h, drv_index, 0, via_ioctl);
1912         }
1913
1914         /* If the disk is in use return */
1915         if (ret)
1916                 goto freeret;
1917
1918         /* Save the new information from cciss_geometry_inquiry
1919          * and serial number inquiry.  If the disk was deregistered
1920          * above, then h->drv[drv_index] will be NULL.
1921          */
1922         if (h->drv[drv_index] == NULL) {
1923                 drvinfo->device_initialized = 0;
1924                 h->drv[drv_index] = drvinfo;
1925                 drvinfo = NULL; /* so it won't be freed below. */
1926         } else {
1927                 /* special case for cxd0 */
1928                 h->drv[drv_index]->block_size = drvinfo->block_size;
1929                 h->drv[drv_index]->nr_blocks = drvinfo->nr_blocks;
1930                 h->drv[drv_index]->heads = drvinfo->heads;
1931                 h->drv[drv_index]->sectors = drvinfo->sectors;
1932                 h->drv[drv_index]->cylinders = drvinfo->cylinders;
1933                 h->drv[drv_index]->raid_level = drvinfo->raid_level;
1934                 memcpy(h->drv[drv_index]->serial_no, drvinfo->serial_no, 16);
1935                 memcpy(h->drv[drv_index]->vendor, drvinfo->vendor,
1936                         VENDOR_LEN + 1);
1937                 memcpy(h->drv[drv_index]->model, drvinfo->model, MODEL_LEN + 1);
1938                 memcpy(h->drv[drv_index]->rev, drvinfo->rev, REV_LEN + 1);
1939         }
1940
1941         ++h->num_luns;
1942         disk = h->gendisk[drv_index];
1943         set_capacity(disk, h->drv[drv_index]->nr_blocks);
1944
1945         /* If it's not disk 0 (drv_index != 0)
1946          * or if it was disk 0, but there was previously
1947          * no actual corresponding configured logical drive
1948          * (raid_leve == -1) then we want to update the
1949          * logical drive's information.
1950          */
1951         if (drv_index || first_time) {
1952                 if (cciss_add_disk(h, disk, drv_index) != 0) {
1953                         cciss_free_gendisk(h, drv_index);
1954                         cciss_free_drive_info(h, drv_index);
1955                         printk(KERN_WARNING "cciss:%d could not update "
1956                                 "disk %d\n", h->ctlr, drv_index);
1957                         --h->num_luns;
1958                 }
1959         }
1960
1961 freeret:
1962         kfree(inq_buff);
1963         kfree(drvinfo);
1964         return;
1965 mem_msg:
1966         printk(KERN_ERR "cciss: out of memory\n");
1967         goto freeret;
1968 }
1969
1970 /* This function will find the first index of the controllers drive array
1971  * that has a null drv pointer and allocate the drive info struct and
1972  * will return that index   This is where new drives will be added.
1973  * If the index to be returned is greater than the highest_lun index for
1974  * the controller then highest_lun is set * to this new index.
1975  * If there are no available indexes or if tha allocation fails, then -1
1976  * is returned.  * "controller_node" is used to know if this is a real
1977  * logical drive, or just the controller node, which determines if this
1978  * counts towards highest_lun.
1979  */
1980 static int cciss_alloc_drive_info(ctlr_info_t *h, int controller_node)
1981 {
1982         int i;
1983         drive_info_struct *drv;
1984
1985         /* Search for an empty slot for our drive info */
1986         for (i = 0; i < CISS_MAX_LUN; i++) {
1987
1988                 /* if not cxd0 case, and it's occupied, skip it. */
1989                 if (h->drv[i] && i != 0)
1990                         continue;
1991                 /*
1992                  * If it's cxd0 case, and drv is alloc'ed already, and a
1993                  * disk is configured there, skip it.
1994                  */
1995                 if (i == 0 && h->drv[i] && h->drv[i]->raid_level != -1)
1996                         continue;
1997
1998                 /*
1999                  * We've found an empty slot.  Update highest_lun
2000                  * provided this isn't just the fake cxd0 controller node.
2001                  */
2002                 if (i > h->highest_lun && !controller_node)
2003                         h->highest_lun = i;
2004
2005                 /* If adding a real disk at cxd0, and it's already alloc'ed */
2006                 if (i == 0 && h->drv[i] != NULL)
2007                         return i;
2008
2009                 /*
2010                  * Found an empty slot, not already alloc'ed.  Allocate it.
2011                  * Mark it with raid_level == -1, so we know it's new later on.
2012                  */
2013                 drv = kzalloc(sizeof(*drv), GFP_KERNEL);
2014                 if (!drv)
2015                         return -1;
2016                 drv->raid_level = -1; /* so we know it's new */
2017                 h->drv[i] = drv;
2018                 return i;
2019         }
2020         return -1;
2021 }
2022
2023 static void cciss_free_drive_info(ctlr_info_t *h, int drv_index)
2024 {
2025         kfree(h->drv[drv_index]);
2026         h->drv[drv_index] = NULL;
2027 }
2028
2029 static void cciss_free_gendisk(ctlr_info_t *h, int drv_index)
2030 {
2031         put_disk(h->gendisk[drv_index]);
2032         h->gendisk[drv_index] = NULL;
2033 }
2034
2035 /* cciss_add_gendisk finds a free hba[]->drv structure
2036  * and allocates a gendisk if needed, and sets the lunid
2037  * in the drvinfo structure.   It returns the index into
2038  * the ->drv[] array, or -1 if none are free.
2039  * is_controller_node indicates whether highest_lun should
2040  * count this disk, or if it's only being added to provide
2041  * a means to talk to the controller in case no logical
2042  * drives have yet been configured.
2043  */
2044 static int cciss_add_gendisk(ctlr_info_t *h, unsigned char lunid[],
2045         int controller_node)
2046 {
2047         int drv_index;
2048
2049         drv_index = cciss_alloc_drive_info(h, controller_node);
2050         if (drv_index == -1)
2051                 return -1;
2052
2053         /*Check if the gendisk needs to be allocated */
2054         if (!h->gendisk[drv_index]) {
2055                 h->gendisk[drv_index] =
2056                         alloc_disk(1 << NWD_SHIFT);
2057                 if (!h->gendisk[drv_index]) {
2058                         printk(KERN_ERR "cciss%d: could not "
2059                                 "allocate a new disk %d\n",
2060                                 h->ctlr, drv_index);
2061                         goto err_free_drive_info;
2062                 }
2063         }
2064         memcpy(h->drv[drv_index]->LunID, lunid,
2065                 sizeof(h->drv[drv_index]->LunID));
2066         if (cciss_create_ld_sysfs_entry(h, drv_index))
2067                 goto err_free_disk;
2068         /* Don't need to mark this busy because nobody */
2069         /* else knows about this disk yet to contend */
2070         /* for access to it. */
2071         h->drv[drv_index]->busy_configuring = 0;
2072         wmb();
2073         return drv_index;
2074
2075 err_free_disk:
2076         cciss_free_gendisk(h, drv_index);
2077 err_free_drive_info:
2078         cciss_free_drive_info(h, drv_index);
2079         return -1;
2080 }
2081
2082 /* This is for the special case of a controller which
2083  * has no logical drives.  In this case, we still need
2084  * to register a disk so the controller can be accessed
2085  * by the Array Config Utility.
2086  */
2087 static void cciss_add_controller_node(ctlr_info_t *h)
2088 {
2089         struct gendisk *disk;
2090         int drv_index;
2091
2092         if (h->gendisk[0] != NULL) /* already did this? Then bail. */
2093                 return;
2094
2095         drv_index = cciss_add_gendisk(h, CTLR_LUNID, 1);
2096         if (drv_index == -1)
2097                 goto error;
2098         h->drv[drv_index]->block_size = 512;
2099         h->drv[drv_index]->nr_blocks = 0;
2100         h->drv[drv_index]->heads = 0;
2101         h->drv[drv_index]->sectors = 0;
2102         h->drv[drv_index]->cylinders = 0;
2103         h->drv[drv_index]->raid_level = -1;
2104         memset(h->drv[drv_index]->serial_no, 0, 16);
2105         disk = h->gendisk[drv_index];
2106         if (cciss_add_disk(h, disk, drv_index) == 0)
2107                 return;
2108         cciss_free_gendisk(h, drv_index);
2109         cciss_free_drive_info(h, drv_index);
2110 error:
2111         printk(KERN_WARNING "cciss%d: could not "
2112                 "add disk 0.\n", h->ctlr);
2113         return;
2114 }
2115
2116 /* This function will add and remove logical drives from the Logical
2117  * drive array of the controller and maintain persistency of ordering
2118  * so that mount points are preserved until the next reboot.  This allows
2119  * for the removal of logical drives in the middle of the drive array
2120  * without a re-ordering of those drives.
2121  * INPUT
2122  * h            = The controller to perform the operations on
2123  */
2124 static int rebuild_lun_table(ctlr_info_t *h, int first_time,
2125         int via_ioctl)
2126 {
2127         int ctlr = h->ctlr;
2128         int num_luns;
2129         ReportLunData_struct *ld_buff = NULL;
2130         int return_code;
2131         int listlength = 0;
2132         int i;
2133         int drv_found;
2134         int drv_index = 0;
2135         unsigned char lunid[8] = CTLR_LUNID;
2136         unsigned long flags;
2137
2138         if (!capable(CAP_SYS_RAWIO))
2139                 return -EPERM;
2140
2141         /* Set busy_configuring flag for this operation */
2142         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
2143         if (h->busy_configuring) {
2144                 spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
2145                 return -EBUSY;
2146         }
2147         h->busy_configuring = 1;
2148         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
2149
2150         ld_buff = kzalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
2151         if (ld_buff == NULL)
2152                 goto mem_msg;
2153
2154         return_code = sendcmd_withirq(CISS_REPORT_LOG, ctlr, ld_buff,
2155                                       sizeof(ReportLunData_struct),
2156                                       0, CTLR_LUNID, TYPE_CMD);
2157
2158         if (return_code == IO_OK)
2159                 listlength = be32_to_cpu(*(__be32 *) ld_buff->LUNListLength);
2160         else {  /* reading number of logical volumes failed */
2161                 printk(KERN_WARNING "cciss: report logical volume"
2162                        " command failed\n");
2163                 listlength = 0;
2164                 goto freeret;
2165         }
2166
2167         num_luns = listlength / 8;      /* 8 bytes per entry */
2168         if (num_luns > CISS_MAX_LUN) {
2169                 num_luns = CISS_MAX_LUN;
2170                 printk(KERN_WARNING "cciss: more luns configured"
2171                        " on controller than can be handled by"
2172                        " this driver.\n");
2173         }
2174
2175         if (num_luns == 0)
2176                 cciss_add_controller_node(h);
2177
2178         /* Compare controller drive array to driver's drive array
2179          * to see if any drives are missing on the controller due
2180          * to action of Array Config Utility (user deletes drive)
2181          * and deregister logical drives which have disappeared.
2182          */
2183         for (i = 0; i <= h->highest_lun; i++) {
2184                 int j;
2185                 drv_found = 0;
2186
2187                 /* skip holes in the array from already deleted drives */
2188                 if (h->drv[i] == NULL)
2189                         continue;
2190
2191                 for (j = 0; j < num_luns; j++) {
2192                         memcpy(lunid, &ld_buff->LUN[j][0], sizeof(lunid));
2193                         if (memcmp(h->drv[i]->LunID, lunid,
2194                                 sizeof(lunid)) == 0) {
2195                                 drv_found = 1;
2196                                 break;
2197                         }
2198                 }
2199                 if (!drv_found) {
2200                         /* Deregister it from the OS, it's gone. */
2201                         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
2202                         h->drv[i]->busy_configuring = 1;
2203                         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
2204                         return_code = deregister_disk(h, i, 1, via_ioctl);
2205                         if (h->drv[i] != NULL)
2206                                 h->drv[i]->busy_configuring = 0;
2207                 }
2208         }
2209
2210         /* Compare controller drive array to driver's drive array.
2211          * Check for updates in the drive information and any new drives
2212          * on the controller due to ACU adding logical drives, or changing
2213          * a logical drive's size, etc.  Reregister any new/changed drives
2214          */
2215         for (i = 0; i < num_luns; i++) {
2216                 int j;
2217
2218                 drv_found = 0;
2219
2220                 memcpy(lunid, &ld_buff->LUN[i][0], sizeof(lunid));
2221                 /* Find if the LUN is already in the drive array
2222                  * of the driver.  If so then update its info
2223                  * if not in use.  If it does not exist then find
2224                  * the first free index and add it.
2225                  */
2226                 for (j = 0; j <= h->highest_lun; j++) {
2227                         if (h->drv[j] != NULL &&
2228                                 memcmp(h->drv[j]->LunID, lunid,
2229                                         sizeof(h->drv[j]->LunID)) == 0) {
2230                                 drv_index = j;
2231                                 drv_found = 1;
2232                                 break;
2233                         }
2234                 }
2235
2236                 /* check if the drive was found already in the array */
2237                 if (!drv_found) {
2238                         drv_index = cciss_add_gendisk(h, lunid, 0);
2239                         if (drv_index == -1)
2240                                 goto freeret;
2241                 }
2242                 cciss_update_drive_info(ctlr, drv_index, first_time,
2243                         via_ioctl);
2244         }               /* end for */
2245
2246 freeret:
2247         kfree(ld_buff);
2248         h->busy_configuring = 0;
2249         /* We return -1 here to tell the ACU that we have registered/updated
2250          * all of the drives that we can and to keep it from calling us
2251          * additional times.
2252          */
2253         return -1;
2254 mem_msg:
2255         printk(KERN_ERR "cciss: out of memory\n");
2256         h->busy_configuring = 0;
2257         goto freeret;
2258 }
2259
2260 static void cciss_clear_drive_info(drive_info_struct *drive_info)
2261 {
2262         /* zero out the disk size info */
2263         drive_info->nr_blocks = 0;
2264         drive_info->block_size = 0;
2265         drive_info->heads = 0;
2266         drive_info->sectors = 0;
2267         drive_info->cylinders = 0;
2268         drive_info->raid_level = -1;
2269         memset(drive_info->serial_no, 0, sizeof(drive_info->serial_no));
2270         memset(drive_info->model, 0, sizeof(drive_info->model));
2271         memset(drive_info->rev, 0, sizeof(drive_info->rev));
2272         memset(drive_info->vendor, 0, sizeof(drive_info->vendor));
2273         /*
2274          * don't clear the LUNID though, we need to remember which
2275          * one this one is.
2276          */
2277 }
2278
2279 /* This function will deregister the disk and it's queue from the
2280  * kernel.  It must be called with the controller lock held and the
2281  * drv structures busy_configuring flag set.  It's parameters are:
2282  *
2283  * disk = This is the disk to be deregistered
2284  * drv  = This is the drive_info_struct associated with the disk to be
2285  *        deregistered.  It contains information about the disk used
2286  *        by the driver.
2287  * clear_all = This flag determines whether or not the disk information
2288  *             is going to be completely cleared out and the highest_lun
2289  *             reset.  Sometimes we want to clear out information about
2290  *             the disk in preparation for re-adding it.  In this case
2291  *             the highest_lun should be left unchanged and the LunID
2292  *             should not be cleared.
2293  * via_ioctl
2294  *    This indicates whether we've reached this path via ioctl.
2295  *    This affects the maximum usage count allowed for c0d0 to be messed with.
2296  *    If this path is reached via ioctl(), then the max_usage_count will
2297  *    be 1, as the process calling ioctl() has got to have the device open.
2298  *    If we get here via sysfs, then the max usage count will be zero.
2299 */
2300 static int deregister_disk(ctlr_info_t *h, int drv_index,
2301                            int clear_all, int via_ioctl)
2302 {
2303         int i;
2304         struct gendisk *disk;
2305         drive_info_struct *drv;
2306         int recalculate_highest_lun;
2307
2308         if (!capable(CAP_SYS_RAWIO))
2309                 return -EPERM;
2310
2311         drv = h->drv[drv_index];
2312         disk = h->gendisk[drv_index];
2313
2314         /* make sure logical volume is NOT is use */
2315         if (clear_all || (h->gendisk[0] == disk)) {
2316                 if (drv->usage_count > via_ioctl)
2317                         return -EBUSY;
2318         } else if (drv->usage_count > 0)
2319                 return -EBUSY;
2320
2321         recalculate_highest_lun = (drv == h->drv[h->highest_lun]);
2322
2323         /* invalidate the devices and deregister the disk.  If it is disk
2324          * zero do not deregister it but just zero out it's values.  This
2325          * allows us to delete disk zero but keep the controller registered.
2326          */
2327         if (h->gendisk[0] != disk) {
2328                 struct request_queue *q = disk->queue;
2329                 if (disk->flags & GENHD_FL_UP) {
2330                         cciss_destroy_ld_sysfs_entry(h, drv_index, 0);
2331                         del_gendisk(disk);
2332                 }
2333                 if (q)
2334                         blk_cleanup_queue(q);
2335                 /* If clear_all is set then we are deleting the logical
2336                  * drive, not just refreshing its info.  For drives
2337                  * other than disk 0 we will call put_disk.  We do not
2338                  * do this for disk 0 as we need it to be able to
2339                  * configure the controller.
2340                  */
2341                 if (clear_all){
2342                         /* This isn't pretty, but we need to find the
2343                          * disk in our array and NULL our the pointer.
2344                          * This is so that we will call alloc_disk if
2345                          * this index is used again later.
2346                          */
2347                         for (i=0; i < CISS_MAX_LUN; i++){
2348                                 if (h->gendisk[i] == disk) {
2349                                         h->gendisk[i] = NULL;
2350                                         break;
2351                                 }
2352                         }
2353                         put_disk(disk);
2354                 }
2355         } else {
2356                 set_capacity(disk, 0);
2357                 cciss_clear_drive_info(drv);
2358         }
2359
2360         --h->num_luns;
2361
2362         /* if it was the last disk, find the new hightest lun */
2363         if (clear_all && recalculate_highest_lun) {
2364                 int i, newhighest = -1;
2365                 for (i = 0; i <= h->highest_lun; i++) {
2366                         /* if the disk has size > 0, it is available */
2367                         if (h->drv[i] && h->drv[i]->heads)
2368                                 newhighest = i;
2369                 }
2370                 h->highest_lun = newhighest;
2371         }
2372         return 0;
2373 }
2374
2375 static int fill_cmd(CommandList_struct *c, __u8 cmd, int ctlr, void *buff,
2376                 size_t size, __u8 page_code, unsigned char *scsi3addr,
2377                 int cmd_type)
2378 {
2379         ctlr_info_t *h = hba[ctlr];
2380         u64bit buff_dma_handle;
2381         int status = IO_OK;
2382
2383         c->cmd_type = CMD_IOCTL_PEND;
2384         c->Header.ReplyQueue = 0;
2385         if (buff != NULL) {
2386                 c->Header.SGList = 1;
2387                 c->Header.SGTotal = 1;
2388         } else {
2389                 c->Header.SGList = 0;
2390                 c->Header.SGTotal = 0;
2391         }
2392         c->Header.Tag.lower = c->busaddr;
2393         memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
2394
2395         c->Request.Type.Type = cmd_type;
2396         if (cmd_type == TYPE_CMD) {
2397                 switch (cmd) {
2398                 case CISS_INQUIRY:
2399                         /* are we trying to read a vital product page */
2400                         if (page_code != 0) {
2401                                 c->Request.CDB[1] = 0x01;
2402                                 c->Request.CDB[2] = page_code;
2403                         }
2404                         c->Request.CDBLen = 6;
2405                         c->Request.Type.Attribute = ATTR_SIMPLE;
2406                         c->Request.Type.Direction = XFER_READ;
2407                         c->Request.Timeout = 0;
2408                         c->Request.CDB[0] = CISS_INQUIRY;
2409                         c->Request.CDB[4] = size & 0xFF;
2410                         break;
2411                 case CISS_REPORT_LOG:
2412                 case CISS_REPORT_PHYS:
2413                         /* Talking to controller so It's a physical command
2414                            mode = 00 target = 0.  Nothing to write.
2415                          */
2416                         c->Request.CDBLen = 12;
2417                         c->Request.Type.Attribute = ATTR_SIMPLE;
2418                         c->Request.Type.Direction = XFER_READ;
2419                         c->Request.Timeout = 0;
2420                         c->Request.CDB[0] = cmd;
2421                         c->Request.CDB[6] = (size >> 24) & 0xFF;        //MSB
2422                         c->Request.CDB[7] = (size >> 16) & 0xFF;
2423                         c->Request.CDB[8] = (size >> 8) & 0xFF;
2424                         c->Request.CDB[9] = size & 0xFF;
2425                         break;
2426
2427                 case CCISS_READ_CAPACITY:
2428                         c->Request.CDBLen = 10;
2429                         c->Request.Type.Attribute = ATTR_SIMPLE;
2430                         c->Request.Type.Direction = XFER_READ;
2431                         c->Request.Timeout = 0;
2432                         c->Request.CDB[0] = cmd;
2433                         break;
2434                 case CCISS_READ_CAPACITY_16:
2435                         c->Request.CDBLen = 16;
2436                         c->Request.Type.Attribute = ATTR_SIMPLE;
2437                         c->Request.Type.Direction = XFER_READ;
2438                         c->Request.Timeout = 0;
2439                         c->Request.CDB[0] = cmd;
2440                         c->Request.CDB[1] = 0x10;
2441                         c->Request.CDB[10] = (size >> 24) & 0xFF;
2442                         c->Request.CDB[11] = (size >> 16) & 0xFF;
2443                         c->Request.CDB[12] = (size >> 8) & 0xFF;
2444                         c->Request.CDB[13] = size & 0xFF;
2445                         c->Request.Timeout = 0;
2446                         c->Request.CDB[0] = cmd;
2447                         break;
2448                 case CCISS_CACHE_FLUSH:
2449                         c->Request.CDBLen = 12;
2450                         c->Request.Type.Attribute = ATTR_SIMPLE;
2451                         c->Request.Type.Direction = XFER_WRITE;
2452                         c->Request.Timeout = 0;
2453                         c->Request.CDB[0] = BMIC_WRITE;
2454                         c->Request.CDB[6] = BMIC_CACHE_FLUSH;
2455                         break;
2456                 case TEST_UNIT_READY:
2457                         c->Request.CDBLen = 6;
2458                         c->Request.Type.Attribute = ATTR_SIMPLE;
2459                         c->Request.Type.Direction = XFER_NONE;
2460                         c->Request.Timeout = 0;
2461                         break;
2462                 default:
2463                         printk(KERN_WARNING
2464                                "cciss%d:  Unknown Command 0x%c\n", ctlr, cmd);
2465                         return IO_ERROR;
2466                 }
2467         } else if (cmd_type == TYPE_MSG) {
2468                 switch (cmd) {
2469                 case 0: /* ABORT message */
2470                         c->Request.CDBLen = 12;
2471                         c->Request.Type.Attribute = ATTR_SIMPLE;
2472                         c->Request.Type.Direction = XFER_WRITE;
2473                         c->Request.Timeout = 0;
2474                         c->Request.CDB[0] = cmd;        /* abort */
2475                         c->Request.CDB[1] = 0;  /* abort a command */
2476                         /* buff contains the tag of the command to abort */
2477                         memcpy(&c->Request.CDB[4], buff, 8);
2478                         break;
2479                 case 1: /* RESET message */
2480                         c->Request.CDBLen = 16;
2481                         c->Request.Type.Attribute = ATTR_SIMPLE;
2482                         c->Request.Type.Direction = XFER_NONE;
2483                         c->Request.Timeout = 0;
2484                         memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
2485                         c->Request.CDB[0] = cmd;        /* reset */
2486                         c->Request.CDB[1] = 0x03;       /* reset a target */
2487                         break;
2488                 case 3: /* No-Op message */
2489                         c->Request.CDBLen = 1;
2490                         c->Request.Type.Attribute = ATTR_SIMPLE;
2491                         c->Request.Type.Direction = XFER_WRITE;
2492                         c->Request.Timeout = 0;
2493                         c->Request.CDB[0] = cmd;
2494                         break;
2495                 default:
2496                         printk(KERN_WARNING
2497                                "cciss%d: unknown message type %d\n", ctlr, cmd);
2498                         return IO_ERROR;
2499                 }
2500         } else {
2501                 printk(KERN_WARNING
2502                        "cciss%d: unknown command type %d\n", ctlr, cmd_type);
2503                 return IO_ERROR;
2504         }
2505         /* Fill in the scatter gather information */
2506         if (size > 0) {
2507                 buff_dma_handle.val = (__u64) pci_map_single(h->pdev,
2508                                                              buff, size,
2509                                                              PCI_DMA_BIDIRECTIONAL);
2510                 c->SG[0].Addr.lower = buff_dma_handle.val32.lower;
2511                 c->SG[0].Addr.upper = buff_dma_handle.val32.upper;
2512                 c->SG[0].Len = size;
2513                 c->SG[0].Ext = 0;       /* we are not chaining */
2514         }
2515         return status;
2516 }
2517
2518 static int check_target_status(ctlr_info_t *h, CommandList_struct *c)
2519 {
2520         switch (c->err_info->ScsiStatus) {
2521         case SAM_STAT_GOOD:
2522                 return IO_OK;
2523         case SAM_STAT_CHECK_CONDITION:
2524                 switch (0xf & c->err_info->SenseInfo[2]) {
2525                 case 0: return IO_OK; /* no sense */
2526                 case 1: return IO_OK; /* recovered error */
2527                 default:
2528                         printk(KERN_WARNING "cciss%d: cmd 0x%02x "
2529                                 "check condition, sense key = 0x%02x\n",
2530                                 h->ctlr, c->Request.CDB[0],
2531                                 c->err_info->SenseInfo[2]);
2532                 }
2533                 break;
2534         default:
2535                 printk(KERN_WARNING "cciss%d: cmd 0x%02x"
2536                         "scsi status = 0x%02x\n", h->ctlr,
2537                         c->Request.CDB[0], c->err_info->ScsiStatus);
2538                 break;
2539         }
2540         return IO_ERROR;
2541 }
2542
2543 static int process_sendcmd_error(ctlr_info_t *h, CommandList_struct *c)
2544 {
2545         int return_status = IO_OK;
2546
2547         if (c->err_info->CommandStatus == CMD_SUCCESS)
2548                 return IO_OK;
2549
2550         switch (c->err_info->CommandStatus) {
2551         case CMD_TARGET_STATUS:
2552                 return_status = check_target_status(h, c);
2553                 break;
2554         case CMD_DATA_UNDERRUN:
2555         case CMD_DATA_OVERRUN:
2556                 /* expected for inquiry and report lun commands */
2557                 break;
2558         case CMD_INVALID:
2559                 printk(KERN_WARNING "cciss: cmd 0x%02x is "
2560                        "reported invalid\n", c->Request.CDB[0]);
2561                 return_status = IO_ERROR;
2562                 break;
2563         case CMD_PROTOCOL_ERR:
2564                 printk(KERN_WARNING "cciss: cmd 0x%02x has "
2565                        "protocol error \n", c->Request.CDB[0]);
2566                 return_status = IO_ERROR;
2567                 break;
2568         case CMD_HARDWARE_ERR:
2569                 printk(KERN_WARNING "cciss: cmd 0x%02x had "
2570                        " hardware error\n", c->Request.CDB[0]);
2571                 return_status = IO_ERROR;
2572                 break;
2573         case CMD_CONNECTION_LOST:
2574                 printk(KERN_WARNING "cciss: cmd 0x%02x had "
2575                        "connection lost\n", c->Request.CDB[0]);
2576                 return_status = IO_ERROR;
2577                 break;
2578         case CMD_ABORTED:
2579                 printk(KERN_WARNING "cciss: cmd 0x%02x was "
2580                        "aborted\n", c->Request.CDB[0]);
2581                 return_status = IO_ERROR;
2582                 break;
2583         case CMD_ABORT_FAILED:
2584                 printk(KERN_WARNING "cciss: cmd 0x%02x reports "
2585                        "abort failed\n", c->Request.CDB[0]);
2586                 return_status = IO_ERROR;
2587                 break;
2588         case CMD_UNSOLICITED_ABORT:
2589                 printk(KERN_WARNING
2590                        "cciss%d: unsolicited abort 0x%02x\n", h->ctlr,
2591                         c->Request.CDB[0]);
2592                 return_status = IO_NEEDS_RETRY;
2593                 break;
2594         default:
2595                 printk(KERN_WARNING "cciss: cmd 0x%02x returned "
2596                        "unknown status %x\n", c->Request.CDB[0],
2597                        c->err_info->CommandStatus);
2598                 return_status = IO_ERROR;
2599         }
2600         return return_status;
2601 }
2602
2603 static int sendcmd_withirq_core(ctlr_info_t *h, CommandList_struct *c,
2604         int attempt_retry)
2605 {
2606         DECLARE_COMPLETION_ONSTACK(wait);
2607         u64bit buff_dma_handle;
2608         unsigned long flags;
2609         int return_status = IO_OK;
2610
2611 resend_cmd2:
2612         c->waiting = &wait;
2613         /* Put the request on the tail of the queue and send it */
2614         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
2615         addQ(&h->reqQ, c);
2616         h->Qdepth++;
2617         start_io(h);
2618         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
2619
2620         wait_for_completion(&wait);
2621
2622         if (c->err_info->CommandStatus == 0 || !attempt_retry)
2623                 goto command_done;
2624
2625         return_status = process_sendcmd_error(h, c);
2626
2627         if (return_status == IO_NEEDS_RETRY &&
2628                 c->retry_count < MAX_CMD_RETRIES) {
2629                 printk(KERN_WARNING "cciss%d: retrying 0x%02x\n", h->ctlr,
2630                         c->Request.CDB[0]);
2631                 c->retry_count++;
2632                 /* erase the old error information */
2633                 memset(c->err_info, 0, sizeof(ErrorInfo_struct));
2634                 return_status = IO_OK;
2635                 INIT_COMPLETION(wait);
2636                 goto resend_cmd2;
2637         }
2638
2639 command_done:
2640         /* unlock the buffers from DMA */
2641         buff_dma_handle.val32.lower = c->SG[0].Addr.lower;
2642         buff_dma_handle.val32.upper = c->SG[0].Addr.upper;
2643         pci_unmap_single(h->pdev, (dma_addr_t) buff_dma_handle.val,
2644                          c->SG[0].Len, PCI_DMA_BIDIRECTIONAL);
2645         return return_status;
2646 }
2647
2648 static int sendcmd_withirq(__u8 cmd, int ctlr, void *buff, size_t size,
2649                            __u8 page_code, unsigned char scsi3addr[],
2650                         int cmd_type)
2651 {
2652         ctlr_info_t *h = hba[ctlr];
2653         CommandList_struct *c;
2654         int return_status;
2655
2656         c = cmd_alloc(h, 0);
2657         if (!c)
2658                 return -ENOMEM;
2659         return_status = fill_cmd(c, cmd, ctlr, buff, size, page_code,
2660                 scsi3addr, cmd_type);
2661         if (return_status == IO_OK)
2662                 return_status = sendcmd_withirq_core(h, c, 1);
2663
2664         cmd_free(h, c, 0);
2665         return return_status;
2666 }
2667
2668 static void cciss_geometry_inquiry(int ctlr, int logvol,
2669                                    int withirq, sector_t total_size,
2670                                    unsigned int block_size,
2671                                    InquiryData_struct *inq_buff,
2672                                    drive_info_struct *drv)
2673 {
2674         int return_code;
2675         unsigned long t;
2676         unsigned char scsi3addr[8];
2677
2678         memset(inq_buff, 0, sizeof(InquiryData_struct));
2679         log_unit_to_scsi3addr(hba[ctlr], scsi3addr, logvol);
2680         if (withirq)
2681                 return_code = sendcmd_withirq(CISS_INQUIRY, ctlr,
2682                                               inq_buff, sizeof(*inq_buff),
2683                                               0xC1, scsi3addr, TYPE_CMD);
2684         else
2685                 return_code = sendcmd(CISS_INQUIRY, ctlr, inq_buff,
2686                                       sizeof(*inq_buff), 0xC1, scsi3addr,
2687                                       TYPE_CMD);
2688         if (return_code == IO_OK) {
2689                 if (inq_buff->data_byte[8] == 0xFF) {
2690                         printk(KERN_WARNING
2691                                "cciss: reading geometry failed, volume "
2692                                "does not support reading geometry\n");
2693                         drv->heads = 255;
2694                         drv->sectors = 32;      // Sectors per track
2695                         drv->cylinders = total_size + 1;
2696                         drv->raid_level = RAID_UNKNOWN;
2697                 } else {
2698                         drv->heads = inq_buff->data_byte[6];
2699                         drv->sectors = inq_buff->data_byte[7];
2700                         drv->cylinders = (inq_buff->data_byte[4] & 0xff) << 8;
2701                         drv->cylinders += inq_buff->data_byte[5];
2702                         drv->raid_level = inq_buff->data_byte[8];
2703                 }
2704                 drv->block_size = block_size;
2705                 drv->nr_blocks = total_size + 1;
2706                 t = drv->heads * drv->sectors;
2707                 if (t > 1) {
2708                         sector_t real_size = total_size + 1;
2709                         unsigned long rem = sector_div(real_size, t);
2710                         if (rem)
2711                                 real_size++;
2712                         drv->cylinders = real_size;
2713                 }
2714         } else {                /* Get geometry failed */
2715                 printk(KERN_WARNING "cciss: reading geometry failed\n");
2716         }
2717 }
2718
2719 static void
2720 cciss_read_capacity(int ctlr, int logvol, int withirq, sector_t *total_size,
2721                     unsigned int *block_size)
2722 {
2723         ReadCapdata_struct *buf;
2724         int return_code;
2725         unsigned char scsi3addr[8];
2726
2727         buf = kzalloc(sizeof(ReadCapdata_struct), GFP_KERNEL);
2728         if (!buf) {
2729                 printk(KERN_WARNING "cciss: out of memory\n");
2730                 return;
2731         }
2732
2733         log_unit_to_scsi3addr(hba[ctlr], scsi3addr, logvol);
2734         if (withirq)
2735                 return_code = sendcmd_withirq(CCISS_READ_CAPACITY,
2736                                 ctlr, buf, sizeof(ReadCapdata_struct),
2737                                         0, scsi3addr, TYPE_CMD);
2738         else
2739                 return_code = sendcmd(CCISS_READ_CAPACITY,
2740                                 ctlr, buf, sizeof(ReadCapdata_struct),
2741                                         0, scsi3addr, TYPE_CMD);
2742         if (return_code == IO_OK) {
2743                 *total_size = be32_to_cpu(*(__be32 *) buf->total_size);
2744                 *block_size = be32_to_cpu(*(__be32 *) buf->block_size);
2745         } else {                /* read capacity command failed */
2746                 printk(KERN_WARNING "cciss: read capacity failed\n");
2747                 *total_size = 0;
2748                 *block_size = BLOCK_SIZE;
2749         }
2750         kfree(buf);
2751 }
2752
2753 static void
2754 cciss_read_capacity_16(int ctlr, int logvol, int withirq, sector_t *total_size,                                 unsigned int *block_size)
2755 {
2756         ReadCapdata_struct_16 *buf;
2757         int return_code;
2758         unsigned char scsi3addr[8];
2759
2760         buf = kzalloc(sizeof(ReadCapdata_struct_16), GFP_KERNEL);
2761         if (!buf) {
2762                 printk(KERN_WARNING "cciss: out of memory\n");
2763                 return;
2764         }
2765
2766         log_unit_to_scsi3addr(hba[ctlr], scsi3addr, logvol);
2767         if (withirq) {
2768                 return_code = sendcmd_withirq(CCISS_READ_CAPACITY_16,
2769                         ctlr, buf, sizeof(ReadCapdata_struct_16),
2770                                 0, scsi3addr, TYPE_CMD);
2771         }
2772         else {
2773                 return_code = sendcmd(CCISS_READ_CAPACITY_16,
2774                         ctlr, buf, sizeof(ReadCapdata_struct_16),
2775                                 0, scsi3addr, TYPE_CMD);
2776         }
2777         if (return_code == IO_OK) {
2778                 *total_size = be64_to_cpu(*(__be64 *) buf->total_size);
2779                 *block_size = be32_to_cpu(*(__be32 *) buf->block_size);
2780         } else {                /* read capacity command failed */
2781                 printk(KERN_WARNING "cciss: read capacity failed\n");
2782                 *total_size = 0;
2783                 *block_size = BLOCK_SIZE;
2784         }
2785         printk(KERN_INFO "      blocks= %llu block_size= %d\n",
2786                (unsigned long long)*total_size+1, *block_size);
2787         kfree(buf);
2788 }
2789
2790 static int cciss_revalidate(struct gendisk *disk)
2791 {
2792         ctlr_info_t *h = get_host(disk);
2793         drive_info_struct *drv = get_drv(disk);
2794         int logvol;
2795         int FOUND = 0;
2796         unsigned int block_size;
2797         sector_t total_size;
2798         InquiryData_struct *inq_buff = NULL;
2799
2800         for (logvol = 0; logvol < CISS_MAX_LUN; logvol++) {
2801                 if (memcmp(h->drv[logvol]->LunID, drv->LunID,
2802                         sizeof(drv->LunID)) == 0) {
2803                         FOUND = 1;
2804                         break;
2805                 }
2806         }
2807
2808         if (!FOUND)
2809                 return 1;
2810
2811         inq_buff = kmalloc(sizeof(InquiryData_struct), GFP_KERNEL);
2812         if (inq_buff == NULL) {
2813                 printk(KERN_WARNING "cciss: out of memory\n");
2814                 return 1;
2815         }
2816         if (h->cciss_read == CCISS_READ_10) {
2817                 cciss_read_capacity(h->ctlr, logvol, 1,
2818                                         &total_size, &block_size);
2819         } else {
2820                 cciss_read_capacity_16(h->ctlr, logvol, 1,
2821                                         &total_size, &block_size);
2822         }
2823         cciss_geometry_inquiry(h->ctlr, logvol, 1, total_size, block_size,
2824                                inq_buff, drv);
2825
2826         blk_queue_logical_block_size(drv->queue, drv->block_size);
2827         set_capacity(disk, drv->nr_blocks);
2828
2829         kfree(inq_buff);
2830         return 0;
2831 }
2832
2833 /*
2834  *   Wait polling for a command to complete.
2835  *   The memory mapped FIFO is polled for the completion.
2836  *   Used only at init time, interrupts from the HBA are disabled.
2837  */
2838 static unsigned long pollcomplete(int ctlr)
2839 {
2840         unsigned long done;
2841         int i;
2842
2843         /* Wait (up to 20 seconds) for a command to complete */
2844
2845         for (i = 20 * HZ; i > 0; i--) {
2846                 done = hba[ctlr]->access.command_completed(hba[ctlr]);
2847                 if (done == FIFO_EMPTY)
2848                         schedule_timeout_uninterruptible(1);
2849                 else
2850                         return done;
2851         }
2852         /* Invalid address to tell caller we ran out of time */
2853         return 1;
2854 }
2855
2856 /* Send command c to controller h and poll for it to complete.
2857  * Turns interrupts off on the board.  Used at driver init time
2858  * and during SCSI error recovery.
2859  */
2860 static int sendcmd_core(ctlr_info_t *h, CommandList_struct *c)
2861 {
2862         int i;
2863         unsigned long complete;
2864         int status = IO_ERROR;
2865         u64bit buff_dma_handle;
2866
2867 resend_cmd1:
2868
2869         /* Disable interrupt on the board. */
2870         h->access.set_intr_mask(h, CCISS_INTR_OFF);
2871
2872         /* Make sure there is room in the command FIFO */
2873         /* Actually it should be completely empty at this time */
2874         /* unless we are in here doing error handling for the scsi */
2875         /* tape side of the driver. */
2876         for (i = 200000; i > 0; i--) {
2877                 /* if fifo isn't full go */
2878                 if (!(h->access.fifo_full(h)))
2879                         break;
2880                 udelay(10);
2881                 printk(KERN_WARNING "cciss cciss%d: SendCmd FIFO full,"
2882                        " waiting!\n", h->ctlr);
2883         }
2884         h->access.submit_command(h, c); /* Send the cmd */
2885         do {
2886                 complete = pollcomplete(h->ctlr);
2887
2888 #ifdef CCISS_DEBUG
2889                 printk(KERN_DEBUG "cciss: command completed\n");
2890 #endif                          /* CCISS_DEBUG */
2891
2892                 if (complete == 1) {
2893                         printk(KERN_WARNING
2894                                "cciss cciss%d: SendCmd Timeout out, "
2895                                "No command list address returned!\n", h->ctlr);
2896                         status = IO_ERROR;
2897                         break;
2898                 }
2899
2900                 /* Make sure it's the command we're expecting. */
2901                 if ((complete & ~CISS_ERROR_BIT) != c->busaddr) {
2902                         printk(KERN_WARNING "cciss%d: Unexpected command "
2903                                 "completion.\n", h->ctlr);
2904                         continue;
2905                 }
2906
2907                 /* It is our command.  If no error, we're done. */
2908                 if (!(complete & CISS_ERROR_BIT)) {
2909                         status = IO_OK;
2910                         break;
2911                 }
2912
2913                 /* There is an error... */
2914
2915                 /* if data overrun or underun on Report command ignore it */
2916                 if (((c->Request.CDB[0] == CISS_REPORT_LOG) ||
2917                      (c->Request.CDB[0] == CISS_REPORT_PHYS) ||
2918                      (c->Request.CDB[0] == CISS_INQUIRY)) &&
2919                         ((c->err_info->CommandStatus == CMD_DATA_OVERRUN) ||
2920                          (c->err_info->CommandStatus == CMD_DATA_UNDERRUN))) {
2921                         complete = c->busaddr;
2922                         status = IO_OK;
2923                         break;
2924                 }
2925
2926                 if (c->err_info->CommandStatus == CMD_UNSOLICITED_ABORT) {
2927                         printk(KERN_WARNING "cciss%d: unsolicited abort %p\n",
2928                                 h->ctlr, c);
2929                         if (c->retry_count < MAX_CMD_RETRIES) {
2930                                 printk(KERN_WARNING "cciss%d: retrying %p\n",
2931                                    h->ctlr, c);
2932                                 c->retry_count++;
2933                                 /* erase the old error information */
2934                                 memset(c->err_info, 0, sizeof(c->err_info));
2935                                 goto resend_cmd1;
2936                         }
2937                         printk(KERN_WARNING "cciss%d: retried %p too many "
2938                                 "times\n", h->ctlr, c);
2939                         status = IO_ERROR;
2940                         break;
2941                 }
2942
2943                 if (c->err_info->CommandStatus == CMD_UNABORTABLE) {
2944                         printk(KERN_WARNING "cciss%d: command could not be "
2945                                 "aborted.\n", h->ctlr);
2946                         status = IO_ERROR;
2947                         break;
2948                 }
2949
2950                 if (c->err_info->CommandStatus == CMD_TARGET_STATUS) {
2951                         status = check_target_status(h, c);
2952                         break;
2953                 }
2954
2955                 printk(KERN_WARNING "cciss%d: sendcmd error\n", h->ctlr);
2956                 printk(KERN_WARNING "cmd = 0x%02x, CommandStatus = 0x%02x\n",
2957                         c->Request.CDB[0], c->err_info->CommandStatus);
2958                 status = IO_ERROR;
2959                 break;
2960
2961         } while (1);
2962
2963         /* unlock the data buffer from DMA */
2964         buff_dma_handle.val32.lower = c->SG[0].Addr.lower;
2965         buff_dma_handle.val32.upper = c->SG[0].Addr.upper;
2966         pci_unmap_single(h->pdev, (dma_addr_t) buff_dma_handle.val,
2967                          c->SG[0].Len, PCI_DMA_BIDIRECTIONAL);
2968         return status;
2969 }
2970
2971 /*
2972  * Send a command to the controller, and wait for it to complete.
2973  * Used at init time, and during SCSI error recovery.
2974  */
2975 static int sendcmd(__u8 cmd, int ctlr, void *buff, size_t size,
2976         __u8 page_code, unsigned char *scsi3addr, int cmd_type)
2977 {
2978         CommandList_struct *c;
2979         int status;
2980
2981         c = cmd_alloc(hba[ctlr], 1);
2982         if (!c) {
2983                 printk(KERN_WARNING "cciss: unable to get memory");
2984                 return IO_ERROR;
2985         }
2986         status = fill_cmd(c, cmd, ctlr, buff, size, page_code,
2987                 scsi3addr, cmd_type);
2988         if (status == IO_OK)
2989                 status = sendcmd_core(hba[ctlr], c);
2990         cmd_free(hba[ctlr], c, 1);
2991         return status;
2992 }
2993
2994 /*
2995  * Map (physical) PCI mem into (virtual) kernel space
2996  */
2997 static void __iomem *remap_pci_mem(ulong base, ulong size)
2998 {
2999         ulong page_base = ((ulong) base) & PAGE_MASK;
3000         ulong page_offs = ((ulong) base) - page_base;
3001         void __iomem *page_remapped = ioremap(page_base, page_offs + size);
3002
3003         return page_remapped ? (page_remapped + page_offs) : NULL;
3004 }
3005
3006 /*
3007  * Takes jobs of the Q and sends them to the hardware, then puts it on
3008  * the Q to wait for completion.
3009  */
3010 static void start_io(ctlr_info_t *h)
3011 {
3012         CommandList_struct *c;
3013
3014         while (!hlist_empty(&h->reqQ)) {
3015                 c = hlist_entry(h->reqQ.first, CommandList_struct, list);
3016                 /* can't do anything if fifo is full */
3017                 if ((h->access.fifo_full(h))) {
3018                         printk(KERN_WARNING "cciss: fifo full\n");
3019                         break;
3020                 }
3021
3022                 /* Get the first entry from the Request Q */
3023                 removeQ(c);
3024                 h->Qdepth--;
3025
3026                 /* Tell the controller execute command */
3027                 h->access.submit_command(h, c);
3028
3029                 /* Put job onto the completed Q */
3030                 addQ(&h->cmpQ, c);
3031         }
3032 }
3033
3034 /* Assumes that CCISS_LOCK(h->ctlr) is held. */
3035 /* Zeros out the error record and then resends the command back */
3036 /* to the controller */
3037 static inline void resend_cciss_cmd(ctlr_info_t *h, CommandList_struct *c)
3038 {
3039         /* erase the old error information */
3040         memset(c->err_info, 0, sizeof(ErrorInfo_struct));
3041
3042         /* add it to software queue and then send it to the controller */
3043         addQ(&h->reqQ, c);
3044         h->Qdepth++;
3045         if (h->Qdepth > h->maxQsinceinit)
3046                 h->maxQsinceinit = h->Qdepth;
3047
3048         start_io(h);
3049 }
3050
3051 static inline unsigned int make_status_bytes(unsigned int scsi_status_byte,
3052         unsigned int msg_byte, unsigned int host_byte,
3053         unsigned int driver_byte)
3054 {
3055         /* inverse of macros in scsi.h */
3056         return (scsi_status_byte & 0xff) |
3057                 ((msg_byte & 0xff) << 8) |
3058                 ((host_byte & 0xff) << 16) |
3059                 ((driver_byte & 0xff) << 24);
3060 }
3061
3062 static inline int evaluate_target_status(ctlr_info_t *h,
3063                         CommandList_struct *cmd, int *retry_cmd)
3064 {
3065         unsigned char sense_key;
3066         unsigned char status_byte, msg_byte, host_byte, driver_byte;
3067         int error_value;
3068
3069         *retry_cmd = 0;
3070         /* If we get in here, it means we got "target status", that is, scsi status */
3071         status_byte = cmd->err_info->ScsiStatus;
3072         driver_byte = DRIVER_OK;
3073         msg_byte = cmd->err_info->CommandStatus; /* correct?  seems too device specific */
3074
3075         if (blk_pc_request(cmd->rq))
3076                 host_byte = DID_PASSTHROUGH;
3077         else
3078                 host_byte = DID_OK;
3079
3080         error_value = make_status_bytes(status_byte, msg_byte,
3081                 host_byte, driver_byte);
3082
3083         if (cmd->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION) {
3084                 if (!blk_pc_request(cmd->rq))
3085                         printk(KERN_WARNING "cciss: cmd %p "
3086                                "has SCSI Status 0x%x\n",
3087                                cmd, cmd->err_info->ScsiStatus);
3088                 return error_value;
3089         }
3090
3091         /* check the sense key */
3092         sense_key = 0xf & cmd->err_info->SenseInfo[2];
3093         /* no status or recovered error */
3094         if (((sense_key == 0x0) || (sense_key == 0x1)) && !blk_pc_request(cmd->rq))
3095                 error_value = 0;
3096
3097         if (check_for_unit_attention(h, cmd)) {
3098                 *retry_cmd = !blk_pc_request(cmd->rq);
3099                 return 0;
3100         }
3101
3102         if (!blk_pc_request(cmd->rq)) { /* Not SG_IO or similar? */
3103                 if (error_value != 0)
3104                         printk(KERN_WARNING "cciss: cmd %p has CHECK CONDITION"
3105                                " sense key = 0x%x\n", cmd, sense_key);
3106                 return error_value;
3107         }
3108
3109         /* SG_IO or similar, copy sense data back */
3110         if (cmd->rq->sense) {
3111                 if (cmd->rq->sense_len > cmd->err_info->SenseLen)
3112                         cmd->rq->sense_len = cmd->err_info->SenseLen;
3113                 memcpy(cmd->rq->sense, cmd->err_info->SenseInfo,
3114                         cmd->rq->sense_len);
3115         } else
3116                 cmd->rq->sense_len = 0;
3117
3118         return error_value;
3119 }
3120
3121 /* checks the status of the job and calls complete buffers to mark all
3122  * buffers for the completed job. Note that this function does not need
3123  * to hold the hba/queue lock.
3124  */
3125 static inline void complete_command(ctlr_info_t *h, CommandList_struct *cmd,
3126                                     int timeout)
3127 {
3128         int retry_cmd = 0;
3129         struct request *rq = cmd->rq;
3130
3131         rq->errors = 0;
3132
3133         if (timeout)
3134                 rq->errors = make_status_bytes(0, 0, 0, DRIVER_TIMEOUT);
3135
3136         if (cmd->err_info->CommandStatus == 0)  /* no error has occurred */
3137                 goto after_error_processing;
3138
3139         switch (cmd->err_info->CommandStatus) {
3140         case CMD_TARGET_STATUS:
3141                 rq->errors = evaluate_target_status(h, cmd, &retry_cmd);
3142                 break;
3143         case CMD_DATA_UNDERRUN:
3144                 if (blk_fs_request(cmd->rq)) {
3145                         printk(KERN_WARNING "cciss: cmd %p has"
3146                                " completed with data underrun "
3147                                "reported\n", cmd);
3148                         cmd->rq->resid_len = cmd->err_info->ResidualCnt;
3149                 }
3150                 break;
3151         case CMD_DATA_OVERRUN:
3152                 if (blk_fs_request(cmd->rq))
3153                         printk(KERN_WARNING "cciss: cmd %p has"
3154                                " completed with data overrun "
3155                                "reported\n", cmd);
3156                 break;
3157         case CMD_INVALID:
3158                 printk(KERN_WARNING "cciss: cmd %p is "
3159                        "reported invalid\n", cmd);
3160                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3161                         cmd->err_info->CommandStatus, DRIVER_OK,
3162                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3163                 break;
3164         case CMD_PROTOCOL_ERR:
3165                 printk(KERN_WARNING "cciss: cmd %p has "
3166                        "protocol error \n", cmd);
3167                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3168                         cmd->err_info->CommandStatus, DRIVER_OK,
3169                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3170                 break;
3171         case CMD_HARDWARE_ERR:
3172                 printk(KERN_WARNING "cciss: cmd %p had "
3173                        " hardware error\n", cmd);
3174                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3175                         cmd->err_info->CommandStatus, DRIVER_OK,
3176                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3177                 break;
3178         case CMD_CONNECTION_LOST:
3179                 printk(KERN_WARNING "cciss: cmd %p had "
3180                        "connection lost\n", cmd);
3181                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3182                         cmd->err_info->CommandStatus, DRIVER_OK,
3183                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3184                 break;
3185         case CMD_ABORTED:
3186                 printk(KERN_WARNING "cciss: cmd %p was "
3187                        "aborted\n", cmd);
3188                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3189                         cmd->err_info->CommandStatus, DRIVER_OK,
3190                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ABORT);
3191                 break;
3192         case CMD_ABORT_FAILED:
3193                 printk(KERN_WARNING "cciss: cmd %p reports "
3194                        "abort failed\n", cmd);
3195                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3196                         cmd->err_info->CommandStatus, DRIVER_OK,
3197                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3198                 break;
3199         case CMD_UNSOLICITED_ABORT:
3200                 printk(KERN_WARNING "cciss%d: unsolicited "
3201                        "abort %p\n", h->ctlr, cmd);
3202                 if (cmd->retry_count < MAX_CMD_RETRIES) {
3203                         retry_cmd = 1;
3204                         printk(KERN_WARNING
3205                                "cciss%d: retrying %p\n", h->ctlr, cmd);
3206                         cmd->retry_count++;
3207                 } else
3208                         printk(KERN_WARNING
3209                                "cciss%d: %p retried too "
3210                                "many times\n", h->ctlr, cmd);
3211                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3212                         cmd->err_info->CommandStatus, DRIVER_OK,
3213                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ABORT);
3214                 break;
3215         case CMD_TIMEOUT:
3216                 printk(KERN_WARNING "cciss: cmd %p timedout\n", cmd);
3217                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3218                         cmd->err_info->CommandStatus, DRIVER_OK,
3219                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3220                 break;
3221         default:
3222                 printk(KERN_WARNING "cciss: cmd %p returned "
3223                        "unknown status %x\n", cmd,
3224                        cmd->err_info->CommandStatus);
3225                 rq->errors = make_status_bytes(SAM_STAT_GOOD,
3226                         cmd->err_info->CommandStatus, DRIVER_OK,
3227                         blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
3228         }
3229
3230 after_error_processing:
3231
3232         /* We need to return this command */
3233         if (retry_cmd) {
3234                 resend_cciss_cmd(h, cmd);
3235                 return;
3236         }
3237         cmd->rq->completion_data = cmd;
3238         blk_complete_request(cmd->rq);
3239 }
3240
3241 /*
3242  * Get a request and submit it to the controller.
3243  */
3244 static void do_cciss_request(struct request_queue *q)
3245 {
3246         ctlr_info_t *h = q->queuedata;
3247         CommandList_struct *c;
3248         sector_t start_blk;
3249         int seg;
3250         struct request *creq;
3251         u64bit temp64;
3252         struct scatterlist tmp_sg[MAXSGENTRIES];
3253         drive_info_struct *drv;
3254         int i, dir;
3255
3256         /* We call start_io here in case there is a command waiting on the
3257          * queue that has not been sent.
3258          */
3259         if (blk_queue_plugged(q))
3260                 goto startio;
3261
3262       queue:
3263         creq = blk_peek_request(q);
3264         if (!creq)
3265                 goto startio;
3266
3267         BUG_ON(creq->nr_phys_segments > MAXSGENTRIES);
3268
3269         if ((c = cmd_alloc(h, 1)) == NULL)
3270                 goto full;
3271
3272         blk_start_request(creq);
3273
3274         spin_unlock_irq(q->queue_lock);
3275
3276         c->cmd_type = CMD_RWREQ;
3277         c->rq = creq;
3278
3279         /* fill in the request */
3280         drv = creq->rq_disk->private_data;
3281         c->Header.ReplyQueue = 0;       // unused in simple mode
3282         /* got command from pool, so use the command block index instead */
3283         /* for direct lookups. */
3284         /* The first 2 bits are reserved for controller error reporting. */
3285         c->Header.Tag.lower = (c->cmdindex << 3);
3286         c->Header.Tag.lower |= 0x04;    /* flag for direct lookup. */
3287         memcpy(&c->Header.LUN, drv->LunID, sizeof(drv->LunID));
3288         c->Request.CDBLen = 10; // 12 byte commands not in FW yet;
3289         c->Request.Type.Type = TYPE_CMD;        // It is a command.
3290         c->Request.Type.Attribute = ATTR_SIMPLE;
3291         c->Request.Type.Direction =
3292             (rq_data_dir(creq) == READ) ? XFER_READ : XFER_WRITE;
3293         c->Request.Timeout = 0; // Don't time out
3294         c->Request.CDB[0] =
3295             (rq_data_dir(creq) == READ) ? h->cciss_read : h->cciss_write;
3296         start_blk = blk_rq_pos(creq);
3297 #ifdef CCISS_DEBUG
3298         printk(KERN_DEBUG "ciss: sector =%d nr_sectors=%d\n",
3299                (int)blk_rq_pos(creq), (int)blk_rq_sectors(creq));
3300 #endif                          /* CCISS_DEBUG */
3301
3302         sg_init_table(tmp_sg, MAXSGENTRIES);
3303         seg = blk_rq_map_sg(q, creq, tmp_sg);
3304
3305         /* get the DMA records for the setup */
3306         if (c->Request.Type.Direction == XFER_READ)
3307                 dir = PCI_DMA_FROMDEVICE;
3308         else
3309                 dir = PCI_DMA_TODEVICE;
3310
3311         for (i = 0; i < seg; i++) {
3312                 c->SG[i].Len = tmp_sg[i].length;
3313                 temp64.val = (__u64) pci_map_page(h->pdev, sg_page(&tmp_sg[i]),
3314                                                   tmp_sg[i].offset,
3315                                                   tmp_sg[i].length, dir);
3316                 c->SG[i].Addr.lower = temp64.val32.lower;
3317                 c->SG[i].Addr.upper = temp64.val32.upper;
3318                 c->SG[i].Ext = 0;       // we are not chaining
3319         }
3320         /* track how many SG entries we are using */
3321         if (seg > h->maxSG)
3322                 h->maxSG = seg;
3323
3324 #ifdef CCISS_DEBUG
3325         printk(KERN_DEBUG "cciss: Submitting %u sectors in %d segments\n",
3326                blk_rq_sectors(creq), seg);
3327 #endif                          /* CCISS_DEBUG */
3328
3329         c->Header.SGList = c->Header.SGTotal = seg;
3330         if (likely(blk_fs_request(creq))) {
3331                 if(h->cciss_read == CCISS_READ_10) {
3332                         c->Request.CDB[1] = 0;
3333                         c->Request.CDB[2] = (start_blk >> 24) & 0xff;   //MSB
3334                         c->Request.CDB[3] = (start_blk >> 16) & 0xff;
3335                         c->Request.CDB[4] = (start_blk >> 8) & 0xff;
3336                         c->Request.CDB[5] = start_blk & 0xff;
3337                         c->Request.CDB[6] = 0;  // (sect >> 24) & 0xff; MSB
3338                         c->Request.CDB[7] = (blk_rq_sectors(creq) >> 8) & 0xff;
3339                         c->Request.CDB[8] = blk_rq_sectors(creq) & 0xff;
3340                         c->Request.CDB[9] = c->Request.CDB[11] = c->Request.CDB[12] = 0;
3341                 } else {
3342                         u32 upper32 = upper_32_bits(start_blk);
3343
3344                         c->Request.CDBLen = 16;
3345                         c->Request.CDB[1]= 0;
3346                         c->Request.CDB[2]= (upper32 >> 24) & 0xff;      //MSB
3347                         c->Request.CDB[3]= (upper32 >> 16) & 0xff;
3348                         c->Request.CDB[4]= (upper32 >>  8) & 0xff;
3349                         c->Request.CDB[5]= upper32 & 0xff;
3350                         c->Request.CDB[6]= (start_blk >> 24) & 0xff;
3351                         c->Request.CDB[7]= (start_blk >> 16) & 0xff;
3352                         c->Request.CDB[8]= (start_blk >>  8) & 0xff;
3353                         c->Request.CDB[9]= start_blk & 0xff;
3354                         c->Request.CDB[10]= (blk_rq_sectors(creq) >> 24) & 0xff;
3355                         c->Request.CDB[11]= (blk_rq_sectors(creq) >> 16) & 0xff;
3356                         c->Request.CDB[12]= (blk_rq_sectors(creq) >>  8) & 0xff;
3357                         c->Request.CDB[13]= blk_rq_sectors(creq) & 0xff;
3358                         c->Request.CDB[14] = c->Request.CDB[15] = 0;
3359                 }
3360         } else if (blk_pc_request(creq)) {
3361                 c->Request.CDBLen = creq->cmd_len;
3362                 memcpy(c->Request.CDB, creq->cmd, BLK_MAX_CDB);
3363         } else {
3364                 printk(KERN_WARNING "cciss%d: bad request type %d\n", h->ctlr, creq->cmd_type);
3365                 BUG();
3366         }
3367
3368         spin_lock_irq(q->queue_lock);
3369
3370         addQ(&h->reqQ, c);
3371         h->Qdepth++;
3372         if (h->Qdepth > h->maxQsinceinit)
3373                 h->maxQsinceinit = h->Qdepth;
3374
3375         goto queue;
3376 full:
3377         blk_stop_queue(q);
3378 startio:
3379         /* We will already have the driver lock here so not need
3380          * to lock it.
3381          */
3382         start_io(h);
3383 }
3384
3385 static inline unsigned long get_next_completion(ctlr_info_t *h)
3386 {
3387         return h->access.command_completed(h);
3388 }
3389
3390 static inline int interrupt_pending(ctlr_info_t *h)
3391 {
3392         return h->access.intr_pending(h);
3393 }
3394
3395 static inline long interrupt_not_for_us(ctlr_info_t *h)
3396 {
3397         return (((h->access.intr_pending(h) == 0) ||
3398                  (h->interrupts_enabled == 0)));
3399 }
3400
3401 static irqreturn_t do_cciss_intr(int irq, void *dev_id)
3402 {
3403         ctlr_info_t *h = dev_id;
3404         CommandList_struct *c;
3405         unsigned long flags;
3406         __u32 a, a1, a2;
3407
3408         if (interrupt_not_for_us(h))
3409                 return IRQ_NONE;
3410         /*
3411          * If there are completed commands in the completion queue,
3412          * we had better do something about it.
3413          */
3414         spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
3415         while (interrupt_pending(h)) {
3416                 while ((a = get_next_completion(h)) != FIFO_EMPTY) {
3417                         a1 = a;
3418                         if ((a & 0x04)) {
3419                                 a2 = (a >> 3);
3420                                 if (a2 >= h->nr_cmds) {
3421                                         printk(KERN_WARNING
3422                                                "cciss: controller cciss%d failed, stopping.\n",
3423                                                h->ctlr);
3424                                         fail_all_cmds(h->ctlr);
3425                                         return IRQ_HANDLED;
3426                                 }
3427
3428                                 c = h->cmd_pool + a2;
3429                                 a = c->busaddr;
3430
3431                         } else {
3432                                 struct hlist_node *tmp;
3433
3434                                 a &= ~3;
3435                                 c = NULL;
3436                                 hlist_for_each_entry(c, tmp, &h->cmpQ, list) {
3437                                         if (c->busaddr == a)
3438                                                 break;
3439                                 }
3440                         }
3441                         /*
3442                          * If we've found the command, take it off the
3443                          * completion Q and free it
3444                          */
3445                         if (c && c->busaddr == a) {
3446                                 removeQ(c);
3447                                 if (c->cmd_type == CMD_RWREQ) {
3448                                         complete_command(h, c, 0);
3449                                 } else if (c->cmd_type == CMD_IOCTL_PEND) {
3450                                         complete(c->waiting);
3451                                 }
3452 #                               ifdef CONFIG_CISS_SCSI_TAPE
3453                                 else if (c->cmd_type == CMD_SCSI)
3454                                         complete_scsi_command(c, 0, a1);
3455 #                               endif
3456                                 continue;
3457                         }
3458                 }
3459         }
3460
3461         spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
3462         return IRQ_HANDLED;
3463 }
3464
3465 /**
3466  * add_to_scan_list() - add controller to rescan queue
3467  * @h:                Pointer to the controller.
3468  *
3469  * Adds the controller to the rescan queue if not already on the queue.
3470  *
3471  * returns 1 if added to the queue, 0 if skipped (could be on the
3472  * queue already, or the controller could be initializing or shutting
3473  * down).
3474  **/
3475 static int add_to_scan_list(struct ctlr_info *h)
3476 {
3477         struct ctlr_info *test_h;
3478         int found = 0;
3479         int ret = 0;
3480
3481         if (h->busy_initializing)
3482                 return 0;
3483
3484         if (!mutex_trylock(&h->busy_shutting_down))
3485                 return 0;
3486
3487         mutex_lock(&scan_mutex);
3488         list_for_each_entry(test_h, &scan_q, scan_list) {
3489                 if (test_h == h) {
3490                         found = 1;
3491                         break;
3492                 }
3493         }
3494         if (!found && !h->busy_scanning) {
3495                 INIT_COMPLETION(h->scan_wait);
3496                 list_add_tail(&h->scan_list, &scan_q);
3497                 ret = 1;
3498         }
3499         mutex_unlock(&scan_mutex);
3500         mutex_unlock(&h->busy_shutting_down);
3501
3502         return ret;
3503 }
3504
3505 /**
3506  * remove_from_scan_list() - remove controller from rescan queue
3507  * @h:                     Pointer to the controller.
3508  *
3509  * Removes the controller from the rescan queue if present. Blocks if
3510  * the controller is currently conducting a rescan.
3511  **/
3512 static void remove_from_scan_list(struct ctlr_info *h)
3513 {
3514         struct ctlr_info *test_h, *tmp_h;
3515         int scanning = 0;
3516
3517         mutex_lock(&scan_mutex);
3518         list_for_each_entry_safe(test_h, tmp_h, &scan_q, scan_list) {
3519                 if (test_h == h) {
3520                         list_del(&h->scan_list);
3521                         complete_all(&h->scan_wait);
3522                         mutex_unlock(&scan_mutex);
3523                         return;
3524                 }
3525         }
3526         if (&h->busy_scanning)
3527                 scanning = 0;
3528         mutex_unlock(&scan_mutex);
3529
3530         if (scanning)
3531                 wait_for_completion(&h->scan_wait);
3532 }
3533
3534 /**
3535  * scan_thread() - kernel thread used to rescan controllers
3536  * @data:        Ignored.
3537  *
3538  * A kernel thread used scan for drive topology changes on
3539  * controllers. The thread processes only one controller at a time
3540  * using a queue.  Controllers are added to the queue using
3541  * add_to_scan_list() and removed from the queue either after done
3542  * processing or using remove_from_scan_list().
3543  *
3544  * returns 0.
3545  **/
3546 static int scan_thread(void *data)
3547 {
3548         struct ctlr_info *h;
3549
3550         while (1) {
3551                 set_current_state(TASK_INTERRUPTIBLE);
3552                 schedule();
3553                 if (kthread_should_stop())
3554                         break;
3555
3556                 while (1) {
3557                         mutex_lock(&scan_mutex);
3558                         if (list_empty(&scan_q)) {
3559                                 mutex_unlock(&scan_mutex);
3560                                 break;
3561                         }
3562
3563                         h = list_entry(scan_q.next,
3564                                        struct ctlr_info,
3565                                        scan_list);
3566                         list_del(&h->scan_list);
3567                         h->busy_scanning = 1;
3568                         mutex_unlock(&scan_mutex);
3569
3570                         if (h) {
3571                                 rebuild_lun_table(h, 0, 0);
3572                                 complete_all(&h->scan_wait);
3573                                 mutex_lock(&scan_mutex);
3574                                 h->busy_scanning = 0;
3575                                 mutex_unlock(&scan_mutex);
3576                         }
3577                 }
3578         }
3579
3580         return 0;
3581 }
3582
3583 static int check_for_unit_attention(ctlr_info_t *h, CommandList_struct *c)
3584 {
3585         if (c->err_info->SenseInfo[2] != UNIT_ATTENTION)
3586                 return 0;
3587
3588         switch (c->err_info->SenseInfo[12]) {
3589         case STATE_CHANGED:
3590                 printk(KERN_WARNING "cciss%d: a state change "
3591                         "detected, command retried\n", h->ctlr);
3592                 return 1;
3593         break;
3594         case LUN_FAILED:
3595                 printk(KERN_WARNING "cciss%d: LUN failure "
3596                         "detected, action required\n", h->ctlr);
3597                 return 1;
3598         break;
3599         case REPORT_LUNS_CHANGED:
3600                 printk(KERN_WARNING "cciss%d: report LUN data "
3601                         "changed\n", h->ctlr);
3602                 add_to_scan_list(h);
3603                 wake_up_process(cciss_scan_thread);
3604                 return 1;
3605         break;
3606         case POWER_OR_RESET:
3607                 printk(KERN_WARNING "cciss%d: a power on "
3608                         "or device reset detected\n", h->ctlr);
3609                 return 1;
3610         break;
3611         case UNIT_ATTENTION_CLEARED:
3612                 printk(KERN_WARNING "cciss%d: unit attention "
3613                     "cleared by another initiator\n", h->ctlr);
3614                 return 1;
3615         break;
3616         default:
3617                 printk(KERN_WARNING "cciss%d: unknown "
3618                         "unit attention detected\n", h->ctlr);
3619                                 return 1;
3620         }
3621 }
3622
3623 /*
3624  *  We cannot read the structure directly, for portability we must use
3625  *   the io functions.
3626  *   This is for debug only.
3627  */
3628 #ifdef CCISS_DEBUG
3629 static void print_cfg_table(CfgTable_struct *tb)
3630 {
3631         int i;
3632         char temp_name[17];
3633
3634         printk("Controller Configuration information\n");
3635         printk("------------------------------------\n");
3636         for (i = 0; i < 4; i++)
3637                 temp_name[i] = readb(&(tb->Signature[i]));
3638         temp_name[4] = '\0';
3639         printk("   Signature = %s\n", temp_name);
3640         printk("   Spec Number = %d\n", readl(&(tb->SpecValence)));
3641         printk("   Transport methods supported = 0x%x\n",
3642                readl(&(tb->TransportSupport)));
3643         printk("   Transport methods active = 0x%x\n",
3644                readl(&(tb->TransportActive)));
3645         printk("   Requested transport Method = 0x%x\n",
3646                readl(&(tb->HostWrite.TransportRequest)));
3647         printk("   Coalesce Interrupt Delay = 0x%x\n",
3648                readl(&(tb->HostWrite.CoalIntDelay)));
3649         printk("   Coalesce Interrupt Count = 0x%x\n",
3650                readl(&(tb->HostWrite.CoalIntCount)));
3651         printk("   Max outstanding commands = 0x%d\n",
3652                readl(&(tb->CmdsOutMax)));
3653         printk("   Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
3654         for (i = 0; i < 16; i++)
3655                 temp_name[i] = readb(&(tb->ServerName[i]));
3656         temp_name[16] = '\0';
3657         printk("   Server Name = %s\n", temp_name);
3658         printk("   Heartbeat Counter = 0x%x\n\n\n", readl(&(tb->HeartBeat)));
3659 }
3660 #endif                          /* CCISS_DEBUG */
3661
3662 static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
3663 {
3664         int i, offset, mem_type, bar_type;
3665         if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
3666                 return 0;
3667         offset = 0;
3668         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3669                 bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
3670                 if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
3671                         offset += 4;
3672                 else {
3673                         mem_type = pci_resource_flags(pdev, i) &
3674                             PCI_BASE_ADDRESS_MEM_TYPE_MASK;
3675                         switch (mem_type) {
3676                         case PCI_BASE_ADDRESS_MEM_TYPE_32:
3677                         case PCI_BASE_ADDRESS_MEM_TYPE_1M:
3678                                 offset += 4;    /* 32 bit */
3679                                 break;
3680                         case PCI_BASE_ADDRESS_MEM_TYPE_64:
3681                                 offset += 8;
3682                                 break;
3683                         default:        /* reserved in PCI 2.2 */
3684                                 printk(KERN_WARNING
3685                                        "Base address is invalid\n");
3686                                 return -1;
3687                                 break;
3688                         }
3689                 }
3690                 if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
3691                         return i + 1;
3692         }
3693         return -1;
3694 }
3695
3696 /* If MSI/MSI-X is supported by the kernel we will try to enable it on
3697  * controllers that are capable. If not, we use IO-APIC mode.
3698  */
3699
3700 static void __devinit cciss_interrupt_mode(ctlr_info_t *c,
3701                                            struct pci_dev *pdev, __u32 board_id)
3702 {
3703 #ifdef CONFIG_PCI_MSI
3704         int err;
3705         struct msix_entry cciss_msix_entries[4] = { {0, 0}, {0, 1},
3706         {0, 2}, {0, 3}
3707         };
3708
3709         /* Some boards advertise MSI but don't really support it */
3710         if ((board_id == 0x40700E11) ||
3711             (board_id == 0x40800E11) ||
3712             (board_id == 0x40820E11) || (board_id == 0x40830E11))
3713                 goto default_int_mode;
3714
3715         if (pci_find_capability(pdev, PCI_CAP_ID_MSIX)) {
3716                 err = pci_enable_msix(pdev, cciss_msix_entries, 4);
3717                 if (!err) {
3718                         c->intr[0] = cciss_msix_entries[0].vector;
3719                         c->intr[1] = cciss_msix_entries[1].vector;
3720                         c->intr[2] = cciss_msix_entries[2].vector;
3721                         c->intr[3] = cciss_msix_entries[3].vector;
3722                         c->msix_vector = 1;
3723                         return;
3724                 }
3725                 if (err > 0) {
3726                         printk(KERN_WARNING "cciss: only %d MSI-X vectors "
3727                                "available\n", err);
3728                         goto default_int_mode;
3729                 } else {
3730                         printk(KERN_WARNING "cciss: MSI-X init failed %d\n",
3731                                err);
3732                         goto default_int_mode;
3733                 }
3734         }
3735         if (pci_find_capability(pdev, PCI_CAP_ID_MSI)) {
3736                 if (!pci_enable_msi(pdev)) {
3737                         c->msi_vector = 1;
3738                 } else {
3739                         printk(KERN_WARNING "cciss: MSI init failed\n");
3740                 }
3741         }
3742 default_int_mode:
3743 #endif                          /* CONFIG_PCI_MSI */
3744         /* if we get here we're going to use the default interrupt mode */
3745         c->intr[SIMPLE_MODE_INT] = pdev->irq;
3746         return;
3747 }
3748
3749 static int __devinit cciss_pci_init(ctlr_info_t *c, struct pci_dev *pdev)
3750 {
3751         ushort subsystem_vendor_id, subsystem_device_id, command;
3752         __u32 board_id, scratchpad = 0;
3753         __u64 cfg_offset;
3754         __u32 cfg_base_addr;
3755         __u64 cfg_base_addr_index;
3756         int i, err;
3757
3758         /* check to see if controller has been disabled */
3759         /* BEFORE trying to enable it */
3760         (void)pci_read_config_word(pdev, PCI_COMMAND, &command);
3761         if (!(command & 0x02)) {
3762                 printk(KERN_WARNING
3763                        "cciss: controller appears to be disabled\n");
3764                 return -ENODEV;
3765         }
3766
3767         err = pci_enable_device(pdev);
3768         if (err) {
3769                 printk(KERN_ERR "cciss: Unable to Enable PCI device\n");
3770                 return err;
3771         }
3772
3773         err = pci_request_regions(pdev, "cciss");
3774         if (err) {
3775                 printk(KERN_ERR "cciss: Cannot obtain PCI resources, "
3776                        "aborting\n");
3777                 return err;
3778         }
3779
3780         subsystem_vendor_id = pdev->subsystem_vendor;
3781         subsystem_device_id = pdev->subsystem_device;
3782         board_id = (((__u32) (subsystem_device_id << 16) & 0xffff0000) |
3783                     subsystem_vendor_id);
3784
3785 #ifdef CCISS_DEBUG
3786         printk("command = %x\n", command);
3787         printk("irq = %x\n", pdev->irq);
3788         printk("board_id = %x\n", board_id);
3789 #endif                          /* CCISS_DEBUG */
3790
3791 /* If the kernel supports MSI/MSI-X we will try to enable that functionality,
3792  * else we use the IO-APIC interrupt assigned to us by system ROM.
3793  */
3794         cciss_interrupt_mode(c, pdev, board_id);
3795
3796         /* find the memory BAR */
3797         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3798                 if (pci_resource_flags(pdev, i) & IORESOURCE_MEM)
3799                         break;
3800         }
3801         if (i == DEVICE_COUNT_RESOURCE) {
3802                 printk(KERN_WARNING "cciss: No memory BAR found\n");
3803                 err = -ENODEV;
3804                 goto err_out_free_res;
3805         }
3806
3807         c->paddr = pci_resource_start(pdev, i); /* addressing mode bits
3808                                                  * already removed
3809                                                  */
3810
3811 #ifdef CCISS_DEBUG
3812         printk("address 0 = %lx\n", c->paddr);
3813 #endif                          /* CCISS_DEBUG */
3814         c->vaddr = remap_pci_mem(c->paddr, 0x250);
3815
3816         /* Wait for the board to become ready.  (PCI hotplug needs this.)
3817          * We poll for up to 120 secs, once per 100ms. */
3818         for (i = 0; i < 1200; i++) {
3819                 scratchpad = readl(c->vaddr + SA5_SCRATCHPAD_OFFSET);
3820                 if (scratchpad == CCISS_FIRMWARE_READY)
3821                         break;
3822                 set_current_state(TASK_INTERRUPTIBLE);
3823                 schedule_timeout(msecs_to_jiffies(100));        /* wait 100ms */
3824         }
3825         if (scratchpad != CCISS_FIRMWARE_READY) {
3826                 printk(KERN_WARNING "cciss: Board not ready.  Timed out.\n");
3827                 err = -ENODEV;
3828                 goto err_out_free_res;
3829         }
3830
3831         /* get the address index number */
3832         cfg_base_addr = readl(c->vaddr + SA5_CTCFG_OFFSET);
3833         cfg_base_addr &= (__u32) 0x0000ffff;
3834 #ifdef CCISS_DEBUG
3835         printk("cfg base address = %x\n", cfg_base_addr);
3836 #endif                          /* CCISS_DEBUG */
3837         cfg_base_addr_index = find_PCI_BAR_index(pdev, cfg_base_addr);
3838 #ifdef CCISS_DEBUG
3839         printk("cfg base address index = %llx\n",
3840                 (unsigned long long)cfg_base_addr_index);
3841 #endif                          /* CCISS_DEBUG */
3842         if (cfg_base_addr_index == -1) {
3843                 printk(KERN_WARNING "cciss: Cannot find cfg_base_addr_index\n");
3844                 err = -ENODEV;
3845                 goto err_out_free_res;
3846         }
3847
3848         cfg_offset = readl(c->vaddr + SA5_CTMEM_OFFSET);
3849 #ifdef CCISS_DEBUG
3850         printk("cfg offset = %llx\n", (unsigned long long)cfg_offset);
3851 #endif                          /* CCISS_DEBUG */
3852         c->cfgtable = remap_pci_mem(pci_resource_start(pdev,
3853                                                        cfg_base_addr_index) +
3854                                     cfg_offset, sizeof(CfgTable_struct));
3855         c->board_id = board_id;
3856
3857 #ifdef CCISS_DEBUG
3858         print_cfg_table(c->cfgtable);
3859 #endif                          /* CCISS_DEBUG */
3860
3861         /* Some controllers support Zero Memory Raid (ZMR).
3862          * When configured in ZMR mode the number of supported
3863          * commands drops to 64. So instead of just setting an
3864          * arbitrary value we make the driver a little smarter.
3865          * We read the config table to tell us how many commands
3866          * are supported on the controller then subtract 4 to
3867          * leave a little room for ioctl calls.
3868          */
3869         c->max_commands = readl(&(c->cfgtable->CmdsOutMax));
3870         for (i = 0; i < ARRAY_SIZE(products); i++) {
3871                 if (board_id == products[i].board_id) {
3872                         c->product_name = products[i].product_name;
3873                         c->access = *(products[i].access);
3874                         c->nr_cmds = c->max_commands - 4;
3875                         break;
3876                 }
3877         }
3878         if ((readb(&c->cfgtable->Signature[0]) != 'C') ||
3879             (readb(&c->cfgtable->Signature[1]) != 'I') ||
3880             (readb(&c->cfgtable->Signature[2]) != 'S') ||
3881             (readb(&c->cfgtable->Signature[3]) != 'S')) {
3882                 printk("Does not appear to be a valid CISS config table\n");
3883                 err = -ENODEV;
3884                 goto err_out_free_res;
3885         }
3886         /* We didn't find the controller in our list. We know the
3887          * signature is valid. If it's an HP device let's try to
3888          * bind to the device and fire it up. Otherwise we bail.
3889          */
3890         if (i == ARRAY_SIZE(products)) {
3891                 if (subsystem_vendor_id == PCI_VENDOR_ID_HP) {
3892                         c->product_name = products[i-1].product_name;
3893                         c->access = *(products[i-1].access);
3894                         c->nr_cmds = c->max_commands - 4;
3895                         printk(KERN_WARNING "cciss: This is an unknown "
3896                                 "Smart Array controller.\n"
3897                                 "cciss: Please update to the latest driver "
3898                                 "available from www.hp.com.\n");
3899                 } else {
3900                         printk(KERN_WARNING "cciss: Sorry, I don't know how"
3901                                 " to access the Smart Array controller %08lx\n"
3902                                         , (unsigned long)board_id);
3903                         err = -ENODEV;
3904                         goto err_out_free_res;
3905                 }
3906         }
3907 #ifdef CONFIG_X86
3908         {
3909                 /* Need to enable prefetch in the SCSI core for 6400 in x86 */
3910                 __u32 prefetch;
3911                 prefetch = readl(&(c->cfgtable->SCSI_Prefetch));
3912                 prefetch |= 0x100;
3913                 writel(prefetch, &(c->cfgtable->SCSI_Prefetch));
3914         }
3915 #endif
3916
3917         /* Disabling DMA prefetch and refetch for the P600.
3918          * An ASIC bug may result in accesses to invalid memory addresses.
3919          * We've disabled prefetch for some time now. Testing with XEN
3920          * kernels revealed a bug in the refetch if dom0 resides on a P600.
3921          */
3922         if(board_id == 0x3225103C) {
3923                 __u32 dma_prefetch;
3924                 __u32 dma_refetch;
3925                 dma_prefetch = readl(c->vaddr + I2O_DMA1_CFG);
3926                 dma_prefetch |= 0x8000;
3927                 writel(dma_prefetch, c->vaddr + I2O_DMA1_CFG);
3928                 pci_read_config_dword(pdev, PCI_COMMAND_PARITY, &dma_refetch);
3929                 dma_refetch |= 0x1;
3930                 pci_write_config_dword(pdev, PCI_COMMAND_PARITY, dma_refetch);
3931         }
3932
3933 #ifdef CCISS_DEBUG
3934         printk("Trying to put board into Simple mode\n");
3935 #endif                          /* CCISS_DEBUG */
3936         c->max_commands = readl(&(c->cfgtable->CmdsOutMax));
3937         /* Update the field, and then ring the doorbell */
3938         writel(CFGTBL_Trans_Simple, &(c->cfgtable->HostWrite.TransportRequest));
3939         writel(CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
3940
3941         /* under certain very rare conditions, this can take awhile.
3942          * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
3943          * as we enter this code.) */
3944         for (i = 0; i < MAX_CONFIG_WAIT; i++) {
3945                 if (!(readl(c->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
3946                         break;
3947                 /* delay and try again */
3948                 set_current_state(TASK_INTERRUPTIBLE);
3949                 schedule_timeout(msecs_to_jiffies(1));
3950         }
3951
3952 #ifdef CCISS_DEBUG
3953         printk(KERN_DEBUG "I counter got to %d %x\n", i,
3954                readl(c->vaddr + SA5_DOORBELL));
3955 #endif                          /* CCISS_DEBUG */
3956 #ifdef CCISS_DEBUG
3957         print_cfg_table(c->cfgtable);
3958 #endif                          /* CCISS_DEBUG */
3959
3960         if (!(readl(&(c->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
3961                 printk(KERN_WARNING "cciss: unable to get board into"
3962                        " simple mode\n");
3963                 err = -ENODEV;
3964                 goto err_out_free_res;
3965         }
3966         return 0;
3967
3968 err_out_free_res:
3969         /*
3970          * Deliberately omit pci_disable_device(): it does something nasty to
3971          * Smart Array controllers that pci_enable_device does not undo
3972          */
3973         pci_release_regions(pdev);
3974         return err;
3975 }
3976
3977 /* Function to find the first free pointer into our hba[] array
3978  * Returns -1 if no free entries are left.
3979  */
3980 static int alloc_cciss_hba(void)
3981 {
3982         int i;
3983
3984         for (i = 0; i < MAX_CTLR; i++) {
3985                 if (!hba[i]) {
3986                         ctlr_info_t *p;
3987
3988                         p = kzalloc(sizeof(ctlr_info_t), GFP_KERNEL);
3989                         if (!p)
3990                                 goto Enomem;
3991                         hba[i] = p;
3992                         return i;
3993                 }
3994         }
3995         printk(KERN_WARNING "cciss: This driver supports a maximum"
3996                " of %d controllers.\n", MAX_CTLR);
3997         return -1;
3998 Enomem:
3999         printk(KERN_ERR "cciss: out of memory.\n");
4000         return -1;
4001 }
4002
4003 static void free_hba(int n)
4004 {
4005         ctlr_info_t *h = hba[n];
4006         int i;
4007
4008         hba[n] = NULL;
4009         for (i = 0; i < h->highest_lun + 1; i++)
4010                 if (h->gendisk[i] != NULL)
4011                         put_disk(h->gendisk[i]);
4012         kfree(h);
4013 }
4014
4015 /* Send a message CDB to the firmware. */
4016 static __devinit int cciss_message(struct pci_dev *pdev, unsigned char opcode, unsigned char type)
4017 {
4018         typedef struct {
4019                 CommandListHeader_struct CommandHeader;
4020                 RequestBlock_struct Request;
4021                 ErrDescriptor_struct ErrorDescriptor;
4022         } Command;
4023         static const size_t cmd_sz = sizeof(Command) + sizeof(ErrorInfo_struct);
4024         Command *cmd;
4025         dma_addr_t paddr64;
4026         uint32_t paddr32, tag;
4027         void __iomem *vaddr;
4028         int i, err;
4029
4030         vaddr = ioremap_nocache(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0));
4031         if (vaddr == NULL)
4032                 return -ENOMEM;
4033
4034         /* The Inbound Post Queue only accepts 32-bit physical addresses for the
4035            CCISS commands, so they must be allocated from the lower 4GiB of
4036            memory. */
4037         err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
4038         if (err) {
4039                 iounmap(vaddr);
4040                 return -ENOMEM;
4041         }
4042
4043         cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
4044         if (cmd == NULL) {
4045                 iounmap(vaddr);
4046                 return -ENOMEM;
4047         }
4048
4049         /* This must fit, because of the 32-bit consistent DMA mask.  Also,
4050            although there's no guarantee, we assume that the address is at
4051            least 4-byte aligned (most likely, it's page-aligned). */
4052         paddr32 = paddr64;
4053
4054         cmd->CommandHeader.ReplyQueue = 0;
4055         cmd->CommandHeader.SGList = 0;
4056         cmd->CommandHeader.SGTotal = 0;
4057         cmd->CommandHeader.Tag.lower = paddr32;
4058         cmd->CommandHeader.Tag.upper = 0;
4059         memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
4060
4061         cmd->Request.CDBLen = 16;
4062         cmd->Request.Type.Type = TYPE_MSG;
4063         cmd->Request.Type.Attribute = ATTR_HEADOFQUEUE;
4064         cmd->Request.Type.Direction = XFER_NONE;
4065         cmd->Request.Timeout = 0; /* Don't time out */
4066         cmd->Request.CDB[0] = opcode;
4067         cmd->Request.CDB[1] = type;
4068         memset(&cmd->Request.CDB[2], 0, 14); /* the rest of the CDB is reserved */
4069
4070         cmd->ErrorDescriptor.Addr.lower = paddr32 + sizeof(Command);
4071         cmd->ErrorDescriptor.Addr.upper = 0;
4072         cmd->ErrorDescriptor.Len = sizeof(ErrorInfo_struct);
4073
4074         writel(paddr32, vaddr + SA5_REQUEST_PORT_OFFSET);
4075
4076         for (i = 0; i < 10; i++) {
4077                 tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
4078                 if ((tag & ~3) == paddr32)
4079                         break;
4080                 schedule_timeout_uninterruptible(HZ);
4081         }
4082
4083         iounmap(vaddr);
4084
4085         /* we leak the DMA buffer here ... no choice since the controller could
4086            still complete the command. */
4087         if (i == 10) {
4088                 printk(KERN_ERR "cciss: controller message %02x:%02x timed out\n",
4089                         opcode, type);
4090                 return -ETIMEDOUT;
4091         }
4092
4093         pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
4094
4095         if (tag & 2) {
4096                 printk(KERN_ERR "cciss: controller message %02x:%02x failed\n",
4097                         opcode, type);
4098                 return -EIO;
4099         }
4100
4101         printk(KERN_INFO "cciss: controller message %02x:%02x succeeded\n",
4102                 opcode, type);
4103         return 0;
4104 }
4105
4106 #define cciss_soft_reset_controller(p) cciss_message(p, 1, 0)
4107 #define cciss_noop(p) cciss_message(p, 3, 0)
4108
4109 static __devinit int cciss_reset_msi(struct pci_dev *pdev)
4110 {
4111 /* the #defines are stolen from drivers/pci/msi.h. */
4112 #define msi_control_reg(base)           (base + PCI_MSI_FLAGS)
4113 #define PCI_MSIX_FLAGS_ENABLE           (1 << 15)
4114
4115         int pos;
4116         u16 control = 0;
4117
4118         pos = pci_find_capability(pdev, PCI_CAP_ID_MSI);
4119         if (pos) {
4120                 pci_read_config_word(pdev, msi_control_reg(pos), &control);
4121                 if (control & PCI_MSI_FLAGS_ENABLE) {
4122                         printk(KERN_INFO "cciss: resetting MSI\n");
4123                         pci_write_config_word(pdev, msi_control_reg(pos), control & ~PCI_MSI_FLAGS_ENABLE);
4124                 }
4125         }
4126
4127         pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
4128         if (pos) {
4129                 pci_read_config_word(pdev, msi_control_reg(pos), &control);
4130                 if (control & PCI_MSIX_FLAGS_ENABLE) {
4131                         printk(KERN_INFO "cciss: resetting MSI-X\n");
4132                         pci_write_config_word(pdev, msi_control_reg(pos), control & ~PCI_MSIX_FLAGS_ENABLE);
4133                 }
4134         }
4135
4136         return 0;
4137 }
4138
4139 /* This does a hard reset of the controller using PCI power management
4140  * states. */
4141 static __devinit int cciss_hard_reset_controller(struct pci_dev *pdev)
4142 {
4143         u16 pmcsr, saved_config_space[32];
4144         int i, pos;
4145
4146         printk(KERN_INFO "cciss: using PCI PM to reset controller\n");
4147
4148         /* This is very nearly the same thing as
4149
4150            pci_save_state(pci_dev);
4151            pci_set_power_state(pci_dev, PCI_D3hot);
4152            pci_set_power_state(pci_dev, PCI_D0);
4153            pci_restore_state(pci_dev);
4154
4155            but we can't use these nice canned kernel routines on
4156            kexec, because they also check the MSI/MSI-X state in PCI
4157            configuration space and do the wrong thing when it is
4158            set/cleared.  Also, the pci_save/restore_state functions
4159            violate the ordering requirements for restoring the
4160            configuration space from the CCISS document (see the
4161            comment below).  So we roll our own .... */
4162
4163         for (i = 0; i < 32; i++)
4164                 pci_read_config_word(pdev, 2*i, &saved_config_space[i]);
4165
4166         pos = pci_find_capability(pdev, PCI_CAP_ID_PM);
4167         if (pos == 0) {
4168                 printk(KERN_ERR "cciss_reset_controller: PCI PM not supported\n");
4169                 return -ENODEV;
4170         }
4171
4172         /* Quoting from the Open CISS Specification: "The Power
4173          * Management Control/Status Register (CSR) controls the power
4174          * state of the device.  The normal operating state is D0,
4175          * CSR=00h.  The software off state is D3, CSR=03h.  To reset
4176          * the controller, place the interface device in D3 then to
4177          * D0, this causes a secondary PCI reset which will reset the
4178          * controller." */
4179
4180         /* enter the D3hot power management state */
4181         pci_read_config_word(pdev, pos + PCI_PM_CTRL, &pmcsr);
4182         pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
4183         pmcsr |= PCI_D3hot;
4184         pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
4185
4186         schedule_timeout_uninterruptible(HZ >> 1);
4187
4188         /* enter the D0 power management state */
4189         pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
4190         pmcsr |= PCI_D0;
4191         pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
4192
4193         schedule_timeout_uninterruptible(HZ >> 1);
4194
4195         /* Restore the PCI configuration space.  The Open CISS
4196          * Specification says, "Restore the PCI Configuration
4197          * Registers, offsets 00h through 60h. It is important to
4198          * restore the command register, 16-bits at offset 04h,
4199          * last. Do not restore the configuration status register,
4200          * 16-bits at offset 06h."  Note that the offset is 2*i. */
4201         for (i = 0; i < 32; i++) {
4202                 if (i == 2 || i == 3)
4203                         continue;
4204                 pci_write_config_word(pdev, 2*i, saved_config_space[i]);
4205         }
4206         wmb();
4207         pci_write_config_word(pdev, 4, saved_config_space[2]);
4208
4209         return 0;
4210 }
4211
4212 /*
4213  *  This is it.  Find all the controllers and register them.  I really hate
4214  *  stealing all these major device numbers.
4215  *  returns the number of block devices registered.
4216  */
4217 static int __devinit cciss_init_one(struct pci_dev *pdev,
4218                                     const struct pci_device_id *ent)
4219 {
4220         int i;
4221         int j = 0;
4222         int rc;
4223         int dac, return_code;
4224         InquiryData_struct *inq_buff;
4225
4226         if (reset_devices) {
4227                 /* Reset the controller with a PCI power-cycle */
4228                 if (cciss_hard_reset_controller(pdev) || cciss_reset_msi(pdev))
4229                         return -ENODEV;
4230
4231                 /* Now try to get the controller to respond to a no-op. Some
4232                    devices (notably the HP Smart Array 5i Controller) need
4233                    up to 30 seconds to respond. */
4234                 for (i=0; i<30; i++) {
4235                         if (cciss_noop(pdev) == 0)
4236                                 break;
4237
4238                         schedule_timeout_uninterruptible(HZ);
4239                 }
4240                 if (i == 30) {
4241                         printk(KERN_ERR "cciss: controller seems dead\n");
4242                         return -EBUSY;
4243                 }
4244         }
4245
4246         i = alloc_cciss_hba();
4247         if (i < 0)
4248                 return -1;
4249
4250         hba[i]->busy_initializing = 1;
4251         INIT_HLIST_HEAD(&hba[i]->cmpQ);
4252         INIT_HLIST_HEAD(&hba[i]->reqQ);
4253         mutex_init(&hba[i]->busy_shutting_down);
4254
4255         if (cciss_pci_init(hba[i], pdev) != 0)
4256                 goto clean0;
4257
4258         sprintf(hba[i]->devname, "cciss%d", i);
4259         hba[i]->ctlr = i;
4260         hba[i]->pdev = pdev;
4261
4262         init_completion(&hba[i]->scan_wait);
4263
4264         if (cciss_create_hba_sysfs_entry(hba[i]))
4265                 goto clean0;
4266
4267         /* configure PCI DMA stuff */
4268         if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64)))
4269                 dac = 1;
4270         else if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32)))
4271                 dac = 0;
4272         else {
4273                 printk(KERN_ERR "cciss: no suitable DMA available\n");
4274                 goto clean1;
4275         }
4276
4277         /*
4278          * register with the major number, or get a dynamic major number
4279          * by passing 0 as argument.  This is done for greater than
4280          * 8 controller support.
4281          */
4282         if (i < MAX_CTLR_ORIG)
4283                 hba[i]->major = COMPAQ_CISS_MAJOR + i;
4284         rc = register_blkdev(hba[i]->major, hba[i]->devname);
4285         if (rc == -EBUSY || rc == -EINVAL) {
4286                 printk(KERN_ERR
4287                        "cciss:  Unable to get major number %d for %s "
4288                        "on hba %d\n", hba[i]->major, hba[i]->devname, i);
4289                 goto clean1;
4290         } else {
4291                 if (i >= MAX_CTLR_ORIG)
4292                         hba[i]->major = rc;
4293         }
4294
4295         /* make sure the board interrupts are off */
4296         hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_OFF);
4297         if (request_irq(hba[i]->intr[SIMPLE_MODE_INT], do_cciss_intr,
4298                         IRQF_DISABLED | IRQF_SHARED, hba[i]->devname, hba[i])) {
4299                 printk(KERN_ERR "cciss: Unable to get irq %d for %s\n",
4300                        hba[i]->intr[SIMPLE_MODE_INT], hba[i]->devname);
4301                 goto clean2;
4302         }
4303
4304         printk(KERN_INFO "%s: <0x%x> at PCI %s IRQ %d%s using DAC\n",
4305                hba[i]->devname, pdev->device, pci_name(pdev),
4306                hba[i]->intr[SIMPLE_MODE_INT], dac ? "" : " not");
4307
4308         hba[i]->cmd_pool_bits =
4309             kmalloc(DIV_ROUND_UP(hba[i]->nr_cmds, BITS_PER_LONG)
4310                         * sizeof(unsigned long), GFP_KERNEL);
4311         hba[i]->cmd_pool = (CommandList_struct *)
4312             pci_alloc_consistent(hba[i]->pdev,
4313                     hba[i]->nr_cmds * sizeof(CommandList_struct),
4314                     &(hba[i]->cmd_pool_dhandle));
4315         hba[i]->errinfo_pool = (ErrorInfo_struct *)
4316             pci_alloc_consistent(hba[i]->pdev,
4317                     hba[i]->nr_cmds * sizeof(ErrorInfo_struct),
4318                     &(hba[i]->errinfo_pool_dhandle));
4319         if ((hba[i]->cmd_pool_bits == NULL)
4320             || (hba[i]->cmd_pool == NULL)
4321             || (hba[i]->errinfo_pool == NULL)) {
4322                 printk(KERN_ERR "cciss: out of memory");
4323                 goto clean4;
4324         }
4325         spin_lock_init(&hba[i]->lock);
4326
4327         /* Initialize the pdev driver private data.
4328            have it point to hba[i].  */
4329         pci_set_drvdata(pdev, hba[i]);
4330         /* command and error info recs zeroed out before
4331            they are used */
4332         memset(hba[i]->cmd_pool_bits, 0,
4333                DIV_ROUND_UP(hba[i]->nr_cmds, BITS_PER_LONG)
4334                         * sizeof(unsigned long));
4335
4336         hba[i]->num_luns = 0;
4337         hba[i]->highest_lun = -1;
4338         for (j = 0; j < CISS_MAX_LUN; j++) {
4339                 hba[i]->drv[j] = NULL;
4340                 hba[i]->gendisk[j] = NULL;
4341         }
4342
4343         cciss_scsi_setup(i);
4344
4345         /* Turn the interrupts on so we can service requests */
4346         hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_ON);
4347
4348         /* Get the firmware version */
4349         inq_buff = kzalloc(sizeof(InquiryData_struct), GFP_KERNEL);
4350         if (inq_buff == NULL) {
4351                 printk(KERN_ERR "cciss: out of memory\n");
4352                 goto clean4;
4353         }
4354
4355         return_code = sendcmd_withirq(CISS_INQUIRY, i, inq_buff,
4356                 sizeof(InquiryData_struct), 0, CTLR_LUNID, TYPE_CMD);
4357         if (return_code == IO_OK) {
4358                 hba[i]->firm_ver[0] = inq_buff->data_byte[32];
4359                 hba[i]->firm_ver[1] = inq_buff->data_byte[33];
4360                 hba[i]->firm_ver[2] = inq_buff->data_byte[34];
4361                 hba[i]->firm_ver[3] = inq_buff->data_byte[35];
4362         } else {         /* send command failed */
4363                 printk(KERN_WARNING "cciss: unable to determine firmware"
4364                         " version of controller\n");
4365         }
4366         kfree(inq_buff);
4367
4368         cciss_procinit(i);
4369
4370         hba[i]->cciss_max_sectors = 2048;
4371
4372         rebuild_lun_table(hba[i], 1, 0);
4373         hba[i]->busy_initializing = 0;
4374         return 1;
4375
4376 clean4:
4377         kfree(hba[i]->cmd_pool_bits);
4378         if (hba[i]->cmd_pool)
4379                 pci_free_consistent(hba[i]->pdev,
4380                                     hba[i]->nr_cmds * sizeof(CommandList_struct),
4381                                     hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
4382         if (hba[i]->errinfo_pool)
4383                 pci_free_consistent(hba[i]->pdev,
4384                                     hba[i]->nr_cmds * sizeof(ErrorInfo_struct),
4385                                     hba[i]->errinfo_pool,
4386                                     hba[i]->errinfo_pool_dhandle);
4387         free_irq(hba[i]->intr[SIMPLE_MODE_INT], hba[i]);
4388 clean2:
4389         unregister_blkdev(hba[i]->major, hba[i]->devname);
4390 clean1:
4391         cciss_destroy_hba_sysfs_entry(hba[i]);
4392 clean0:
4393         hba[i]->busy_initializing = 0;
4394
4395         /*
4396          * Deliberately omit pci_disable_device(): it does something nasty to
4397          * Smart Array controllers that pci_enable_device does not undo
4398          */
4399         pci_release_regions(pdev);
4400         pci_set_drvdata(pdev, NULL);
4401         free_hba(i);
4402         return -1;
4403 }
4404
4405 static void cciss_shutdown(struct pci_dev *pdev)
4406 {
4407         ctlr_info_t *tmp_ptr;
4408         int i;
4409         char flush_buf[4];
4410         int return_code;
4411
4412         tmp_ptr = pci_get_drvdata(pdev);
4413         if (tmp_ptr == NULL)
4414                 return;
4415         i = tmp_ptr->ctlr;
4416         if (hba[i] == NULL)
4417                 return;
4418
4419         /* Turn board interrupts off  and send the flush cache command */
4420         /* sendcmd will turn off interrupt, and send the flush...
4421          * To write all data in the battery backed cache to disks */
4422         memset(flush_buf, 0, 4);
4423         return_code = sendcmd(CCISS_CACHE_FLUSH, i, flush_buf, 4, 0,
4424                 CTLR_LUNID, TYPE_CMD);
4425         if (return_code == IO_OK) {
4426                 printk(KERN_INFO "Completed flushing cache on controller %d\n", i);
4427         } else {
4428                 printk(KERN_WARNING "Error flushing cache on controller %d\n", i);
4429         }
4430         free_irq(hba[i]->intr[2], hba[i]);
4431 }
4432
4433 static void __devexit cciss_remove_one(struct pci_dev *pdev)
4434 {
4435         ctlr_info_t *tmp_ptr;
4436         int i, j;
4437
4438         if (pci_get_drvdata(pdev) == NULL) {
4439                 printk(KERN_ERR "cciss: Unable to remove device \n");
4440                 return;
4441         }
4442
4443         tmp_ptr = pci_get_drvdata(pdev);
4444         i = tmp_ptr->ctlr;
4445         if (hba[i] == NULL) {
4446                 printk(KERN_ERR "cciss: device appears to "
4447                        "already be removed \n");
4448                 return;
4449         }
4450
4451         mutex_lock(&hba[i]->busy_shutting_down);
4452
4453         remove_from_scan_list(hba[i]);
4454         remove_proc_entry(hba[i]->devname, proc_cciss);
4455         unregister_blkdev(hba[i]->major, hba[i]->devname);
4456
4457         /* remove it from the disk list */
4458         for (j = 0; j < CISS_MAX_LUN; j++) {
4459                 struct gendisk *disk = hba[i]->gendisk[j];
4460                 if (disk) {
4461                         struct request_queue *q = disk->queue;
4462
4463                         if (disk->flags & GENHD_FL_UP) {
4464                                 cciss_destroy_ld_sysfs_entry(hba[i], j, 1);
4465                                 del_gendisk(disk);
4466                         }
4467                         if (q)
4468                                 blk_cleanup_queue(q);
4469                 }
4470         }
4471
4472 #ifdef CONFIG_CISS_SCSI_TAPE
4473         cciss_unregister_scsi(i);       /* unhook from SCSI subsystem */
4474 #endif
4475
4476         cciss_shutdown(pdev);
4477
4478 #ifdef CONFIG_PCI_MSI
4479         if (hba[i]->msix_vector)
4480                 pci_disable_msix(hba[i]->pdev);
4481         else if (hba[i]->msi_vector)
4482                 pci_disable_msi(hba[i]->pdev);
4483 #endif                          /* CONFIG_PCI_MSI */
4484
4485         iounmap(hba[i]->vaddr);
4486
4487         pci_free_consistent(hba[i]->pdev, hba[i]->nr_cmds * sizeof(CommandList_struct),
4488                             hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
4489         pci_free_consistent(hba[i]->pdev, hba[i]->nr_cmds * sizeof(ErrorInfo_struct),
4490                             hba[i]->errinfo_pool, hba[i]->errinfo_pool_dhandle);
4491         kfree(hba[i]->cmd_pool_bits);
4492         /*
4493          * Deliberately omit pci_disable_device(): it does something nasty to
4494          * Smart Array controllers that pci_enable_device does not undo
4495          */
4496         pci_release_regions(pdev);
4497         pci_set_drvdata(pdev, NULL);
4498         cciss_destroy_hba_sysfs_entry(hba[i]);
4499         mutex_unlock(&hba[i]->busy_shutting_down);
4500         free_hba(i);
4501 }
4502
4503 static struct pci_driver cciss_pci_driver = {
4504         .name = "cciss",
4505         .probe = cciss_init_one,
4506         .remove = __devexit_p(cciss_remove_one),
4507         .id_table = cciss_pci_device_id,        /* id_table */
4508         .shutdown = cciss_shutdown,
4509 };
4510
4511 /*
4512  *  This is it.  Register the PCI driver information for the cards we control
4513  *  the OS will call our registered routines when it finds one of our cards.
4514  */
4515 static int __init cciss_init(void)
4516 {
4517         int err;
4518
4519         /*
4520          * The hardware requires that commands are aligned on a 64-bit
4521          * boundary. Given that we use pci_alloc_consistent() to allocate an
4522          * array of them, the size must be a multiple of 8 bytes.
4523          */
4524         BUILD_BUG_ON(sizeof(CommandList_struct) % 8);
4525
4526         printk(KERN_INFO DRIVER_NAME "\n");
4527
4528         err = bus_register(&cciss_bus_type);
4529         if (err)
4530                 return err;
4531
4532         /* Start the scan thread */
4533         cciss_scan_thread = kthread_run(scan_thread, NULL, "cciss_scan");
4534         if (IS_ERR(cciss_scan_thread)) {
4535                 err = PTR_ERR(cciss_scan_thread);
4536                 goto err_bus_unregister;
4537         }
4538
4539         /* Register for our PCI devices */
4540         err = pci_register_driver(&cciss_pci_driver);
4541         if (err)
4542                 goto err_thread_stop;
4543
4544         return err;
4545
4546 err_thread_stop:
4547         kthread_stop(cciss_scan_thread);
4548 err_bus_unregister:
4549         bus_unregister(&cciss_bus_type);
4550
4551         return err;
4552 }
4553
4554 static void __exit cciss_cleanup(void)
4555 {
4556         int i;
4557
4558         pci_unregister_driver(&cciss_pci_driver);
4559         /* double check that all controller entrys have been removed */
4560         for (i = 0; i < MAX_CTLR; i++) {
4561                 if (hba[i] != NULL) {
4562                         printk(KERN_WARNING "cciss: had to remove"
4563                                " controller %d\n", i);
4564                         cciss_remove_one(hba[i]->pdev);
4565                 }
4566         }
4567         kthread_stop(cciss_scan_thread);
4568         remove_proc_entry("driver/cciss", NULL);
4569         bus_unregister(&cciss_bus_type);
4570 }
4571
4572 static void fail_all_cmds(unsigned long ctlr)
4573 {
4574         /* If we get here, the board is apparently dead. */
4575         ctlr_info_t *h = hba[ctlr];
4576         CommandList_struct *c;
4577         unsigned long flags;
4578
4579         printk(KERN_WARNING "cciss%d: controller not responding.\n", h->ctlr);
4580         h->alive = 0;           /* the controller apparently died... */
4581
4582         spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
4583
4584         pci_disable_device(h->pdev);    /* Make sure it is really dead. */
4585
4586         /* move everything off the request queue onto the completed queue */
4587         while (!hlist_empty(&h->reqQ)) {
4588                 c = hlist_entry(h->reqQ.first, CommandList_struct, list);
4589                 removeQ(c);
4590                 h->Qdepth--;
4591                 addQ(&h->cmpQ, c);
4592         }
4593
4594         /* Now, fail everything on the completed queue with a HW error */
4595         while (!hlist_empty(&h->cmpQ)) {
4596                 c = hlist_entry(h->cmpQ.first, CommandList_struct, list);
4597                 removeQ(c);
4598                 if (c->cmd_type != CMD_MSG_STALE)
4599                         c->err_info->CommandStatus = CMD_HARDWARE_ERR;
4600                 if (c->cmd_type == CMD_RWREQ) {
4601                         complete_command(h, c, 0);
4602                 } else if (c->cmd_type == CMD_IOCTL_PEND)
4603                         complete(c->waiting);
4604 #ifdef CONFIG_CISS_SCSI_TAPE
4605                 else if (c->cmd_type == CMD_SCSI)
4606                         complete_scsi_command(c, 0, 0);
4607 #endif
4608         }
4609         spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
4610         return;
4611 }
4612
4613 module_init(cciss_init);
4614 module_exit(cciss_cleanup);