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