[SCSI] hpsa: forbid hard reset of 640x boards
[linux-2.6.git] / drivers / scsi / hpsa.c
1 /*
2  *    Disk Array driver for HP Smart Array SAS controllers
3  *    Copyright 2000, 2009 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, GOOD TITLE or
12  *    NON INFRINGEMENT.  See the GNU 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., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *
18  *    Questions/Comments/Bugfixes to iss_storagedev@hp.com
19  *
20  */
21
22 #include <linux/module.h>
23 #include <linux/interrupt.h>
24 #include <linux/types.h>
25 #include <linux/pci.h>
26 #include <linux/kernel.h>
27 #include <linux/slab.h>
28 #include <linux/delay.h>
29 #include <linux/fs.h>
30 #include <linux/timer.h>
31 #include <linux/seq_file.h>
32 #include <linux/init.h>
33 #include <linux/spinlock.h>
34 #include <linux/smp_lock.h>
35 #include <linux/compat.h>
36 #include <linux/blktrace_api.h>
37 #include <linux/uaccess.h>
38 #include <linux/io.h>
39 #include <linux/dma-mapping.h>
40 #include <linux/completion.h>
41 #include <linux/moduleparam.h>
42 #include <scsi/scsi.h>
43 #include <scsi/scsi_cmnd.h>
44 #include <scsi/scsi_device.h>
45 #include <scsi/scsi_host.h>
46 #include <scsi/scsi_tcq.h>
47 #include <linux/cciss_ioctl.h>
48 #include <linux/string.h>
49 #include <linux/bitmap.h>
50 #include <asm/atomic.h>
51 #include <linux/kthread.h>
52 #include "hpsa_cmd.h"
53 #include "hpsa.h"
54
55 /* HPSA_DRIVER_VERSION must be 3 byte values (0-255) separated by '.' */
56 #define HPSA_DRIVER_VERSION "2.0.2-1"
57 #define DRIVER_NAME "HP HPSA Driver (v " HPSA_DRIVER_VERSION ")"
58
59 /* How long to wait (in milliseconds) for board to go into simple mode */
60 #define MAX_CONFIG_WAIT 30000
61 #define MAX_IOCTL_CONFIG_WAIT 1000
62
63 /*define how many times we will try a command because of bus resets */
64 #define MAX_CMD_RETRIES 3
65
66 /* Embedded module documentation macros - see modules.h */
67 MODULE_AUTHOR("Hewlett-Packard Company");
68 MODULE_DESCRIPTION("Driver for HP Smart Array Controller version " \
69         HPSA_DRIVER_VERSION);
70 MODULE_SUPPORTED_DEVICE("HP Smart Array Controllers");
71 MODULE_VERSION(HPSA_DRIVER_VERSION);
72 MODULE_LICENSE("GPL");
73
74 static int hpsa_allow_any;
75 module_param(hpsa_allow_any, int, S_IRUGO|S_IWUSR);
76 MODULE_PARM_DESC(hpsa_allow_any,
77                 "Allow hpsa driver to access unknown HP Smart Array hardware");
78
79 /* define the PCI info for the cards we can control */
80 static const struct pci_device_id hpsa_pci_device_id[] = {
81         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3241},
82         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3243},
83         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3245},
84         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3247},
85         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3249},
86         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324a},
87         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324b},
88         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3233},
89         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3250},
90         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3251},
91         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3252},
92         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3253},
93         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3254},
94 #define PCI_DEVICE_ID_HP_CISSF 0x333f
95         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x333F},
96         {PCI_VENDOR_ID_HP,     PCI_ANY_ID,             PCI_ANY_ID, PCI_ANY_ID,
97                 PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
98         {PCI_VENDOR_ID_COMPAQ,     PCI_ANY_ID,             PCI_ANY_ID, PCI_ANY_ID,
99                 PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
100         {0,}
101 };
102
103 MODULE_DEVICE_TABLE(pci, hpsa_pci_device_id);
104
105 /*  board_id = Subsystem Device ID & Vendor ID
106  *  product = Marketing Name for the board
107  *  access = Address of the struct of function pointers
108  */
109 static struct board_type products[] = {
110         {0x3241103C, "Smart Array P212", &SA5_access},
111         {0x3243103C, "Smart Array P410", &SA5_access},
112         {0x3245103C, "Smart Array P410i", &SA5_access},
113         {0x3247103C, "Smart Array P411", &SA5_access},
114         {0x3249103C, "Smart Array P812", &SA5_access},
115         {0x324a103C, "Smart Array P712m", &SA5_access},
116         {0x324b103C, "Smart Array P711m", &SA5_access},
117         {0x3233103C, "StorageWorks P1210m", &SA5_access},
118         {0x333F103C, "StorageWorks P1210m", &SA5_access},
119         {0x3250103C, "Smart Array", &SA5_access},
120         {0x3250113C, "Smart Array", &SA5_access},
121         {0x3250123C, "Smart Array", &SA5_access},
122         {0x3250133C, "Smart Array", &SA5_access},
123         {0x3250143C, "Smart Array", &SA5_access},
124         {0xFFFF103C, "Unknown Smart Array", &SA5_access},
125 };
126
127 static int number_of_controllers;
128
129 static irqreturn_t do_hpsa_intr(int irq, void *dev_id);
130 static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg);
131 static void start_io(struct ctlr_info *h);
132
133 #ifdef CONFIG_COMPAT
134 static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg);
135 #endif
136
137 static void cmd_free(struct ctlr_info *h, struct CommandList *c);
138 static void cmd_special_free(struct ctlr_info *h, struct CommandList *c);
139 static struct CommandList *cmd_alloc(struct ctlr_info *h);
140 static struct CommandList *cmd_special_alloc(struct ctlr_info *h);
141 static void fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
142         void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
143         int cmd_type);
144
145 static int hpsa_scsi_queue_command(struct scsi_cmnd *cmd,
146                 void (*done)(struct scsi_cmnd *));
147 static void hpsa_scan_start(struct Scsi_Host *);
148 static int hpsa_scan_finished(struct Scsi_Host *sh,
149         unsigned long elapsed_time);
150 static int hpsa_change_queue_depth(struct scsi_device *sdev,
151         int qdepth, int reason);
152
153 static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd);
154 static int hpsa_slave_alloc(struct scsi_device *sdev);
155 static void hpsa_slave_destroy(struct scsi_device *sdev);
156
157 static ssize_t raid_level_show(struct device *dev,
158         struct device_attribute *attr, char *buf);
159 static ssize_t lunid_show(struct device *dev,
160         struct device_attribute *attr, char *buf);
161 static ssize_t unique_id_show(struct device *dev,
162         struct device_attribute *attr, char *buf);
163 static ssize_t host_show_firmware_revision(struct device *dev,
164              struct device_attribute *attr, char *buf);
165 static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno);
166 static ssize_t host_store_rescan(struct device *dev,
167          struct device_attribute *attr, const char *buf, size_t count);
168 static int check_for_unit_attention(struct ctlr_info *h,
169         struct CommandList *c);
170 static void check_ioctl_unit_attention(struct ctlr_info *h,
171         struct CommandList *c);
172 /* performant mode helper functions */
173 static void calc_bucket_map(int *bucket, int num_buckets,
174         int nsgs, int *bucket_map);
175 static __devinit void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h);
176 static inline u32 next_command(struct ctlr_info *h);
177 static int __devinit hpsa_find_cfg_addrs(struct pci_dev *pdev,
178         void __iomem *vaddr, u32 *cfg_base_addr, u64 *cfg_base_addr_index,
179         u64 *cfg_offset);
180 static int __devinit hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
181         unsigned long *memory_bar);
182 static int __devinit hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id);
183
184 static DEVICE_ATTR(raid_level, S_IRUGO, raid_level_show, NULL);
185 static DEVICE_ATTR(lunid, S_IRUGO, lunid_show, NULL);
186 static DEVICE_ATTR(unique_id, S_IRUGO, unique_id_show, NULL);
187 static DEVICE_ATTR(rescan, S_IWUSR, NULL, host_store_rescan);
188 static DEVICE_ATTR(firmware_revision, S_IRUGO,
189         host_show_firmware_revision, NULL);
190
191 static struct device_attribute *hpsa_sdev_attrs[] = {
192         &dev_attr_raid_level,
193         &dev_attr_lunid,
194         &dev_attr_unique_id,
195         NULL,
196 };
197
198 static struct device_attribute *hpsa_shost_attrs[] = {
199         &dev_attr_rescan,
200         &dev_attr_firmware_revision,
201         NULL,
202 };
203
204 static struct scsi_host_template hpsa_driver_template = {
205         .module                 = THIS_MODULE,
206         .name                   = "hpsa",
207         .proc_name              = "hpsa",
208         .queuecommand           = hpsa_scsi_queue_command,
209         .scan_start             = hpsa_scan_start,
210         .scan_finished          = hpsa_scan_finished,
211         .change_queue_depth     = hpsa_change_queue_depth,
212         .this_id                = -1,
213         .use_clustering         = ENABLE_CLUSTERING,
214         .eh_device_reset_handler = hpsa_eh_device_reset_handler,
215         .ioctl                  = hpsa_ioctl,
216         .slave_alloc            = hpsa_slave_alloc,
217         .slave_destroy          = hpsa_slave_destroy,
218 #ifdef CONFIG_COMPAT
219         .compat_ioctl           = hpsa_compat_ioctl,
220 #endif
221         .sdev_attrs = hpsa_sdev_attrs,
222         .shost_attrs = hpsa_shost_attrs,
223 };
224
225 static inline struct ctlr_info *sdev_to_hba(struct scsi_device *sdev)
226 {
227         unsigned long *priv = shost_priv(sdev->host);
228         return (struct ctlr_info *) *priv;
229 }
230
231 static inline struct ctlr_info *shost_to_hba(struct Scsi_Host *sh)
232 {
233         unsigned long *priv = shost_priv(sh);
234         return (struct ctlr_info *) *priv;
235 }
236
237 static int check_for_unit_attention(struct ctlr_info *h,
238         struct CommandList *c)
239 {
240         if (c->err_info->SenseInfo[2] != UNIT_ATTENTION)
241                 return 0;
242
243         switch (c->err_info->SenseInfo[12]) {
244         case STATE_CHANGED:
245                 dev_warn(&h->pdev->dev, "hpsa%d: a state change "
246                         "detected, command retried\n", h->ctlr);
247                 break;
248         case LUN_FAILED:
249                 dev_warn(&h->pdev->dev, "hpsa%d: LUN failure "
250                         "detected, action required\n", h->ctlr);
251                 break;
252         case REPORT_LUNS_CHANGED:
253                 dev_warn(&h->pdev->dev, "hpsa%d: report LUN data "
254                         "changed, action required\n", h->ctlr);
255         /*
256          * Note: this REPORT_LUNS_CHANGED condition only occurs on the MSA2012.
257          */
258                 break;
259         case POWER_OR_RESET:
260                 dev_warn(&h->pdev->dev, "hpsa%d: a power on "
261                         "or device reset detected\n", h->ctlr);
262                 break;
263         case UNIT_ATTENTION_CLEARED:
264                 dev_warn(&h->pdev->dev, "hpsa%d: unit attention "
265                     "cleared by another initiator\n", h->ctlr);
266                 break;
267         default:
268                 dev_warn(&h->pdev->dev, "hpsa%d: unknown "
269                         "unit attention detected\n", h->ctlr);
270                 break;
271         }
272         return 1;
273 }
274
275 static ssize_t host_store_rescan(struct device *dev,
276                                  struct device_attribute *attr,
277                                  const char *buf, size_t count)
278 {
279         struct ctlr_info *h;
280         struct Scsi_Host *shost = class_to_shost(dev);
281         h = shost_to_hba(shost);
282         hpsa_scan_start(h->scsi_host);
283         return count;
284 }
285
286 static ssize_t host_show_firmware_revision(struct device *dev,
287              struct device_attribute *attr, char *buf)
288 {
289         struct ctlr_info *h;
290         struct Scsi_Host *shost = class_to_shost(dev);
291         unsigned char *fwrev;
292
293         h = shost_to_hba(shost);
294         if (!h->hba_inquiry_data)
295                 return 0;
296         fwrev = &h->hba_inquiry_data[32];
297         return snprintf(buf, 20, "%c%c%c%c\n",
298                 fwrev[0], fwrev[1], fwrev[2], fwrev[3]);
299 }
300
301 /* Enqueuing and dequeuing functions for cmdlists. */
302 static inline void addQ(struct hlist_head *list, struct CommandList *c)
303 {
304         hlist_add_head(&c->list, list);
305 }
306
307 static inline u32 next_command(struct ctlr_info *h)
308 {
309         u32 a;
310
311         if (unlikely(h->transMethod != CFGTBL_Trans_Performant))
312                 return h->access.command_completed(h);
313
314         if ((*(h->reply_pool_head) & 1) == (h->reply_pool_wraparound)) {
315                 a = *(h->reply_pool_head); /* Next cmd in ring buffer */
316                 (h->reply_pool_head)++;
317                 h->commands_outstanding--;
318         } else {
319                 a = FIFO_EMPTY;
320         }
321         /* Check for wraparound */
322         if (h->reply_pool_head == (h->reply_pool + h->max_commands)) {
323                 h->reply_pool_head = h->reply_pool;
324                 h->reply_pool_wraparound ^= 1;
325         }
326         return a;
327 }
328
329 /* set_performant_mode: Modify the tag for cciss performant
330  * set bit 0 for pull model, bits 3-1 for block fetch
331  * register number
332  */
333 static void set_performant_mode(struct ctlr_info *h, struct CommandList *c)
334 {
335         if (likely(h->transMethod == CFGTBL_Trans_Performant))
336                 c->busaddr |= 1 | (h->blockFetchTable[c->Header.SGList] << 1);
337 }
338
339 static void enqueue_cmd_and_start_io(struct ctlr_info *h,
340         struct CommandList *c)
341 {
342         unsigned long flags;
343
344         set_performant_mode(h, c);
345         spin_lock_irqsave(&h->lock, flags);
346         addQ(&h->reqQ, c);
347         h->Qdepth++;
348         start_io(h);
349         spin_unlock_irqrestore(&h->lock, flags);
350 }
351
352 static inline void removeQ(struct CommandList *c)
353 {
354         if (WARN_ON(hlist_unhashed(&c->list)))
355                 return;
356         hlist_del_init(&c->list);
357 }
358
359 static inline int is_hba_lunid(unsigned char scsi3addr[])
360 {
361         return memcmp(scsi3addr, RAID_CTLR_LUNID, 8) == 0;
362 }
363
364 static inline int is_logical_dev_addr_mode(unsigned char scsi3addr[])
365 {
366         return (scsi3addr[3] & 0xC0) == 0x40;
367 }
368
369 static inline int is_scsi_rev_5(struct ctlr_info *h)
370 {
371         if (!h->hba_inquiry_data)
372                 return 0;
373         if ((h->hba_inquiry_data[2] & 0x07) == 5)
374                 return 1;
375         return 0;
376 }
377
378 static const char *raid_label[] = { "0", "4", "1(1+0)", "5", "5+1", "ADG",
379         "UNKNOWN"
380 };
381 #define RAID_UNKNOWN (ARRAY_SIZE(raid_label) - 1)
382
383 static ssize_t raid_level_show(struct device *dev,
384              struct device_attribute *attr, char *buf)
385 {
386         ssize_t l = 0;
387         unsigned char rlevel;
388         struct ctlr_info *h;
389         struct scsi_device *sdev;
390         struct hpsa_scsi_dev_t *hdev;
391         unsigned long flags;
392
393         sdev = to_scsi_device(dev);
394         h = sdev_to_hba(sdev);
395         spin_lock_irqsave(&h->lock, flags);
396         hdev = sdev->hostdata;
397         if (!hdev) {
398                 spin_unlock_irqrestore(&h->lock, flags);
399                 return -ENODEV;
400         }
401
402         /* Is this even a logical drive? */
403         if (!is_logical_dev_addr_mode(hdev->scsi3addr)) {
404                 spin_unlock_irqrestore(&h->lock, flags);
405                 l = snprintf(buf, PAGE_SIZE, "N/A\n");
406                 return l;
407         }
408
409         rlevel = hdev->raid_level;
410         spin_unlock_irqrestore(&h->lock, flags);
411         if (rlevel > RAID_UNKNOWN)
412                 rlevel = RAID_UNKNOWN;
413         l = snprintf(buf, PAGE_SIZE, "RAID %s\n", raid_label[rlevel]);
414         return l;
415 }
416
417 static ssize_t lunid_show(struct device *dev,
418              struct device_attribute *attr, char *buf)
419 {
420         struct ctlr_info *h;
421         struct scsi_device *sdev;
422         struct hpsa_scsi_dev_t *hdev;
423         unsigned long flags;
424         unsigned char lunid[8];
425
426         sdev = to_scsi_device(dev);
427         h = sdev_to_hba(sdev);
428         spin_lock_irqsave(&h->lock, flags);
429         hdev = sdev->hostdata;
430         if (!hdev) {
431                 spin_unlock_irqrestore(&h->lock, flags);
432                 return -ENODEV;
433         }
434         memcpy(lunid, hdev->scsi3addr, sizeof(lunid));
435         spin_unlock_irqrestore(&h->lock, flags);
436         return snprintf(buf, 20, "0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
437                 lunid[0], lunid[1], lunid[2], lunid[3],
438                 lunid[4], lunid[5], lunid[6], lunid[7]);
439 }
440
441 static ssize_t unique_id_show(struct device *dev,
442              struct device_attribute *attr, char *buf)
443 {
444         struct ctlr_info *h;
445         struct scsi_device *sdev;
446         struct hpsa_scsi_dev_t *hdev;
447         unsigned long flags;
448         unsigned char sn[16];
449
450         sdev = to_scsi_device(dev);
451         h = sdev_to_hba(sdev);
452         spin_lock_irqsave(&h->lock, flags);
453         hdev = sdev->hostdata;
454         if (!hdev) {
455                 spin_unlock_irqrestore(&h->lock, flags);
456                 return -ENODEV;
457         }
458         memcpy(sn, hdev->device_id, sizeof(sn));
459         spin_unlock_irqrestore(&h->lock, flags);
460         return snprintf(buf, 16 * 2 + 2,
461                         "%02X%02X%02X%02X%02X%02X%02X%02X"
462                         "%02X%02X%02X%02X%02X%02X%02X%02X\n",
463                         sn[0], sn[1], sn[2], sn[3],
464                         sn[4], sn[5], sn[6], sn[7],
465                         sn[8], sn[9], sn[10], sn[11],
466                         sn[12], sn[13], sn[14], sn[15]);
467 }
468
469 static int hpsa_find_target_lun(struct ctlr_info *h,
470         unsigned char scsi3addr[], int bus, int *target, int *lun)
471 {
472         /* finds an unused bus, target, lun for a new physical device
473          * assumes h->devlock is held
474          */
475         int i, found = 0;
476         DECLARE_BITMAP(lun_taken, HPSA_MAX_SCSI_DEVS_PER_HBA);
477
478         memset(&lun_taken[0], 0, HPSA_MAX_SCSI_DEVS_PER_HBA >> 3);
479
480         for (i = 0; i < h->ndevices; i++) {
481                 if (h->dev[i]->bus == bus && h->dev[i]->target != -1)
482                         set_bit(h->dev[i]->target, lun_taken);
483         }
484
485         for (i = 0; i < HPSA_MAX_SCSI_DEVS_PER_HBA; i++) {
486                 if (!test_bit(i, lun_taken)) {
487                         /* *bus = 1; */
488                         *target = i;
489                         *lun = 0;
490                         found = 1;
491                         break;
492                 }
493         }
494         return !found;
495 }
496
497 /* Add an entry into h->dev[] array. */
498 static int hpsa_scsi_add_entry(struct ctlr_info *h, int hostno,
499                 struct hpsa_scsi_dev_t *device,
500                 struct hpsa_scsi_dev_t *added[], int *nadded)
501 {
502         /* assumes h->devlock is held */
503         int n = h->ndevices;
504         int i;
505         unsigned char addr1[8], addr2[8];
506         struct hpsa_scsi_dev_t *sd;
507
508         if (n >= HPSA_MAX_SCSI_DEVS_PER_HBA) {
509                 dev_err(&h->pdev->dev, "too many devices, some will be "
510                         "inaccessible.\n");
511                 return -1;
512         }
513
514         /* physical devices do not have lun or target assigned until now. */
515         if (device->lun != -1)
516                 /* Logical device, lun is already assigned. */
517                 goto lun_assigned;
518
519         /* If this device a non-zero lun of a multi-lun device
520          * byte 4 of the 8-byte LUN addr will contain the logical
521          * unit no, zero otherise.
522          */
523         if (device->scsi3addr[4] == 0) {
524                 /* This is not a non-zero lun of a multi-lun device */
525                 if (hpsa_find_target_lun(h, device->scsi3addr,
526                         device->bus, &device->target, &device->lun) != 0)
527                         return -1;
528                 goto lun_assigned;
529         }
530
531         /* This is a non-zero lun of a multi-lun device.
532          * Search through our list and find the device which
533          * has the same 8 byte LUN address, excepting byte 4.
534          * Assign the same bus and target for this new LUN.
535          * Use the logical unit number from the firmware.
536          */
537         memcpy(addr1, device->scsi3addr, 8);
538         addr1[4] = 0;
539         for (i = 0; i < n; i++) {
540                 sd = h->dev[i];
541                 memcpy(addr2, sd->scsi3addr, 8);
542                 addr2[4] = 0;
543                 /* differ only in byte 4? */
544                 if (memcmp(addr1, addr2, 8) == 0) {
545                         device->bus = sd->bus;
546                         device->target = sd->target;
547                         device->lun = device->scsi3addr[4];
548                         break;
549                 }
550         }
551         if (device->lun == -1) {
552                 dev_warn(&h->pdev->dev, "physical device with no LUN=0,"
553                         " suspect firmware bug or unsupported hardware "
554                         "configuration.\n");
555                         return -1;
556         }
557
558 lun_assigned:
559
560         h->dev[n] = device;
561         h->ndevices++;
562         added[*nadded] = device;
563         (*nadded)++;
564
565         /* initially, (before registering with scsi layer) we don't
566          * know our hostno and we don't want to print anything first
567          * time anyway (the scsi layer's inquiries will show that info)
568          */
569         /* if (hostno != -1) */
570                 dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d added.\n",
571                         scsi_device_type(device->devtype), hostno,
572                         device->bus, device->target, device->lun);
573         return 0;
574 }
575
576 /* Replace an entry from h->dev[] array. */
577 static void hpsa_scsi_replace_entry(struct ctlr_info *h, int hostno,
578         int entry, struct hpsa_scsi_dev_t *new_entry,
579         struct hpsa_scsi_dev_t *added[], int *nadded,
580         struct hpsa_scsi_dev_t *removed[], int *nremoved)
581 {
582         /* assumes h->devlock is held */
583         BUG_ON(entry < 0 || entry >= HPSA_MAX_SCSI_DEVS_PER_HBA);
584         removed[*nremoved] = h->dev[entry];
585         (*nremoved)++;
586         h->dev[entry] = new_entry;
587         added[*nadded] = new_entry;
588         (*nadded)++;
589         dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d changed.\n",
590                 scsi_device_type(new_entry->devtype), hostno, new_entry->bus,
591                         new_entry->target, new_entry->lun);
592 }
593
594 /* Remove an entry from h->dev[] array. */
595 static void hpsa_scsi_remove_entry(struct ctlr_info *h, int hostno, int entry,
596         struct hpsa_scsi_dev_t *removed[], int *nremoved)
597 {
598         /* assumes h->devlock is held */
599         int i;
600         struct hpsa_scsi_dev_t *sd;
601
602         BUG_ON(entry < 0 || entry >= HPSA_MAX_SCSI_DEVS_PER_HBA);
603
604         sd = h->dev[entry];
605         removed[*nremoved] = h->dev[entry];
606         (*nremoved)++;
607
608         for (i = entry; i < h->ndevices-1; i++)
609                 h->dev[i] = h->dev[i+1];
610         h->ndevices--;
611         dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d removed.\n",
612                 scsi_device_type(sd->devtype), hostno, sd->bus, sd->target,
613                 sd->lun);
614 }
615
616 #define SCSI3ADDR_EQ(a, b) ( \
617         (a)[7] == (b)[7] && \
618         (a)[6] == (b)[6] && \
619         (a)[5] == (b)[5] && \
620         (a)[4] == (b)[4] && \
621         (a)[3] == (b)[3] && \
622         (a)[2] == (b)[2] && \
623         (a)[1] == (b)[1] && \
624         (a)[0] == (b)[0])
625
626 static void fixup_botched_add(struct ctlr_info *h,
627         struct hpsa_scsi_dev_t *added)
628 {
629         /* called when scsi_add_device fails in order to re-adjust
630          * h->dev[] to match the mid layer's view.
631          */
632         unsigned long flags;
633         int i, j;
634
635         spin_lock_irqsave(&h->lock, flags);
636         for (i = 0; i < h->ndevices; i++) {
637                 if (h->dev[i] == added) {
638                         for (j = i; j < h->ndevices-1; j++)
639                                 h->dev[j] = h->dev[j+1];
640                         h->ndevices--;
641                         break;
642                 }
643         }
644         spin_unlock_irqrestore(&h->lock, flags);
645         kfree(added);
646 }
647
648 static inline int device_is_the_same(struct hpsa_scsi_dev_t *dev1,
649         struct hpsa_scsi_dev_t *dev2)
650 {
651         if ((is_logical_dev_addr_mode(dev1->scsi3addr) ||
652                 (dev1->lun != -1 && dev2->lun != -1)) &&
653                 dev1->devtype != 0x0C)
654                 return (memcmp(dev1, dev2, sizeof(*dev1)) == 0);
655
656         /* we compare everything except lun and target as these
657          * are not yet assigned.  Compare parts likely
658          * to differ first
659          */
660         if (memcmp(dev1->scsi3addr, dev2->scsi3addr,
661                 sizeof(dev1->scsi3addr)) != 0)
662                 return 0;
663         if (memcmp(dev1->device_id, dev2->device_id,
664                 sizeof(dev1->device_id)) != 0)
665                 return 0;
666         if (memcmp(dev1->model, dev2->model, sizeof(dev1->model)) != 0)
667                 return 0;
668         if (memcmp(dev1->vendor, dev2->vendor, sizeof(dev1->vendor)) != 0)
669                 return 0;
670         if (memcmp(dev1->revision, dev2->revision, sizeof(dev1->revision)) != 0)
671                 return 0;
672         if (dev1->devtype != dev2->devtype)
673                 return 0;
674         if (dev1->raid_level != dev2->raid_level)
675                 return 0;
676         if (dev1->bus != dev2->bus)
677                 return 0;
678         return 1;
679 }
680
681 /* Find needle in haystack.  If exact match found, return DEVICE_SAME,
682  * and return needle location in *index.  If scsi3addr matches, but not
683  * vendor, model, serial num, etc. return DEVICE_CHANGED, and return needle
684  * location in *index.  If needle not found, return DEVICE_NOT_FOUND.
685  */
686 static int hpsa_scsi_find_entry(struct hpsa_scsi_dev_t *needle,
687         struct hpsa_scsi_dev_t *haystack[], int haystack_size,
688         int *index)
689 {
690         int i;
691 #define DEVICE_NOT_FOUND 0
692 #define DEVICE_CHANGED 1
693 #define DEVICE_SAME 2
694         for (i = 0; i < haystack_size; i++) {
695                 if (haystack[i] == NULL) /* previously removed. */
696                         continue;
697                 if (SCSI3ADDR_EQ(needle->scsi3addr, haystack[i]->scsi3addr)) {
698                         *index = i;
699                         if (device_is_the_same(needle, haystack[i]))
700                                 return DEVICE_SAME;
701                         else
702                                 return DEVICE_CHANGED;
703                 }
704         }
705         *index = -1;
706         return DEVICE_NOT_FOUND;
707 }
708
709 static void adjust_hpsa_scsi_table(struct ctlr_info *h, int hostno,
710         struct hpsa_scsi_dev_t *sd[], int nsds)
711 {
712         /* sd contains scsi3 addresses and devtypes, and inquiry
713          * data.  This function takes what's in sd to be the current
714          * reality and updates h->dev[] to reflect that reality.
715          */
716         int i, entry, device_change, changes = 0;
717         struct hpsa_scsi_dev_t *csd;
718         unsigned long flags;
719         struct hpsa_scsi_dev_t **added, **removed;
720         int nadded, nremoved;
721         struct Scsi_Host *sh = NULL;
722
723         added = kzalloc(sizeof(*added) * HPSA_MAX_SCSI_DEVS_PER_HBA,
724                 GFP_KERNEL);
725         removed = kzalloc(sizeof(*removed) * HPSA_MAX_SCSI_DEVS_PER_HBA,
726                 GFP_KERNEL);
727
728         if (!added || !removed) {
729                 dev_warn(&h->pdev->dev, "out of memory in "
730                         "adjust_hpsa_scsi_table\n");
731                 goto free_and_out;
732         }
733
734         spin_lock_irqsave(&h->devlock, flags);
735
736         /* find any devices in h->dev[] that are not in
737          * sd[] and remove them from h->dev[], and for any
738          * devices which have changed, remove the old device
739          * info and add the new device info.
740          */
741         i = 0;
742         nremoved = 0;
743         nadded = 0;
744         while (i < h->ndevices) {
745                 csd = h->dev[i];
746                 device_change = hpsa_scsi_find_entry(csd, sd, nsds, &entry);
747                 if (device_change == DEVICE_NOT_FOUND) {
748                         changes++;
749                         hpsa_scsi_remove_entry(h, hostno, i,
750                                 removed, &nremoved);
751                         continue; /* remove ^^^, hence i not incremented */
752                 } else if (device_change == DEVICE_CHANGED) {
753                         changes++;
754                         hpsa_scsi_replace_entry(h, hostno, i, sd[entry],
755                                 added, &nadded, removed, &nremoved);
756                         /* Set it to NULL to prevent it from being freed
757                          * at the bottom of hpsa_update_scsi_devices()
758                          */
759                         sd[entry] = NULL;
760                 }
761                 i++;
762         }
763
764         /* Now, make sure every device listed in sd[] is also
765          * listed in h->dev[], adding them if they aren't found
766          */
767
768         for (i = 0; i < nsds; i++) {
769                 if (!sd[i]) /* if already added above. */
770                         continue;
771                 device_change = hpsa_scsi_find_entry(sd[i], h->dev,
772                                         h->ndevices, &entry);
773                 if (device_change == DEVICE_NOT_FOUND) {
774                         changes++;
775                         if (hpsa_scsi_add_entry(h, hostno, sd[i],
776                                 added, &nadded) != 0)
777                                 break;
778                         sd[i] = NULL; /* prevent from being freed later. */
779                 } else if (device_change == DEVICE_CHANGED) {
780                         /* should never happen... */
781                         changes++;
782                         dev_warn(&h->pdev->dev,
783                                 "device unexpectedly changed.\n");
784                         /* but if it does happen, we just ignore that device */
785                 }
786         }
787         spin_unlock_irqrestore(&h->devlock, flags);
788
789         /* Don't notify scsi mid layer of any changes the first time through
790          * (or if there are no changes) scsi_scan_host will do it later the
791          * first time through.
792          */
793         if (hostno == -1 || !changes)
794                 goto free_and_out;
795
796         sh = h->scsi_host;
797         /* Notify scsi mid layer of any removed devices */
798         for (i = 0; i < nremoved; i++) {
799                 struct scsi_device *sdev =
800                         scsi_device_lookup(sh, removed[i]->bus,
801                                 removed[i]->target, removed[i]->lun);
802                 if (sdev != NULL) {
803                         scsi_remove_device(sdev);
804                         scsi_device_put(sdev);
805                 } else {
806                         /* We don't expect to get here.
807                          * future cmds to this device will get selection
808                          * timeout as if the device was gone.
809                          */
810                         dev_warn(&h->pdev->dev, "didn't find c%db%dt%dl%d "
811                                 " for removal.", hostno, removed[i]->bus,
812                                 removed[i]->target, removed[i]->lun);
813                 }
814                 kfree(removed[i]);
815                 removed[i] = NULL;
816         }
817
818         /* Notify scsi mid layer of any added devices */
819         for (i = 0; i < nadded; i++) {
820                 if (scsi_add_device(sh, added[i]->bus,
821                         added[i]->target, added[i]->lun) == 0)
822                         continue;
823                 dev_warn(&h->pdev->dev, "scsi_add_device c%db%dt%dl%d failed, "
824                         "device not added.\n", hostno, added[i]->bus,
825                         added[i]->target, added[i]->lun);
826                 /* now we have to remove it from h->dev,
827                  * since it didn't get added to scsi mid layer
828                  */
829                 fixup_botched_add(h, added[i]);
830         }
831
832 free_and_out:
833         kfree(added);
834         kfree(removed);
835 }
836
837 /*
838  * Lookup bus/target/lun and retrun corresponding struct hpsa_scsi_dev_t *
839  * Assume's h->devlock is held.
840  */
841 static struct hpsa_scsi_dev_t *lookup_hpsa_scsi_dev(struct ctlr_info *h,
842         int bus, int target, int lun)
843 {
844         int i;
845         struct hpsa_scsi_dev_t *sd;
846
847         for (i = 0; i < h->ndevices; i++) {
848                 sd = h->dev[i];
849                 if (sd->bus == bus && sd->target == target && sd->lun == lun)
850                         return sd;
851         }
852         return NULL;
853 }
854
855 /* link sdev->hostdata to our per-device structure. */
856 static int hpsa_slave_alloc(struct scsi_device *sdev)
857 {
858         struct hpsa_scsi_dev_t *sd;
859         unsigned long flags;
860         struct ctlr_info *h;
861
862         h = sdev_to_hba(sdev);
863         spin_lock_irqsave(&h->devlock, flags);
864         sd = lookup_hpsa_scsi_dev(h, sdev_channel(sdev),
865                 sdev_id(sdev), sdev->lun);
866         if (sd != NULL)
867                 sdev->hostdata = sd;
868         spin_unlock_irqrestore(&h->devlock, flags);
869         return 0;
870 }
871
872 static void hpsa_slave_destroy(struct scsi_device *sdev)
873 {
874         /* nothing to do. */
875 }
876
877 static void hpsa_scsi_setup(struct ctlr_info *h)
878 {
879         h->ndevices = 0;
880         h->scsi_host = NULL;
881         spin_lock_init(&h->devlock);
882 }
883
884 static void hpsa_free_sg_chain_blocks(struct ctlr_info *h)
885 {
886         int i;
887
888         if (!h->cmd_sg_list)
889                 return;
890         for (i = 0; i < h->nr_cmds; i++) {
891                 kfree(h->cmd_sg_list[i]);
892                 h->cmd_sg_list[i] = NULL;
893         }
894         kfree(h->cmd_sg_list);
895         h->cmd_sg_list = NULL;
896 }
897
898 static int hpsa_allocate_sg_chain_blocks(struct ctlr_info *h)
899 {
900         int i;
901
902         if (h->chainsize <= 0)
903                 return 0;
904
905         h->cmd_sg_list = kzalloc(sizeof(*h->cmd_sg_list) * h->nr_cmds,
906                                 GFP_KERNEL);
907         if (!h->cmd_sg_list)
908                 return -ENOMEM;
909         for (i = 0; i < h->nr_cmds; i++) {
910                 h->cmd_sg_list[i] = kmalloc(sizeof(*h->cmd_sg_list[i]) *
911                                                 h->chainsize, GFP_KERNEL);
912                 if (!h->cmd_sg_list[i])
913                         goto clean;
914         }
915         return 0;
916
917 clean:
918         hpsa_free_sg_chain_blocks(h);
919         return -ENOMEM;
920 }
921
922 static void hpsa_map_sg_chain_block(struct ctlr_info *h,
923         struct CommandList *c)
924 {
925         struct SGDescriptor *chain_sg, *chain_block;
926         u64 temp64;
927
928         chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
929         chain_block = h->cmd_sg_list[c->cmdindex];
930         chain_sg->Ext = HPSA_SG_CHAIN;
931         chain_sg->Len = sizeof(*chain_sg) *
932                 (c->Header.SGTotal - h->max_cmd_sg_entries);
933         temp64 = pci_map_single(h->pdev, chain_block, chain_sg->Len,
934                                 PCI_DMA_TODEVICE);
935         chain_sg->Addr.lower = (u32) (temp64 & 0x0FFFFFFFFULL);
936         chain_sg->Addr.upper = (u32) ((temp64 >> 32) & 0x0FFFFFFFFULL);
937 }
938
939 static void hpsa_unmap_sg_chain_block(struct ctlr_info *h,
940         struct CommandList *c)
941 {
942         struct SGDescriptor *chain_sg;
943         union u64bit temp64;
944
945         if (c->Header.SGTotal <= h->max_cmd_sg_entries)
946                 return;
947
948         chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
949         temp64.val32.lower = chain_sg->Addr.lower;
950         temp64.val32.upper = chain_sg->Addr.upper;
951         pci_unmap_single(h->pdev, temp64.val, chain_sg->Len, PCI_DMA_TODEVICE);
952 }
953
954 static void complete_scsi_command(struct CommandList *cp,
955         int timeout, u32 tag)
956 {
957         struct scsi_cmnd *cmd;
958         struct ctlr_info *h;
959         struct ErrorInfo *ei;
960
961         unsigned char sense_key;
962         unsigned char asc;      /* additional sense code */
963         unsigned char ascq;     /* additional sense code qualifier */
964
965         ei = cp->err_info;
966         cmd = (struct scsi_cmnd *) cp->scsi_cmd;
967         h = cp->h;
968
969         scsi_dma_unmap(cmd); /* undo the DMA mappings */
970         if (cp->Header.SGTotal > h->max_cmd_sg_entries)
971                 hpsa_unmap_sg_chain_block(h, cp);
972
973         cmd->result = (DID_OK << 16);           /* host byte */
974         cmd->result |= (COMMAND_COMPLETE << 8); /* msg byte */
975         cmd->result |= ei->ScsiStatus;
976
977         /* copy the sense data whether we need to or not. */
978         memcpy(cmd->sense_buffer, ei->SenseInfo,
979                 ei->SenseLen > SCSI_SENSE_BUFFERSIZE ?
980                         SCSI_SENSE_BUFFERSIZE :
981                         ei->SenseLen);
982         scsi_set_resid(cmd, ei->ResidualCnt);
983
984         if (ei->CommandStatus == 0) {
985                 cmd->scsi_done(cmd);
986                 cmd_free(h, cp);
987                 return;
988         }
989
990         /* an error has occurred */
991         switch (ei->CommandStatus) {
992
993         case CMD_TARGET_STATUS:
994                 if (ei->ScsiStatus) {
995                         /* Get sense key */
996                         sense_key = 0xf & ei->SenseInfo[2];
997                         /* Get additional sense code */
998                         asc = ei->SenseInfo[12];
999                         /* Get addition sense code qualifier */
1000                         ascq = ei->SenseInfo[13];
1001                 }
1002
1003                 if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION) {
1004                         if (check_for_unit_attention(h, cp)) {
1005                                 cmd->result = DID_SOFT_ERROR << 16;
1006                                 break;
1007                         }
1008                         if (sense_key == ILLEGAL_REQUEST) {
1009                                 /*
1010                                  * SCSI REPORT_LUNS is commonly unsupported on
1011                                  * Smart Array.  Suppress noisy complaint.
1012                                  */
1013                                 if (cp->Request.CDB[0] == REPORT_LUNS)
1014                                         break;
1015
1016                                 /* If ASC/ASCQ indicate Logical Unit
1017                                  * Not Supported condition,
1018                                  */
1019                                 if ((asc == 0x25) && (ascq == 0x0)) {
1020                                         dev_warn(&h->pdev->dev, "cp %p "
1021                                                 "has check condition\n", cp);
1022                                         break;
1023                                 }
1024                         }
1025
1026                         if (sense_key == NOT_READY) {
1027                                 /* If Sense is Not Ready, Logical Unit
1028                                  * Not ready, Manual Intervention
1029                                  * required
1030                                  */
1031                                 if ((asc == 0x04) && (ascq == 0x03)) {
1032                                         dev_warn(&h->pdev->dev, "cp %p "
1033                                                 "has check condition: unit "
1034                                                 "not ready, manual "
1035                                                 "intervention required\n", cp);
1036                                         break;
1037                                 }
1038                         }
1039                         if (sense_key == ABORTED_COMMAND) {
1040                                 /* Aborted command is retryable */
1041                                 dev_warn(&h->pdev->dev, "cp %p "
1042                                         "has check condition: aborted command: "
1043                                         "ASC: 0x%x, ASCQ: 0x%x\n",
1044                                         cp, asc, ascq);
1045                                 cmd->result = DID_SOFT_ERROR << 16;
1046                                 break;
1047                         }
1048                         /* Must be some other type of check condition */
1049                         dev_warn(&h->pdev->dev, "cp %p has check condition: "
1050                                         "unknown type: "
1051                                         "Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
1052                                         "Returning result: 0x%x, "
1053                                         "cmd=[%02x %02x %02x %02x %02x "
1054                                         "%02x %02x %02x %02x %02x %02x "
1055                                         "%02x %02x %02x %02x %02x]\n",
1056                                         cp, sense_key, asc, ascq,
1057                                         cmd->result,
1058                                         cmd->cmnd[0], cmd->cmnd[1],
1059                                         cmd->cmnd[2], cmd->cmnd[3],
1060                                         cmd->cmnd[4], cmd->cmnd[5],
1061                                         cmd->cmnd[6], cmd->cmnd[7],
1062                                         cmd->cmnd[8], cmd->cmnd[9],
1063                                         cmd->cmnd[10], cmd->cmnd[11],
1064                                         cmd->cmnd[12], cmd->cmnd[13],
1065                                         cmd->cmnd[14], cmd->cmnd[15]);
1066                         break;
1067                 }
1068
1069
1070                 /* Problem was not a check condition
1071                  * Pass it up to the upper layers...
1072                  */
1073                 if (ei->ScsiStatus) {
1074                         dev_warn(&h->pdev->dev, "cp %p has status 0x%x "
1075                                 "Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
1076                                 "Returning result: 0x%x\n",
1077                                 cp, ei->ScsiStatus,
1078                                 sense_key, asc, ascq,
1079                                 cmd->result);
1080                 } else {  /* scsi status is zero??? How??? */
1081                         dev_warn(&h->pdev->dev, "cp %p SCSI status was 0. "
1082                                 "Returning no connection.\n", cp),
1083
1084                         /* Ordinarily, this case should never happen,
1085                          * but there is a bug in some released firmware
1086                          * revisions that allows it to happen if, for
1087                          * example, a 4100 backplane loses power and
1088                          * the tape drive is in it.  We assume that
1089                          * it's a fatal error of some kind because we
1090                          * can't show that it wasn't. We will make it
1091                          * look like selection timeout since that is
1092                          * the most common reason for this to occur,
1093                          * and it's severe enough.
1094                          */
1095
1096                         cmd->result = DID_NO_CONNECT << 16;
1097                 }
1098                 break;
1099
1100         case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
1101                 break;
1102         case CMD_DATA_OVERRUN:
1103                 dev_warn(&h->pdev->dev, "cp %p has"
1104                         " completed with data overrun "
1105                         "reported\n", cp);
1106                 break;
1107         case CMD_INVALID: {
1108                 /* print_bytes(cp, sizeof(*cp), 1, 0);
1109                 print_cmd(cp); */
1110                 /* We get CMD_INVALID if you address a non-existent device
1111                  * instead of a selection timeout (no response).  You will
1112                  * see this if you yank out a drive, then try to access it.
1113                  * This is kind of a shame because it means that any other
1114                  * CMD_INVALID (e.g. driver bug) will get interpreted as a
1115                  * missing target. */
1116                 cmd->result = DID_NO_CONNECT << 16;
1117         }
1118                 break;
1119         case CMD_PROTOCOL_ERR:
1120                 dev_warn(&h->pdev->dev, "cp %p has "
1121                         "protocol error \n", cp);
1122                 break;
1123         case CMD_HARDWARE_ERR:
1124                 cmd->result = DID_ERROR << 16;
1125                 dev_warn(&h->pdev->dev, "cp %p had  hardware error\n", cp);
1126                 break;
1127         case CMD_CONNECTION_LOST:
1128                 cmd->result = DID_ERROR << 16;
1129                 dev_warn(&h->pdev->dev, "cp %p had connection lost\n", cp);
1130                 break;
1131         case CMD_ABORTED:
1132                 cmd->result = DID_ABORT << 16;
1133                 dev_warn(&h->pdev->dev, "cp %p was aborted with status 0x%x\n",
1134                                 cp, ei->ScsiStatus);
1135                 break;
1136         case CMD_ABORT_FAILED:
1137                 cmd->result = DID_ERROR << 16;
1138                 dev_warn(&h->pdev->dev, "cp %p reports abort failed\n", cp);
1139                 break;
1140         case CMD_UNSOLICITED_ABORT:
1141                 cmd->result = DID_RESET << 16;
1142                 dev_warn(&h->pdev->dev, "cp %p aborted do to an unsolicited "
1143                         "abort\n", cp);
1144                 break;
1145         case CMD_TIMEOUT:
1146                 cmd->result = DID_TIME_OUT << 16;
1147                 dev_warn(&h->pdev->dev, "cp %p timedout\n", cp);
1148                 break;
1149         default:
1150                 cmd->result = DID_ERROR << 16;
1151                 dev_warn(&h->pdev->dev, "cp %p returned unknown status %x\n",
1152                                 cp, ei->CommandStatus);
1153         }
1154         cmd->scsi_done(cmd);
1155         cmd_free(h, cp);
1156 }
1157
1158 static int hpsa_scsi_detect(struct ctlr_info *h)
1159 {
1160         struct Scsi_Host *sh;
1161         int error;
1162
1163         sh = scsi_host_alloc(&hpsa_driver_template, sizeof(h));
1164         if (sh == NULL)
1165                 goto fail;
1166
1167         sh->io_port = 0;
1168         sh->n_io_port = 0;
1169         sh->this_id = -1;
1170         sh->max_channel = 3;
1171         sh->max_cmd_len = MAX_COMMAND_SIZE;
1172         sh->max_lun = HPSA_MAX_LUN;
1173         sh->max_id = HPSA_MAX_LUN;
1174         sh->can_queue = h->nr_cmds;
1175         sh->cmd_per_lun = h->nr_cmds;
1176         sh->sg_tablesize = h->maxsgentries;
1177         h->scsi_host = sh;
1178         sh->hostdata[0] = (unsigned long) h;
1179         sh->irq = h->intr[PERF_MODE_INT];
1180         sh->unique_id = sh->irq;
1181         error = scsi_add_host(sh, &h->pdev->dev);
1182         if (error)
1183                 goto fail_host_put;
1184         scsi_scan_host(sh);
1185         return 0;
1186
1187  fail_host_put:
1188         dev_err(&h->pdev->dev, "hpsa_scsi_detect: scsi_add_host"
1189                 " failed for controller %d\n", h->ctlr);
1190         scsi_host_put(sh);
1191         return error;
1192  fail:
1193         dev_err(&h->pdev->dev, "hpsa_scsi_detect: scsi_host_alloc"
1194                 " failed for controller %d\n", h->ctlr);
1195         return -ENOMEM;
1196 }
1197
1198 static void hpsa_pci_unmap(struct pci_dev *pdev,
1199         struct CommandList *c, int sg_used, int data_direction)
1200 {
1201         int i;
1202         union u64bit addr64;
1203
1204         for (i = 0; i < sg_used; i++) {
1205                 addr64.val32.lower = c->SG[i].Addr.lower;
1206                 addr64.val32.upper = c->SG[i].Addr.upper;
1207                 pci_unmap_single(pdev, (dma_addr_t) addr64.val, c->SG[i].Len,
1208                         data_direction);
1209         }
1210 }
1211
1212 static void hpsa_map_one(struct pci_dev *pdev,
1213                 struct CommandList *cp,
1214                 unsigned char *buf,
1215                 size_t buflen,
1216                 int data_direction)
1217 {
1218         u64 addr64;
1219
1220         if (buflen == 0 || data_direction == PCI_DMA_NONE) {
1221                 cp->Header.SGList = 0;
1222                 cp->Header.SGTotal = 0;
1223                 return;
1224         }
1225
1226         addr64 = (u64) pci_map_single(pdev, buf, buflen, data_direction);
1227         cp->SG[0].Addr.lower =
1228           (u32) (addr64 & (u64) 0x00000000FFFFFFFF);
1229         cp->SG[0].Addr.upper =
1230           (u32) ((addr64 >> 32) & (u64) 0x00000000FFFFFFFF);
1231         cp->SG[0].Len = buflen;
1232         cp->Header.SGList = (u8) 1;   /* no. SGs contig in this cmd */
1233         cp->Header.SGTotal = (u16) 1; /* total sgs in this cmd list */
1234 }
1235
1236 static inline void hpsa_scsi_do_simple_cmd_core(struct ctlr_info *h,
1237         struct CommandList *c)
1238 {
1239         DECLARE_COMPLETION_ONSTACK(wait);
1240
1241         c->waiting = &wait;
1242         enqueue_cmd_and_start_io(h, c);
1243         wait_for_completion(&wait);
1244 }
1245
1246 static void hpsa_scsi_do_simple_cmd_with_retry(struct ctlr_info *h,
1247         struct CommandList *c, int data_direction)
1248 {
1249         int retry_count = 0;
1250
1251         do {
1252                 memset(c->err_info, 0, sizeof(c->err_info));
1253                 hpsa_scsi_do_simple_cmd_core(h, c);
1254                 retry_count++;
1255         } while (check_for_unit_attention(h, c) && retry_count <= 3);
1256         hpsa_pci_unmap(h->pdev, c, 1, data_direction);
1257 }
1258
1259 static void hpsa_scsi_interpret_error(struct CommandList *cp)
1260 {
1261         struct ErrorInfo *ei;
1262         struct device *d = &cp->h->pdev->dev;
1263
1264         ei = cp->err_info;
1265         switch (ei->CommandStatus) {
1266         case CMD_TARGET_STATUS:
1267                 dev_warn(d, "cmd %p has completed with errors\n", cp);
1268                 dev_warn(d, "cmd %p has SCSI Status = %x\n", cp,
1269                                 ei->ScsiStatus);
1270                 if (ei->ScsiStatus == 0)
1271                         dev_warn(d, "SCSI status is abnormally zero.  "
1272                         "(probably indicates selection timeout "
1273                         "reported incorrectly due to a known "
1274                         "firmware bug, circa July, 2001.)\n");
1275                 break;
1276         case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
1277                         dev_info(d, "UNDERRUN\n");
1278                 break;
1279         case CMD_DATA_OVERRUN:
1280                 dev_warn(d, "cp %p has completed with data overrun\n", cp);
1281                 break;
1282         case CMD_INVALID: {
1283                 /* controller unfortunately reports SCSI passthru's
1284                  * to non-existent targets as invalid commands.
1285                  */
1286                 dev_warn(d, "cp %p is reported invalid (probably means "
1287                         "target device no longer present)\n", cp);
1288                 /* print_bytes((unsigned char *) cp, sizeof(*cp), 1, 0);
1289                 print_cmd(cp);  */
1290                 }
1291                 break;
1292         case CMD_PROTOCOL_ERR:
1293                 dev_warn(d, "cp %p has protocol error \n", cp);
1294                 break;
1295         case CMD_HARDWARE_ERR:
1296                 /* cmd->result = DID_ERROR << 16; */
1297                 dev_warn(d, "cp %p had hardware error\n", cp);
1298                 break;
1299         case CMD_CONNECTION_LOST:
1300                 dev_warn(d, "cp %p had connection lost\n", cp);
1301                 break;
1302         case CMD_ABORTED:
1303                 dev_warn(d, "cp %p was aborted\n", cp);
1304                 break;
1305         case CMD_ABORT_FAILED:
1306                 dev_warn(d, "cp %p reports abort failed\n", cp);
1307                 break;
1308         case CMD_UNSOLICITED_ABORT:
1309                 dev_warn(d, "cp %p aborted due to an unsolicited abort\n", cp);
1310                 break;
1311         case CMD_TIMEOUT:
1312                 dev_warn(d, "cp %p timed out\n", cp);
1313                 break;
1314         default:
1315                 dev_warn(d, "cp %p returned unknown status %x\n", cp,
1316                                 ei->CommandStatus);
1317         }
1318 }
1319
1320 static int hpsa_scsi_do_inquiry(struct ctlr_info *h, unsigned char *scsi3addr,
1321                         unsigned char page, unsigned char *buf,
1322                         unsigned char bufsize)
1323 {
1324         int rc = IO_OK;
1325         struct CommandList *c;
1326         struct ErrorInfo *ei;
1327
1328         c = cmd_special_alloc(h);
1329
1330         if (c == NULL) {                        /* trouble... */
1331                 dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
1332                 return -ENOMEM;
1333         }
1334
1335         fill_cmd(c, HPSA_INQUIRY, h, buf, bufsize, page, scsi3addr, TYPE_CMD);
1336         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
1337         ei = c->err_info;
1338         if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
1339                 hpsa_scsi_interpret_error(c);
1340                 rc = -1;
1341         }
1342         cmd_special_free(h, c);
1343         return rc;
1344 }
1345
1346 static int hpsa_send_reset(struct ctlr_info *h, unsigned char *scsi3addr)
1347 {
1348         int rc = IO_OK;
1349         struct CommandList *c;
1350         struct ErrorInfo *ei;
1351
1352         c = cmd_special_alloc(h);
1353
1354         if (c == NULL) {                        /* trouble... */
1355                 dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
1356                 return -ENOMEM;
1357         }
1358
1359         fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0, scsi3addr, TYPE_MSG);
1360         hpsa_scsi_do_simple_cmd_core(h, c);
1361         /* no unmap needed here because no data xfer. */
1362
1363         ei = c->err_info;
1364         if (ei->CommandStatus != 0) {
1365                 hpsa_scsi_interpret_error(c);
1366                 rc = -1;
1367         }
1368         cmd_special_free(h, c);
1369         return rc;
1370 }
1371
1372 static void hpsa_get_raid_level(struct ctlr_info *h,
1373         unsigned char *scsi3addr, unsigned char *raid_level)
1374 {
1375         int rc;
1376         unsigned char *buf;
1377
1378         *raid_level = RAID_UNKNOWN;
1379         buf = kzalloc(64, GFP_KERNEL);
1380         if (!buf)
1381                 return;
1382         rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0xC1, buf, 64);
1383         if (rc == 0)
1384                 *raid_level = buf[8];
1385         if (*raid_level > RAID_UNKNOWN)
1386                 *raid_level = RAID_UNKNOWN;
1387         kfree(buf);
1388         return;
1389 }
1390
1391 /* Get the device id from inquiry page 0x83 */
1392 static int hpsa_get_device_id(struct ctlr_info *h, unsigned char *scsi3addr,
1393         unsigned char *device_id, int buflen)
1394 {
1395         int rc;
1396         unsigned char *buf;
1397
1398         if (buflen > 16)
1399                 buflen = 16;
1400         buf = kzalloc(64, GFP_KERNEL);
1401         if (!buf)
1402                 return -1;
1403         rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0x83, buf, 64);
1404         if (rc == 0)
1405                 memcpy(device_id, &buf[8], buflen);
1406         kfree(buf);
1407         return rc != 0;
1408 }
1409
1410 static int hpsa_scsi_do_report_luns(struct ctlr_info *h, int logical,
1411                 struct ReportLUNdata *buf, int bufsize,
1412                 int extended_response)
1413 {
1414         int rc = IO_OK;
1415         struct CommandList *c;
1416         unsigned char scsi3addr[8];
1417         struct ErrorInfo *ei;
1418
1419         c = cmd_special_alloc(h);
1420         if (c == NULL) {                        /* trouble... */
1421                 dev_err(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
1422                 return -1;
1423         }
1424         /* address the controller */
1425         memset(scsi3addr, 0, sizeof(scsi3addr));
1426         fill_cmd(c, logical ? HPSA_REPORT_LOG : HPSA_REPORT_PHYS, h,
1427                 buf, bufsize, 0, scsi3addr, TYPE_CMD);
1428         if (extended_response)
1429                 c->Request.CDB[1] = extended_response;
1430         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
1431         ei = c->err_info;
1432         if (ei->CommandStatus != 0 &&
1433             ei->CommandStatus != CMD_DATA_UNDERRUN) {
1434                 hpsa_scsi_interpret_error(c);
1435                 rc = -1;
1436         }
1437         cmd_special_free(h, c);
1438         return rc;
1439 }
1440
1441 static inline int hpsa_scsi_do_report_phys_luns(struct ctlr_info *h,
1442                 struct ReportLUNdata *buf,
1443                 int bufsize, int extended_response)
1444 {
1445         return hpsa_scsi_do_report_luns(h, 0, buf, bufsize, extended_response);
1446 }
1447
1448 static inline int hpsa_scsi_do_report_log_luns(struct ctlr_info *h,
1449                 struct ReportLUNdata *buf, int bufsize)
1450 {
1451         return hpsa_scsi_do_report_luns(h, 1, buf, bufsize, 0);
1452 }
1453
1454 static inline void hpsa_set_bus_target_lun(struct hpsa_scsi_dev_t *device,
1455         int bus, int target, int lun)
1456 {
1457         device->bus = bus;
1458         device->target = target;
1459         device->lun = lun;
1460 }
1461
1462 static int hpsa_update_device_info(struct ctlr_info *h,
1463         unsigned char scsi3addr[], struct hpsa_scsi_dev_t *this_device)
1464 {
1465 #define OBDR_TAPE_INQ_SIZE 49
1466         unsigned char *inq_buff;
1467
1468         inq_buff = kzalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
1469         if (!inq_buff)
1470                 goto bail_out;
1471
1472         /* Do an inquiry to the device to see what it is. */
1473         if (hpsa_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
1474                 (unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
1475                 /* Inquiry failed (msg printed already) */
1476                 dev_err(&h->pdev->dev,
1477                         "hpsa_update_device_info: inquiry failed\n");
1478                 goto bail_out;
1479         }
1480
1481         this_device->devtype = (inq_buff[0] & 0x1f);
1482         memcpy(this_device->scsi3addr, scsi3addr, 8);
1483         memcpy(this_device->vendor, &inq_buff[8],
1484                 sizeof(this_device->vendor));
1485         memcpy(this_device->model, &inq_buff[16],
1486                 sizeof(this_device->model));
1487         memcpy(this_device->revision, &inq_buff[32],
1488                 sizeof(this_device->revision));
1489         memset(this_device->device_id, 0,
1490                 sizeof(this_device->device_id));
1491         hpsa_get_device_id(h, scsi3addr, this_device->device_id,
1492                 sizeof(this_device->device_id));
1493
1494         if (this_device->devtype == TYPE_DISK &&
1495                 is_logical_dev_addr_mode(scsi3addr))
1496                 hpsa_get_raid_level(h, scsi3addr, &this_device->raid_level);
1497         else
1498                 this_device->raid_level = RAID_UNKNOWN;
1499
1500         kfree(inq_buff);
1501         return 0;
1502
1503 bail_out:
1504         kfree(inq_buff);
1505         return 1;
1506 }
1507
1508 static unsigned char *msa2xxx_model[] = {
1509         "MSA2012",
1510         "MSA2024",
1511         "MSA2312",
1512         "MSA2324",
1513         NULL,
1514 };
1515
1516 static int is_msa2xxx(struct ctlr_info *h, struct hpsa_scsi_dev_t *device)
1517 {
1518         int i;
1519
1520         for (i = 0; msa2xxx_model[i]; i++)
1521                 if (strncmp(device->model, msa2xxx_model[i],
1522                         strlen(msa2xxx_model[i])) == 0)
1523                         return 1;
1524         return 0;
1525 }
1526
1527 /* Helper function to assign bus, target, lun mapping of devices.
1528  * Puts non-msa2xxx logical volumes on bus 0, msa2xxx logical
1529  * volumes on bus 1, physical devices on bus 2. and the hba on bus 3.
1530  * Logical drive target and lun are assigned at this time, but
1531  * physical device lun and target assignment are deferred (assigned
1532  * in hpsa_find_target_lun, called by hpsa_scsi_add_entry.)
1533  */
1534 static void figure_bus_target_lun(struct ctlr_info *h,
1535         u8 *lunaddrbytes, int *bus, int *target, int *lun,
1536         struct hpsa_scsi_dev_t *device)
1537 {
1538         u32 lunid;
1539
1540         if (is_logical_dev_addr_mode(lunaddrbytes)) {
1541                 /* logical device */
1542                 if (unlikely(is_scsi_rev_5(h))) {
1543                         /* p1210m, logical drives lun assignments
1544                          * match SCSI REPORT LUNS data.
1545                          */
1546                         lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
1547                         *bus = 0;
1548                         *target = 0;
1549                         *lun = (lunid & 0x3fff) + 1;
1550                 } else {
1551                         /* not p1210m... */
1552                         lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
1553                         if (is_msa2xxx(h, device)) {
1554                                 /* msa2xxx way, put logicals on bus 1
1555                                  * and match target/lun numbers box
1556                                  * reports.
1557                                  */
1558                                 *bus = 1;
1559                                 *target = (lunid >> 16) & 0x3fff;
1560                                 *lun = lunid & 0x00ff;
1561                         } else {
1562                                 /* Traditional smart array way. */
1563                                 *bus = 0;
1564                                 *lun = 0;
1565                                 *target = lunid & 0x3fff;
1566                         }
1567                 }
1568         } else {
1569                 /* physical device */
1570                 if (is_hba_lunid(lunaddrbytes))
1571                         if (unlikely(is_scsi_rev_5(h))) {
1572                                 *bus = 0; /* put p1210m ctlr at 0,0,0 */
1573                                 *target = 0;
1574                                 *lun = 0;
1575                                 return;
1576                         } else
1577                                 *bus = 3; /* traditional smartarray */
1578                 else
1579                         *bus = 2; /* physical disk */
1580                 *target = -1;
1581                 *lun = -1; /* we will fill these in later. */
1582         }
1583 }
1584
1585 /*
1586  * If there is no lun 0 on a target, linux won't find any devices.
1587  * For the MSA2xxx boxes, we have to manually detect the enclosure
1588  * which is at lun zero, as CCISS_REPORT_PHYSICAL_LUNS doesn't report
1589  * it for some reason.  *tmpdevice is the target we're adding,
1590  * this_device is a pointer into the current element of currentsd[]
1591  * that we're building up in update_scsi_devices(), below.
1592  * lunzerobits is a bitmap that tracks which targets already have a
1593  * lun 0 assigned.
1594  * Returns 1 if an enclosure was added, 0 if not.
1595  */
1596 static int add_msa2xxx_enclosure_device(struct ctlr_info *h,
1597         struct hpsa_scsi_dev_t *tmpdevice,
1598         struct hpsa_scsi_dev_t *this_device, u8 *lunaddrbytes,
1599         int bus, int target, int lun, unsigned long lunzerobits[],
1600         int *nmsa2xxx_enclosures)
1601 {
1602         unsigned char scsi3addr[8];
1603
1604         if (test_bit(target, lunzerobits))
1605                 return 0; /* There is already a lun 0 on this target. */
1606
1607         if (!is_logical_dev_addr_mode(lunaddrbytes))
1608                 return 0; /* It's the logical targets that may lack lun 0. */
1609
1610         if (!is_msa2xxx(h, tmpdevice))
1611                 return 0; /* It's only the MSA2xxx that have this problem. */
1612
1613         if (lun == 0) /* if lun is 0, then obviously we have a lun 0. */
1614                 return 0;
1615
1616         if (is_hba_lunid(scsi3addr))
1617                 return 0; /* Don't add the RAID controller here. */
1618
1619         if (is_scsi_rev_5(h))
1620                 return 0; /* p1210m doesn't need to do this. */
1621
1622 #define MAX_MSA2XXX_ENCLOSURES 32
1623         if (*nmsa2xxx_enclosures >= MAX_MSA2XXX_ENCLOSURES) {
1624                 dev_warn(&h->pdev->dev, "Maximum number of MSA2XXX "
1625                         "enclosures exceeded.  Check your hardware "
1626                         "configuration.");
1627                 return 0;
1628         }
1629
1630         memset(scsi3addr, 0, 8);
1631         scsi3addr[3] = target;
1632         if (hpsa_update_device_info(h, scsi3addr, this_device))
1633                 return 0;
1634         (*nmsa2xxx_enclosures)++;
1635         hpsa_set_bus_target_lun(this_device, bus, target, 0);
1636         set_bit(target, lunzerobits);
1637         return 1;
1638 }
1639
1640 /*
1641  * Do CISS_REPORT_PHYS and CISS_REPORT_LOG.  Data is returned in physdev,
1642  * logdev.  The number of luns in physdev and logdev are returned in
1643  * *nphysicals and *nlogicals, respectively.
1644  * Returns 0 on success, -1 otherwise.
1645  */
1646 static int hpsa_gather_lun_info(struct ctlr_info *h,
1647         int reportlunsize,
1648         struct ReportLUNdata *physdev, u32 *nphysicals,
1649         struct ReportLUNdata *logdev, u32 *nlogicals)
1650 {
1651         if (hpsa_scsi_do_report_phys_luns(h, physdev, reportlunsize, 0)) {
1652                 dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
1653                 return -1;
1654         }
1655         *nphysicals = be32_to_cpu(*((__be32 *)physdev->LUNListLength)) / 8;
1656         if (*nphysicals > HPSA_MAX_PHYS_LUN) {
1657                 dev_warn(&h->pdev->dev, "maximum physical LUNs (%d) exceeded."
1658                         "  %d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
1659                         *nphysicals - HPSA_MAX_PHYS_LUN);
1660                 *nphysicals = HPSA_MAX_PHYS_LUN;
1661         }
1662         if (hpsa_scsi_do_report_log_luns(h, logdev, reportlunsize)) {
1663                 dev_err(&h->pdev->dev, "report logical LUNs failed.\n");
1664                 return -1;
1665         }
1666         *nlogicals = be32_to_cpu(*((__be32 *) logdev->LUNListLength)) / 8;
1667         /* Reject Logicals in excess of our max capability. */
1668         if (*nlogicals > HPSA_MAX_LUN) {
1669                 dev_warn(&h->pdev->dev,
1670                         "maximum logical LUNs (%d) exceeded.  "
1671                         "%d LUNs ignored.\n", HPSA_MAX_LUN,
1672                         *nlogicals - HPSA_MAX_LUN);
1673                         *nlogicals = HPSA_MAX_LUN;
1674         }
1675         if (*nlogicals + *nphysicals > HPSA_MAX_PHYS_LUN) {
1676                 dev_warn(&h->pdev->dev,
1677                         "maximum logical + physical LUNs (%d) exceeded. "
1678                         "%d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
1679                         *nphysicals + *nlogicals - HPSA_MAX_PHYS_LUN);
1680                 *nlogicals = HPSA_MAX_PHYS_LUN - *nphysicals;
1681         }
1682         return 0;
1683 }
1684
1685 u8 *figure_lunaddrbytes(struct ctlr_info *h, int raid_ctlr_position, int i,
1686         int nphysicals, int nlogicals, struct ReportLUNdata *physdev_list,
1687         struct ReportLUNdata *logdev_list)
1688 {
1689         /* Helper function, figure out where the LUN ID info is coming from
1690          * given index i, lists of physical and logical devices, where in
1691          * the list the raid controller is supposed to appear (first or last)
1692          */
1693
1694         int logicals_start = nphysicals + (raid_ctlr_position == 0);
1695         int last_device = nphysicals + nlogicals + (raid_ctlr_position == 0);
1696
1697         if (i == raid_ctlr_position)
1698                 return RAID_CTLR_LUNID;
1699
1700         if (i < logicals_start)
1701                 return &physdev_list->LUN[i - (raid_ctlr_position == 0)][0];
1702
1703         if (i < last_device)
1704                 return &logdev_list->LUN[i - nphysicals -
1705                         (raid_ctlr_position == 0)][0];
1706         BUG();
1707         return NULL;
1708 }
1709
1710 static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno)
1711 {
1712         /* the idea here is we could get notified
1713          * that some devices have changed, so we do a report
1714          * physical luns and report logical luns cmd, and adjust
1715          * our list of devices accordingly.
1716          *
1717          * The scsi3addr's of devices won't change so long as the
1718          * adapter is not reset.  That means we can rescan and
1719          * tell which devices we already know about, vs. new
1720          * devices, vs.  disappearing devices.
1721          */
1722         struct ReportLUNdata *physdev_list = NULL;
1723         struct ReportLUNdata *logdev_list = NULL;
1724         unsigned char *inq_buff = NULL;
1725         u32 nphysicals = 0;
1726         u32 nlogicals = 0;
1727         u32 ndev_allocated = 0;
1728         struct hpsa_scsi_dev_t **currentsd, *this_device, *tmpdevice;
1729         int ncurrent = 0;
1730         int reportlunsize = sizeof(*physdev_list) + HPSA_MAX_PHYS_LUN * 8;
1731         int i, nmsa2xxx_enclosures, ndevs_to_allocate;
1732         int bus, target, lun;
1733         int raid_ctlr_position;
1734         DECLARE_BITMAP(lunzerobits, HPSA_MAX_TARGETS_PER_CTLR);
1735
1736         currentsd = kzalloc(sizeof(*currentsd) * HPSA_MAX_SCSI_DEVS_PER_HBA,
1737                 GFP_KERNEL);
1738         physdev_list = kzalloc(reportlunsize, GFP_KERNEL);
1739         logdev_list = kzalloc(reportlunsize, GFP_KERNEL);
1740         inq_buff = kmalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
1741         tmpdevice = kzalloc(sizeof(*tmpdevice), GFP_KERNEL);
1742
1743         if (!currentsd || !physdev_list || !logdev_list ||
1744                 !inq_buff || !tmpdevice) {
1745                 dev_err(&h->pdev->dev, "out of memory\n");
1746                 goto out;
1747         }
1748         memset(lunzerobits, 0, sizeof(lunzerobits));
1749
1750         if (hpsa_gather_lun_info(h, reportlunsize, physdev_list, &nphysicals,
1751                         logdev_list, &nlogicals))
1752                 goto out;
1753
1754         /* We might see up to 32 MSA2xxx enclosures, actually 8 of them
1755          * but each of them 4 times through different paths.  The plus 1
1756          * is for the RAID controller.
1757          */
1758         ndevs_to_allocate = nphysicals + nlogicals + MAX_MSA2XXX_ENCLOSURES + 1;
1759
1760         /* Allocate the per device structures */
1761         for (i = 0; i < ndevs_to_allocate; i++) {
1762                 currentsd[i] = kzalloc(sizeof(*currentsd[i]), GFP_KERNEL);
1763                 if (!currentsd[i]) {
1764                         dev_warn(&h->pdev->dev, "out of memory at %s:%d\n",
1765                                 __FILE__, __LINE__);
1766                         goto out;
1767                 }
1768                 ndev_allocated++;
1769         }
1770
1771         if (unlikely(is_scsi_rev_5(h)))
1772                 raid_ctlr_position = 0;
1773         else
1774                 raid_ctlr_position = nphysicals + nlogicals;
1775
1776         /* adjust our table of devices */
1777         nmsa2xxx_enclosures = 0;
1778         for (i = 0; i < nphysicals + nlogicals + 1; i++) {
1779                 u8 *lunaddrbytes;
1780
1781                 /* Figure out where the LUN ID info is coming from */
1782                 lunaddrbytes = figure_lunaddrbytes(h, raid_ctlr_position,
1783                         i, nphysicals, nlogicals, physdev_list, logdev_list);
1784                 /* skip masked physical devices. */
1785                 if (lunaddrbytes[3] & 0xC0 &&
1786                         i < nphysicals + (raid_ctlr_position == 0))
1787                         continue;
1788
1789                 /* Get device type, vendor, model, device id */
1790                 if (hpsa_update_device_info(h, lunaddrbytes, tmpdevice))
1791                         continue; /* skip it if we can't talk to it. */
1792                 figure_bus_target_lun(h, lunaddrbytes, &bus, &target, &lun,
1793                         tmpdevice);
1794                 this_device = currentsd[ncurrent];
1795
1796                 /*
1797                  * For the msa2xxx boxes, we have to insert a LUN 0 which
1798                  * doesn't show up in CCISS_REPORT_PHYSICAL data, but there
1799                  * is nonetheless an enclosure device there.  We have to
1800                  * present that otherwise linux won't find anything if
1801                  * there is no lun 0.
1802                  */
1803                 if (add_msa2xxx_enclosure_device(h, tmpdevice, this_device,
1804                                 lunaddrbytes, bus, target, lun, lunzerobits,
1805                                 &nmsa2xxx_enclosures)) {
1806                         ncurrent++;
1807                         this_device = currentsd[ncurrent];
1808                 }
1809
1810                 *this_device = *tmpdevice;
1811                 hpsa_set_bus_target_lun(this_device, bus, target, lun);
1812
1813                 switch (this_device->devtype) {
1814                 case TYPE_ROM: {
1815                         /* We don't *really* support actual CD-ROM devices,
1816                          * just "One Button Disaster Recovery" tape drive
1817                          * which temporarily pretends to be a CD-ROM drive.
1818                          * So we check that the device is really an OBDR tape
1819                          * device by checking for "$DR-10" in bytes 43-48 of
1820                          * the inquiry data.
1821                          */
1822                                 char obdr_sig[7];
1823 #define OBDR_TAPE_SIG "$DR-10"
1824                                 strncpy(obdr_sig, &inq_buff[43], 6);
1825                                 obdr_sig[6] = '\0';
1826                                 if (strncmp(obdr_sig, OBDR_TAPE_SIG, 6) != 0)
1827                                         /* Not OBDR device, ignore it. */
1828                                         break;
1829                         }
1830                         ncurrent++;
1831                         break;
1832                 case TYPE_DISK:
1833                         if (i < nphysicals)
1834                                 break;
1835                         ncurrent++;
1836                         break;
1837                 case TYPE_TAPE:
1838                 case TYPE_MEDIUM_CHANGER:
1839                         ncurrent++;
1840                         break;
1841                 case TYPE_RAID:
1842                         /* Only present the Smartarray HBA as a RAID controller.
1843                          * If it's a RAID controller other than the HBA itself
1844                          * (an external RAID controller, MSA500 or similar)
1845                          * don't present it.
1846                          */
1847                         if (!is_hba_lunid(lunaddrbytes))
1848                                 break;
1849                         ncurrent++;
1850                         break;
1851                 default:
1852                         break;
1853                 }
1854                 if (ncurrent >= HPSA_MAX_SCSI_DEVS_PER_HBA)
1855                         break;
1856         }
1857         adjust_hpsa_scsi_table(h, hostno, currentsd, ncurrent);
1858 out:
1859         kfree(tmpdevice);
1860         for (i = 0; i < ndev_allocated; i++)
1861                 kfree(currentsd[i]);
1862         kfree(currentsd);
1863         kfree(inq_buff);
1864         kfree(physdev_list);
1865         kfree(logdev_list);
1866 }
1867
1868 /* hpsa_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
1869  * dma mapping  and fills in the scatter gather entries of the
1870  * hpsa command, cp.
1871  */
1872 static int hpsa_scatter_gather(struct ctlr_info *h,
1873                 struct CommandList *cp,
1874                 struct scsi_cmnd *cmd)
1875 {
1876         unsigned int len;
1877         struct scatterlist *sg;
1878         u64 addr64;
1879         int use_sg, i, sg_index, chained;
1880         struct SGDescriptor *curr_sg;
1881
1882         BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
1883
1884         use_sg = scsi_dma_map(cmd);
1885         if (use_sg < 0)
1886                 return use_sg;
1887
1888         if (!use_sg)
1889                 goto sglist_finished;
1890
1891         curr_sg = cp->SG;
1892         chained = 0;
1893         sg_index = 0;
1894         scsi_for_each_sg(cmd, sg, use_sg, i) {
1895                 if (i == h->max_cmd_sg_entries - 1 &&
1896                         use_sg > h->max_cmd_sg_entries) {
1897                         chained = 1;
1898                         curr_sg = h->cmd_sg_list[cp->cmdindex];
1899                         sg_index = 0;
1900                 }
1901                 addr64 = (u64) sg_dma_address(sg);
1902                 len  = sg_dma_len(sg);
1903                 curr_sg->Addr.lower = (u32) (addr64 & 0x0FFFFFFFFULL);
1904                 curr_sg->Addr.upper = (u32) ((addr64 >> 32) & 0x0FFFFFFFFULL);
1905                 curr_sg->Len = len;
1906                 curr_sg->Ext = 0;  /* we are not chaining */
1907                 curr_sg++;
1908         }
1909
1910         if (use_sg + chained > h->maxSG)
1911                 h->maxSG = use_sg + chained;
1912
1913         if (chained) {
1914                 cp->Header.SGList = h->max_cmd_sg_entries;
1915                 cp->Header.SGTotal = (u16) (use_sg + 1);
1916                 hpsa_map_sg_chain_block(h, cp);
1917                 return 0;
1918         }
1919
1920 sglist_finished:
1921
1922         cp->Header.SGList = (u8) use_sg;   /* no. SGs contig in this cmd */
1923         cp->Header.SGTotal = (u16) use_sg; /* total sgs in this cmd list */
1924         return 0;
1925 }
1926
1927
1928 static int hpsa_scsi_queue_command(struct scsi_cmnd *cmd,
1929         void (*done)(struct scsi_cmnd *))
1930 {
1931         struct ctlr_info *h;
1932         struct hpsa_scsi_dev_t *dev;
1933         unsigned char scsi3addr[8];
1934         struct CommandList *c;
1935         unsigned long flags;
1936
1937         /* Get the ptr to our adapter structure out of cmd->host. */
1938         h = sdev_to_hba(cmd->device);
1939         dev = cmd->device->hostdata;
1940         if (!dev) {
1941                 cmd->result = DID_NO_CONNECT << 16;
1942                 done(cmd);
1943                 return 0;
1944         }
1945         memcpy(scsi3addr, dev->scsi3addr, sizeof(scsi3addr));
1946
1947         /* Need a lock as this is being allocated from the pool */
1948         spin_lock_irqsave(&h->lock, flags);
1949         c = cmd_alloc(h);
1950         spin_unlock_irqrestore(&h->lock, flags);
1951         if (c == NULL) {                        /* trouble... */
1952                 dev_err(&h->pdev->dev, "cmd_alloc returned NULL!\n");
1953                 return SCSI_MLQUEUE_HOST_BUSY;
1954         }
1955
1956         /* Fill in the command list header */
1957
1958         cmd->scsi_done = done;    /* save this for use by completion code */
1959
1960         /* save c in case we have to abort it  */
1961         cmd->host_scribble = (unsigned char *) c;
1962
1963         c->cmd_type = CMD_SCSI;
1964         c->scsi_cmd = cmd;
1965         c->Header.ReplyQueue = 0;  /* unused in simple mode */
1966         memcpy(&c->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
1967         c->Header.Tag.lower = (c->cmdindex << DIRECT_LOOKUP_SHIFT);
1968         c->Header.Tag.lower |= DIRECT_LOOKUP_BIT;
1969
1970         /* Fill in the request block... */
1971
1972         c->Request.Timeout = 0;
1973         memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
1974         BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
1975         c->Request.CDBLen = cmd->cmd_len;
1976         memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
1977         c->Request.Type.Type = TYPE_CMD;
1978         c->Request.Type.Attribute = ATTR_SIMPLE;
1979         switch (cmd->sc_data_direction) {
1980         case DMA_TO_DEVICE:
1981                 c->Request.Type.Direction = XFER_WRITE;
1982                 break;
1983         case DMA_FROM_DEVICE:
1984                 c->Request.Type.Direction = XFER_READ;
1985                 break;
1986         case DMA_NONE:
1987                 c->Request.Type.Direction = XFER_NONE;
1988                 break;
1989         case DMA_BIDIRECTIONAL:
1990                 /* This can happen if a buggy application does a scsi passthru
1991                  * and sets both inlen and outlen to non-zero. ( see
1992                  * ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
1993                  */
1994
1995                 c->Request.Type.Direction = XFER_RSVD;
1996                 /* This is technically wrong, and hpsa controllers should
1997                  * reject it with CMD_INVALID, which is the most correct
1998                  * response, but non-fibre backends appear to let it
1999                  * slide by, and give the same results as if this field
2000                  * were set correctly.  Either way is acceptable for
2001                  * our purposes here.
2002                  */
2003
2004                 break;
2005
2006         default:
2007                 dev_err(&h->pdev->dev, "unknown data direction: %d\n",
2008                         cmd->sc_data_direction);
2009                 BUG();
2010                 break;
2011         }
2012
2013         if (hpsa_scatter_gather(h, c, cmd) < 0) { /* Fill SG list */
2014                 cmd_free(h, c);
2015                 return SCSI_MLQUEUE_HOST_BUSY;
2016         }
2017         enqueue_cmd_and_start_io(h, c);
2018         /* the cmd'll come back via intr handler in complete_scsi_command()  */
2019         return 0;
2020 }
2021
2022 static void hpsa_scan_start(struct Scsi_Host *sh)
2023 {
2024         struct ctlr_info *h = shost_to_hba(sh);
2025         unsigned long flags;
2026
2027         /* wait until any scan already in progress is finished. */
2028         while (1) {
2029                 spin_lock_irqsave(&h->scan_lock, flags);
2030                 if (h->scan_finished)
2031                         break;
2032                 spin_unlock_irqrestore(&h->scan_lock, flags);
2033                 wait_event(h->scan_wait_queue, h->scan_finished);
2034                 /* Note: We don't need to worry about a race between this
2035                  * thread and driver unload because the midlayer will
2036                  * have incremented the reference count, so unload won't
2037                  * happen if we're in here.
2038                  */
2039         }
2040         h->scan_finished = 0; /* mark scan as in progress */
2041         spin_unlock_irqrestore(&h->scan_lock, flags);
2042
2043         hpsa_update_scsi_devices(h, h->scsi_host->host_no);
2044
2045         spin_lock_irqsave(&h->scan_lock, flags);
2046         h->scan_finished = 1; /* mark scan as finished. */
2047         wake_up_all(&h->scan_wait_queue);
2048         spin_unlock_irqrestore(&h->scan_lock, flags);
2049 }
2050
2051 static int hpsa_scan_finished(struct Scsi_Host *sh,
2052         unsigned long elapsed_time)
2053 {
2054         struct ctlr_info *h = shost_to_hba(sh);
2055         unsigned long flags;
2056         int finished;
2057
2058         spin_lock_irqsave(&h->scan_lock, flags);
2059         finished = h->scan_finished;
2060         spin_unlock_irqrestore(&h->scan_lock, flags);
2061         return finished;
2062 }
2063
2064 static int hpsa_change_queue_depth(struct scsi_device *sdev,
2065         int qdepth, int reason)
2066 {
2067         struct ctlr_info *h = sdev_to_hba(sdev);
2068
2069         if (reason != SCSI_QDEPTH_DEFAULT)
2070                 return -ENOTSUPP;
2071
2072         if (qdepth < 1)
2073                 qdepth = 1;
2074         else
2075                 if (qdepth > h->nr_cmds)
2076                         qdepth = h->nr_cmds;
2077         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), qdepth);
2078         return sdev->queue_depth;
2079 }
2080
2081 static void hpsa_unregister_scsi(struct ctlr_info *h)
2082 {
2083         /* we are being forcibly unloaded, and may not refuse. */
2084         scsi_remove_host(h->scsi_host);
2085         scsi_host_put(h->scsi_host);
2086         h->scsi_host = NULL;
2087 }
2088
2089 static int hpsa_register_scsi(struct ctlr_info *h)
2090 {
2091         int rc;
2092
2093         rc = hpsa_scsi_detect(h);
2094         if (rc != 0)
2095                 dev_err(&h->pdev->dev, "hpsa_register_scsi: failed"
2096                         " hpsa_scsi_detect(), rc is %d\n", rc);
2097         return rc;
2098 }
2099
2100 static int wait_for_device_to_become_ready(struct ctlr_info *h,
2101         unsigned char lunaddr[])
2102 {
2103         int rc = 0;
2104         int count = 0;
2105         int waittime = 1; /* seconds */
2106         struct CommandList *c;
2107
2108         c = cmd_special_alloc(h);
2109         if (!c) {
2110                 dev_warn(&h->pdev->dev, "out of memory in "
2111                         "wait_for_device_to_become_ready.\n");
2112                 return IO_ERROR;
2113         }
2114
2115         /* Send test unit ready until device ready, or give up. */
2116         while (count < HPSA_TUR_RETRY_LIMIT) {
2117
2118                 /* Wait for a bit.  do this first, because if we send
2119                  * the TUR right away, the reset will just abort it.
2120                  */
2121                 msleep(1000 * waittime);
2122                 count++;
2123
2124                 /* Increase wait time with each try, up to a point. */
2125                 if (waittime < HPSA_MAX_WAIT_INTERVAL_SECS)
2126                         waittime = waittime * 2;
2127
2128                 /* Send the Test Unit Ready */
2129                 fill_cmd(c, TEST_UNIT_READY, h, NULL, 0, 0, lunaddr, TYPE_CMD);
2130                 hpsa_scsi_do_simple_cmd_core(h, c);
2131                 /* no unmap needed here because no data xfer. */
2132
2133                 if (c->err_info->CommandStatus == CMD_SUCCESS)
2134                         break;
2135
2136                 if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
2137                         c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION &&
2138                         (c->err_info->SenseInfo[2] == NO_SENSE ||
2139                         c->err_info->SenseInfo[2] == UNIT_ATTENTION))
2140                         break;
2141
2142                 dev_warn(&h->pdev->dev, "waiting %d secs "
2143                         "for device to become ready.\n", waittime);
2144                 rc = 1; /* device not ready. */
2145         }
2146
2147         if (rc)
2148                 dev_warn(&h->pdev->dev, "giving up on device.\n");
2149         else
2150                 dev_warn(&h->pdev->dev, "device is ready.\n");
2151
2152         cmd_special_free(h, c);
2153         return rc;
2154 }
2155
2156 /* Need at least one of these error handlers to keep ../scsi/hosts.c from
2157  * complaining.  Doing a host- or bus-reset can't do anything good here.
2158  */
2159 static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
2160 {
2161         int rc;
2162         struct ctlr_info *h;
2163         struct hpsa_scsi_dev_t *dev;
2164
2165         /* find the controller to which the command to be aborted was sent */
2166         h = sdev_to_hba(scsicmd->device);
2167         if (h == NULL) /* paranoia */
2168                 return FAILED;
2169         dev = scsicmd->device->hostdata;
2170         if (!dev) {
2171                 dev_err(&h->pdev->dev, "hpsa_eh_device_reset_handler: "
2172                         "device lookup failed.\n");
2173                 return FAILED;
2174         }
2175         dev_warn(&h->pdev->dev, "resetting device %d:%d:%d:%d\n",
2176                 h->scsi_host->host_no, dev->bus, dev->target, dev->lun);
2177         /* send a reset to the SCSI LUN which the command was sent to */
2178         rc = hpsa_send_reset(h, dev->scsi3addr);
2179         if (rc == 0 && wait_for_device_to_become_ready(h, dev->scsi3addr) == 0)
2180                 return SUCCESS;
2181
2182         dev_warn(&h->pdev->dev, "resetting device failed.\n");
2183         return FAILED;
2184 }
2185
2186 /*
2187  * For operations that cannot sleep, a command block is allocated at init,
2188  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
2189  * which ones are free or in use.  Lock must be held when calling this.
2190  * cmd_free() is the complement.
2191  */
2192 static struct CommandList *cmd_alloc(struct ctlr_info *h)
2193 {
2194         struct CommandList *c;
2195         int i;
2196         union u64bit temp64;
2197         dma_addr_t cmd_dma_handle, err_dma_handle;
2198
2199         do {
2200                 i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
2201                 if (i == h->nr_cmds)
2202                         return NULL;
2203         } while (test_and_set_bit
2204                  (i & (BITS_PER_LONG - 1),
2205                   h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
2206         c = h->cmd_pool + i;
2207         memset(c, 0, sizeof(*c));
2208         cmd_dma_handle = h->cmd_pool_dhandle
2209             + i * sizeof(*c);
2210         c->err_info = h->errinfo_pool + i;
2211         memset(c->err_info, 0, sizeof(*c->err_info));
2212         err_dma_handle = h->errinfo_pool_dhandle
2213             + i * sizeof(*c->err_info);
2214         h->nr_allocs++;
2215
2216         c->cmdindex = i;
2217
2218         INIT_HLIST_NODE(&c->list);
2219         c->busaddr = (u32) cmd_dma_handle;
2220         temp64.val = (u64) err_dma_handle;
2221         c->ErrDesc.Addr.lower = temp64.val32.lower;
2222         c->ErrDesc.Addr.upper = temp64.val32.upper;
2223         c->ErrDesc.Len = sizeof(*c->err_info);
2224
2225         c->h = h;
2226         return c;
2227 }
2228
2229 /* For operations that can wait for kmalloc to possibly sleep,
2230  * this routine can be called. Lock need not be held to call
2231  * cmd_special_alloc. cmd_special_free() is the complement.
2232  */
2233 static struct CommandList *cmd_special_alloc(struct ctlr_info *h)
2234 {
2235         struct CommandList *c;
2236         union u64bit temp64;
2237         dma_addr_t cmd_dma_handle, err_dma_handle;
2238
2239         c = pci_alloc_consistent(h->pdev, sizeof(*c), &cmd_dma_handle);
2240         if (c == NULL)
2241                 return NULL;
2242         memset(c, 0, sizeof(*c));
2243
2244         c->cmdindex = -1;
2245
2246         c->err_info = pci_alloc_consistent(h->pdev, sizeof(*c->err_info),
2247                     &err_dma_handle);
2248
2249         if (c->err_info == NULL) {
2250                 pci_free_consistent(h->pdev,
2251                         sizeof(*c), c, cmd_dma_handle);
2252                 return NULL;
2253         }
2254         memset(c->err_info, 0, sizeof(*c->err_info));
2255
2256         INIT_HLIST_NODE(&c->list);
2257         c->busaddr = (u32) cmd_dma_handle;
2258         temp64.val = (u64) err_dma_handle;
2259         c->ErrDesc.Addr.lower = temp64.val32.lower;
2260         c->ErrDesc.Addr.upper = temp64.val32.upper;
2261         c->ErrDesc.Len = sizeof(*c->err_info);
2262
2263         c->h = h;
2264         return c;
2265 }
2266
2267 static void cmd_free(struct ctlr_info *h, struct CommandList *c)
2268 {
2269         int i;
2270
2271         i = c - h->cmd_pool;
2272         clear_bit(i & (BITS_PER_LONG - 1),
2273                   h->cmd_pool_bits + (i / BITS_PER_LONG));
2274         h->nr_frees++;
2275 }
2276
2277 static void cmd_special_free(struct ctlr_info *h, struct CommandList *c)
2278 {
2279         union u64bit temp64;
2280
2281         temp64.val32.lower = c->ErrDesc.Addr.lower;
2282         temp64.val32.upper = c->ErrDesc.Addr.upper;
2283         pci_free_consistent(h->pdev, sizeof(*c->err_info),
2284                             c->err_info, (dma_addr_t) temp64.val);
2285         pci_free_consistent(h->pdev, sizeof(*c),
2286                             c, (dma_addr_t) c->busaddr);
2287 }
2288
2289 #ifdef CONFIG_COMPAT
2290
2291 static int hpsa_ioctl32_passthru(struct scsi_device *dev, int cmd, void *arg)
2292 {
2293         IOCTL32_Command_struct __user *arg32 =
2294             (IOCTL32_Command_struct __user *) arg;
2295         IOCTL_Command_struct arg64;
2296         IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
2297         int err;
2298         u32 cp;
2299
2300         err = 0;
2301         err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
2302                            sizeof(arg64.LUN_info));
2303         err |= copy_from_user(&arg64.Request, &arg32->Request,
2304                            sizeof(arg64.Request));
2305         err |= copy_from_user(&arg64.error_info, &arg32->error_info,
2306                            sizeof(arg64.error_info));
2307         err |= get_user(arg64.buf_size, &arg32->buf_size);
2308         err |= get_user(cp, &arg32->buf);
2309         arg64.buf = compat_ptr(cp);
2310         err |= copy_to_user(p, &arg64, sizeof(arg64));
2311
2312         if (err)
2313                 return -EFAULT;
2314
2315         err = hpsa_ioctl(dev, CCISS_PASSTHRU, (void *)p);
2316         if (err)
2317                 return err;
2318         err |= copy_in_user(&arg32->error_info, &p->error_info,
2319                          sizeof(arg32->error_info));
2320         if (err)
2321                 return -EFAULT;
2322         return err;
2323 }
2324
2325 static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
2326         int cmd, void *arg)
2327 {
2328         BIG_IOCTL32_Command_struct __user *arg32 =
2329             (BIG_IOCTL32_Command_struct __user *) arg;
2330         BIG_IOCTL_Command_struct arg64;
2331         BIG_IOCTL_Command_struct __user *p =
2332             compat_alloc_user_space(sizeof(arg64));
2333         int err;
2334         u32 cp;
2335
2336         err = 0;
2337         err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
2338                            sizeof(arg64.LUN_info));
2339         err |= copy_from_user(&arg64.Request, &arg32->Request,
2340                            sizeof(arg64.Request));
2341         err |= copy_from_user(&arg64.error_info, &arg32->error_info,
2342                            sizeof(arg64.error_info));
2343         err |= get_user(arg64.buf_size, &arg32->buf_size);
2344         err |= get_user(arg64.malloc_size, &arg32->malloc_size);
2345         err |= get_user(cp, &arg32->buf);
2346         arg64.buf = compat_ptr(cp);
2347         err |= copy_to_user(p, &arg64, sizeof(arg64));
2348
2349         if (err)
2350                 return -EFAULT;
2351
2352         err = hpsa_ioctl(dev, CCISS_BIG_PASSTHRU, (void *)p);
2353         if (err)
2354                 return err;
2355         err |= copy_in_user(&arg32->error_info, &p->error_info,
2356                          sizeof(arg32->error_info));
2357         if (err)
2358                 return -EFAULT;
2359         return err;
2360 }
2361
2362 static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg)
2363 {
2364         switch (cmd) {
2365         case CCISS_GETPCIINFO:
2366         case CCISS_GETINTINFO:
2367         case CCISS_SETINTINFO:
2368         case CCISS_GETNODENAME:
2369         case CCISS_SETNODENAME:
2370         case CCISS_GETHEARTBEAT:
2371         case CCISS_GETBUSTYPES:
2372         case CCISS_GETFIRMVER:
2373         case CCISS_GETDRIVVER:
2374         case CCISS_REVALIDVOLS:
2375         case CCISS_DEREGDISK:
2376         case CCISS_REGNEWDISK:
2377         case CCISS_REGNEWD:
2378         case CCISS_RESCANDISK:
2379         case CCISS_GETLUNINFO:
2380                 return hpsa_ioctl(dev, cmd, arg);
2381
2382         case CCISS_PASSTHRU32:
2383                 return hpsa_ioctl32_passthru(dev, cmd, arg);
2384         case CCISS_BIG_PASSTHRU32:
2385                 return hpsa_ioctl32_big_passthru(dev, cmd, arg);
2386
2387         default:
2388                 return -ENOIOCTLCMD;
2389         }
2390 }
2391 #endif
2392
2393 static int hpsa_getpciinfo_ioctl(struct ctlr_info *h, void __user *argp)
2394 {
2395         struct hpsa_pci_info pciinfo;
2396
2397         if (!argp)
2398                 return -EINVAL;
2399         pciinfo.domain = pci_domain_nr(h->pdev->bus);
2400         pciinfo.bus = h->pdev->bus->number;
2401         pciinfo.dev_fn = h->pdev->devfn;
2402         pciinfo.board_id = h->board_id;
2403         if (copy_to_user(argp, &pciinfo, sizeof(pciinfo)))
2404                 return -EFAULT;
2405         return 0;
2406 }
2407
2408 static int hpsa_getdrivver_ioctl(struct ctlr_info *h, void __user *argp)
2409 {
2410         DriverVer_type DriverVer;
2411         unsigned char vmaj, vmin, vsubmin;
2412         int rc;
2413
2414         rc = sscanf(HPSA_DRIVER_VERSION, "%hhu.%hhu.%hhu",
2415                 &vmaj, &vmin, &vsubmin);
2416         if (rc != 3) {
2417                 dev_info(&h->pdev->dev, "driver version string '%s' "
2418                         "unrecognized.", HPSA_DRIVER_VERSION);
2419                 vmaj = 0;
2420                 vmin = 0;
2421                 vsubmin = 0;
2422         }
2423         DriverVer = (vmaj << 16) | (vmin << 8) | vsubmin;
2424         if (!argp)
2425                 return -EINVAL;
2426         if (copy_to_user(argp, &DriverVer, sizeof(DriverVer_type)))
2427                 return -EFAULT;
2428         return 0;
2429 }
2430
2431 static int hpsa_passthru_ioctl(struct ctlr_info *h, void __user *argp)
2432 {
2433         IOCTL_Command_struct iocommand;
2434         struct CommandList *c;
2435         char *buff = NULL;
2436         union u64bit temp64;
2437
2438         if (!argp)
2439                 return -EINVAL;
2440         if (!capable(CAP_SYS_RAWIO))
2441                 return -EPERM;
2442         if (copy_from_user(&iocommand, argp, sizeof(iocommand)))
2443                 return -EFAULT;
2444         if ((iocommand.buf_size < 1) &&
2445             (iocommand.Request.Type.Direction != XFER_NONE)) {
2446                 return -EINVAL;
2447         }
2448         if (iocommand.buf_size > 0) {
2449                 buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
2450                 if (buff == NULL)
2451                         return -EFAULT;
2452         }
2453         if (iocommand.Request.Type.Direction == XFER_WRITE) {
2454                 /* Copy the data into the buffer we created */
2455                 if (copy_from_user(buff, iocommand.buf, iocommand.buf_size)) {
2456                         kfree(buff);
2457                         return -EFAULT;
2458                 }
2459         } else
2460                 memset(buff, 0, iocommand.buf_size);
2461         c = cmd_special_alloc(h);
2462         if (c == NULL) {
2463                 kfree(buff);
2464                 return -ENOMEM;
2465         }
2466         /* Fill in the command type */
2467         c->cmd_type = CMD_IOCTL_PEND;
2468         /* Fill in Command Header */
2469         c->Header.ReplyQueue = 0; /* unused in simple mode */
2470         if (iocommand.buf_size > 0) {   /* buffer to fill */
2471                 c->Header.SGList = 1;
2472                 c->Header.SGTotal = 1;
2473         } else  { /* no buffers to fill */
2474                 c->Header.SGList = 0;
2475                 c->Header.SGTotal = 0;
2476         }
2477         memcpy(&c->Header.LUN, &iocommand.LUN_info, sizeof(c->Header.LUN));
2478         /* use the kernel address the cmd block for tag */
2479         c->Header.Tag.lower = c->busaddr;
2480
2481         /* Fill in Request block */
2482         memcpy(&c->Request, &iocommand.Request,
2483                 sizeof(c->Request));
2484
2485         /* Fill in the scatter gather information */
2486         if (iocommand.buf_size > 0) {
2487                 temp64.val = pci_map_single(h->pdev, buff,
2488                         iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
2489                 c->SG[0].Addr.lower = temp64.val32.lower;
2490                 c->SG[0].Addr.upper = temp64.val32.upper;
2491                 c->SG[0].Len = iocommand.buf_size;
2492                 c->SG[0].Ext = 0; /* we are not chaining*/
2493         }
2494         hpsa_scsi_do_simple_cmd_core(h, c);
2495         hpsa_pci_unmap(h->pdev, c, 1, PCI_DMA_BIDIRECTIONAL);
2496         check_ioctl_unit_attention(h, c);
2497
2498         /* Copy the error information out */
2499         memcpy(&iocommand.error_info, c->err_info,
2500                 sizeof(iocommand.error_info));
2501         if (copy_to_user(argp, &iocommand, sizeof(iocommand))) {
2502                 kfree(buff);
2503                 cmd_special_free(h, c);
2504                 return -EFAULT;
2505         }
2506
2507         if (iocommand.Request.Type.Direction == XFER_READ) {
2508                 /* Copy the data out of the buffer we created */
2509                 if (copy_to_user(iocommand.buf, buff, iocommand.buf_size)) {
2510                         kfree(buff);
2511                         cmd_special_free(h, c);
2512                         return -EFAULT;
2513                 }
2514         }
2515         kfree(buff);
2516         cmd_special_free(h, c);
2517         return 0;
2518 }
2519
2520 static int hpsa_big_passthru_ioctl(struct ctlr_info *h, void __user *argp)
2521 {
2522         BIG_IOCTL_Command_struct *ioc;
2523         struct CommandList *c;
2524         unsigned char **buff = NULL;
2525         int *buff_size = NULL;
2526         union u64bit temp64;
2527         BYTE sg_used = 0;
2528         int status = 0;
2529         int i;
2530         u32 left;
2531         u32 sz;
2532         BYTE __user *data_ptr;
2533
2534         if (!argp)
2535                 return -EINVAL;
2536         if (!capable(CAP_SYS_RAWIO))
2537                 return -EPERM;
2538         ioc = (BIG_IOCTL_Command_struct *)
2539             kmalloc(sizeof(*ioc), GFP_KERNEL);
2540         if (!ioc) {
2541                 status = -ENOMEM;
2542                 goto cleanup1;
2543         }
2544         if (copy_from_user(ioc, argp, sizeof(*ioc))) {
2545                 status = -EFAULT;
2546                 goto cleanup1;
2547         }
2548         if ((ioc->buf_size < 1) &&
2549             (ioc->Request.Type.Direction != XFER_NONE)) {
2550                 status = -EINVAL;
2551                 goto cleanup1;
2552         }
2553         /* Check kmalloc limits  using all SGs */
2554         if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
2555                 status = -EINVAL;
2556                 goto cleanup1;
2557         }
2558         if (ioc->buf_size > ioc->malloc_size * MAXSGENTRIES) {
2559                 status = -EINVAL;
2560                 goto cleanup1;
2561         }
2562         buff = kzalloc(MAXSGENTRIES * sizeof(char *), GFP_KERNEL);
2563         if (!buff) {
2564                 status = -ENOMEM;
2565                 goto cleanup1;
2566         }
2567         buff_size = kmalloc(MAXSGENTRIES * sizeof(int), GFP_KERNEL);
2568         if (!buff_size) {
2569                 status = -ENOMEM;
2570                 goto cleanup1;
2571         }
2572         left = ioc->buf_size;
2573         data_ptr = ioc->buf;
2574         while (left) {
2575                 sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
2576                 buff_size[sg_used] = sz;
2577                 buff[sg_used] = kmalloc(sz, GFP_KERNEL);
2578                 if (buff[sg_used] == NULL) {
2579                         status = -ENOMEM;
2580                         goto cleanup1;
2581                 }
2582                 if (ioc->Request.Type.Direction == XFER_WRITE) {
2583                         if (copy_from_user(buff[sg_used], data_ptr, sz)) {
2584                                 status = -ENOMEM;
2585                                 goto cleanup1;
2586                         }
2587                 } else
2588                         memset(buff[sg_used], 0, sz);
2589                 left -= sz;
2590                 data_ptr += sz;
2591                 sg_used++;
2592         }
2593         c = cmd_special_alloc(h);
2594         if (c == NULL) {
2595                 status = -ENOMEM;
2596                 goto cleanup1;
2597         }
2598         c->cmd_type = CMD_IOCTL_PEND;
2599         c->Header.ReplyQueue = 0;
2600
2601         if (ioc->buf_size > 0) {
2602                 c->Header.SGList = sg_used;
2603                 c->Header.SGTotal = sg_used;
2604         } else {
2605                 c->Header.SGList = 0;
2606                 c->Header.SGTotal = 0;
2607         }
2608         memcpy(&c->Header.LUN, &ioc->LUN_info, sizeof(c->Header.LUN));
2609         c->Header.Tag.lower = c->busaddr;
2610         memcpy(&c->Request, &ioc->Request, sizeof(c->Request));
2611         if (ioc->buf_size > 0) {
2612                 int i;
2613                 for (i = 0; i < sg_used; i++) {
2614                         temp64.val = pci_map_single(h->pdev, buff[i],
2615                                     buff_size[i], PCI_DMA_BIDIRECTIONAL);
2616                         c->SG[i].Addr.lower = temp64.val32.lower;
2617                         c->SG[i].Addr.upper = temp64.val32.upper;
2618                         c->SG[i].Len = buff_size[i];
2619                         /* we are not chaining */
2620                         c->SG[i].Ext = 0;
2621                 }
2622         }
2623         hpsa_scsi_do_simple_cmd_core(h, c);
2624         hpsa_pci_unmap(h->pdev, c, sg_used, PCI_DMA_BIDIRECTIONAL);
2625         check_ioctl_unit_attention(h, c);
2626         /* Copy the error information out */
2627         memcpy(&ioc->error_info, c->err_info, sizeof(ioc->error_info));
2628         if (copy_to_user(argp, ioc, sizeof(*ioc))) {
2629                 cmd_special_free(h, c);
2630                 status = -EFAULT;
2631                 goto cleanup1;
2632         }
2633         if (ioc->Request.Type.Direction == XFER_READ) {
2634                 /* Copy the data out of the buffer we created */
2635                 BYTE __user *ptr = ioc->buf;
2636                 for (i = 0; i < sg_used; i++) {
2637                         if (copy_to_user(ptr, buff[i], buff_size[i])) {
2638                                 cmd_special_free(h, c);
2639                                 status = -EFAULT;
2640                                 goto cleanup1;
2641                         }
2642                         ptr += buff_size[i];
2643                 }
2644         }
2645         cmd_special_free(h, c);
2646         status = 0;
2647 cleanup1:
2648         if (buff) {
2649                 for (i = 0; i < sg_used; i++)
2650                         kfree(buff[i]);
2651                 kfree(buff);
2652         }
2653         kfree(buff_size);
2654         kfree(ioc);
2655         return status;
2656 }
2657
2658 static void check_ioctl_unit_attention(struct ctlr_info *h,
2659         struct CommandList *c)
2660 {
2661         if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
2662                         c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
2663                 (void) check_for_unit_attention(h, c);
2664 }
2665 /*
2666  * ioctl
2667  */
2668 static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg)
2669 {
2670         struct ctlr_info *h;
2671         void __user *argp = (void __user *)arg;
2672
2673         h = sdev_to_hba(dev);
2674
2675         switch (cmd) {
2676         case CCISS_DEREGDISK:
2677         case CCISS_REGNEWDISK:
2678         case CCISS_REGNEWD:
2679                 hpsa_scan_start(h->scsi_host);
2680                 return 0;
2681         case CCISS_GETPCIINFO:
2682                 return hpsa_getpciinfo_ioctl(h, argp);
2683         case CCISS_GETDRIVVER:
2684                 return hpsa_getdrivver_ioctl(h, argp);
2685         case CCISS_PASSTHRU:
2686                 return hpsa_passthru_ioctl(h, argp);
2687         case CCISS_BIG_PASSTHRU:
2688                 return hpsa_big_passthru_ioctl(h, argp);
2689         default:
2690                 return -ENOTTY;
2691         }
2692 }
2693
2694 static void fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
2695         void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
2696         int cmd_type)
2697 {
2698         int pci_dir = XFER_NONE;
2699
2700         c->cmd_type = CMD_IOCTL_PEND;
2701         c->Header.ReplyQueue = 0;
2702         if (buff != NULL && size > 0) {
2703                 c->Header.SGList = 1;
2704                 c->Header.SGTotal = 1;
2705         } else {
2706                 c->Header.SGList = 0;
2707                 c->Header.SGTotal = 0;
2708         }
2709         c->Header.Tag.lower = c->busaddr;
2710         memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
2711
2712         c->Request.Type.Type = cmd_type;
2713         if (cmd_type == TYPE_CMD) {
2714                 switch (cmd) {
2715                 case HPSA_INQUIRY:
2716                         /* are we trying to read a vital product page */
2717                         if (page_code != 0) {
2718                                 c->Request.CDB[1] = 0x01;
2719                                 c->Request.CDB[2] = page_code;
2720                         }
2721                         c->Request.CDBLen = 6;
2722                         c->Request.Type.Attribute = ATTR_SIMPLE;
2723                         c->Request.Type.Direction = XFER_READ;
2724                         c->Request.Timeout = 0;
2725                         c->Request.CDB[0] = HPSA_INQUIRY;
2726                         c->Request.CDB[4] = size & 0xFF;
2727                         break;
2728                 case HPSA_REPORT_LOG:
2729                 case HPSA_REPORT_PHYS:
2730                         /* Talking to controller so It's a physical command
2731                            mode = 00 target = 0.  Nothing to write.
2732                          */
2733                         c->Request.CDBLen = 12;
2734                         c->Request.Type.Attribute = ATTR_SIMPLE;
2735                         c->Request.Type.Direction = XFER_READ;
2736                         c->Request.Timeout = 0;
2737                         c->Request.CDB[0] = cmd;
2738                         c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
2739                         c->Request.CDB[7] = (size >> 16) & 0xFF;
2740                         c->Request.CDB[8] = (size >> 8) & 0xFF;
2741                         c->Request.CDB[9] = size & 0xFF;
2742                         break;
2743                 case HPSA_CACHE_FLUSH:
2744                         c->Request.CDBLen = 12;
2745                         c->Request.Type.Attribute = ATTR_SIMPLE;
2746                         c->Request.Type.Direction = XFER_WRITE;
2747                         c->Request.Timeout = 0;
2748                         c->Request.CDB[0] = BMIC_WRITE;
2749                         c->Request.CDB[6] = BMIC_CACHE_FLUSH;
2750                         break;
2751                 case TEST_UNIT_READY:
2752                         c->Request.CDBLen = 6;
2753                         c->Request.Type.Attribute = ATTR_SIMPLE;
2754                         c->Request.Type.Direction = XFER_NONE;
2755                         c->Request.Timeout = 0;
2756                         break;
2757                 default:
2758                         dev_warn(&h->pdev->dev, "unknown command 0x%c\n", cmd);
2759                         BUG();
2760                         return;
2761                 }
2762         } else if (cmd_type == TYPE_MSG) {
2763                 switch (cmd) {
2764
2765                 case  HPSA_DEVICE_RESET_MSG:
2766                         c->Request.CDBLen = 16;
2767                         c->Request.Type.Type =  1; /* It is a MSG not a CMD */
2768                         c->Request.Type.Attribute = ATTR_SIMPLE;
2769                         c->Request.Type.Direction = XFER_NONE;
2770                         c->Request.Timeout = 0; /* Don't time out */
2771                         c->Request.CDB[0] =  0x01; /* RESET_MSG is 0x01 */
2772                         c->Request.CDB[1] = 0x03;  /* Reset target above */
2773                         /* If bytes 4-7 are zero, it means reset the */
2774                         /* LunID device */
2775                         c->Request.CDB[4] = 0x00;
2776                         c->Request.CDB[5] = 0x00;
2777                         c->Request.CDB[6] = 0x00;
2778                         c->Request.CDB[7] = 0x00;
2779                 break;
2780
2781                 default:
2782                         dev_warn(&h->pdev->dev, "unknown message type %d\n",
2783                                 cmd);
2784                         BUG();
2785                 }
2786         } else {
2787                 dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
2788                 BUG();
2789         }
2790
2791         switch (c->Request.Type.Direction) {
2792         case XFER_READ:
2793                 pci_dir = PCI_DMA_FROMDEVICE;
2794                 break;
2795         case XFER_WRITE:
2796                 pci_dir = PCI_DMA_TODEVICE;
2797                 break;
2798         case XFER_NONE:
2799                 pci_dir = PCI_DMA_NONE;
2800                 break;
2801         default:
2802                 pci_dir = PCI_DMA_BIDIRECTIONAL;
2803         }
2804
2805         hpsa_map_one(h->pdev, c, buff, size, pci_dir);
2806
2807         return;
2808 }
2809
2810 /*
2811  * Map (physical) PCI mem into (virtual) kernel space
2812  */
2813 static void __iomem *remap_pci_mem(ulong base, ulong size)
2814 {
2815         ulong page_base = ((ulong) base) & PAGE_MASK;
2816         ulong page_offs = ((ulong) base) - page_base;
2817         void __iomem *page_remapped = ioremap(page_base, page_offs + size);
2818
2819         return page_remapped ? (page_remapped + page_offs) : NULL;
2820 }
2821
2822 /* Takes cmds off the submission queue and sends them to the hardware,
2823  * then puts them on the queue of cmds waiting for completion.
2824  */
2825 static void start_io(struct ctlr_info *h)
2826 {
2827         struct CommandList *c;
2828
2829         while (!hlist_empty(&h->reqQ)) {
2830                 c = hlist_entry(h->reqQ.first, struct CommandList, list);
2831                 /* can't do anything if fifo is full */
2832                 if ((h->access.fifo_full(h))) {
2833                         dev_warn(&h->pdev->dev, "fifo full\n");
2834                         break;
2835                 }
2836
2837                 /* Get the first entry from the Request Q */
2838                 removeQ(c);
2839                 h->Qdepth--;
2840
2841                 /* Tell the controller execute command */
2842                 h->access.submit_command(h, c);
2843
2844                 /* Put job onto the completed Q */
2845                 addQ(&h->cmpQ, c);
2846         }
2847 }
2848
2849 static inline unsigned long get_next_completion(struct ctlr_info *h)
2850 {
2851         return h->access.command_completed(h);
2852 }
2853
2854 static inline bool interrupt_pending(struct ctlr_info *h)
2855 {
2856         return h->access.intr_pending(h);
2857 }
2858
2859 static inline long interrupt_not_for_us(struct ctlr_info *h)
2860 {
2861         return !(h->msi_vector || h->msix_vector) &&
2862                 ((h->access.intr_pending(h) == 0) ||
2863                 (h->interrupts_enabled == 0));
2864 }
2865
2866 static inline int bad_tag(struct ctlr_info *h, u32 tag_index,
2867         u32 raw_tag)
2868 {
2869         if (unlikely(tag_index >= h->nr_cmds)) {
2870                 dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
2871                 return 1;
2872         }
2873         return 0;
2874 }
2875
2876 static inline void finish_cmd(struct CommandList *c, u32 raw_tag)
2877 {
2878         removeQ(c);
2879         if (likely(c->cmd_type == CMD_SCSI))
2880                 complete_scsi_command(c, 0, raw_tag);
2881         else if (c->cmd_type == CMD_IOCTL_PEND)
2882                 complete(c->waiting);
2883 }
2884
2885 static inline u32 hpsa_tag_contains_index(u32 tag)
2886 {
2887 #define DIRECT_LOOKUP_BIT 0x10
2888         return tag & DIRECT_LOOKUP_BIT;
2889 }
2890
2891 static inline u32 hpsa_tag_to_index(u32 tag)
2892 {
2893 #define DIRECT_LOOKUP_SHIFT 5
2894         return tag >> DIRECT_LOOKUP_SHIFT;
2895 }
2896
2897 static inline u32 hpsa_tag_discard_error_bits(u32 tag)
2898 {
2899 #define HPSA_ERROR_BITS 0x03
2900         return tag & ~HPSA_ERROR_BITS;
2901 }
2902
2903 /* process completion of an indexed ("direct lookup") command */
2904 static inline u32 process_indexed_cmd(struct ctlr_info *h,
2905         u32 raw_tag)
2906 {
2907         u32 tag_index;
2908         struct CommandList *c;
2909
2910         tag_index = hpsa_tag_to_index(raw_tag);
2911         if (bad_tag(h, tag_index, raw_tag))
2912                 return next_command(h);
2913         c = h->cmd_pool + tag_index;
2914         finish_cmd(c, raw_tag);
2915         return next_command(h);
2916 }
2917
2918 /* process completion of a non-indexed command */
2919 static inline u32 process_nonindexed_cmd(struct ctlr_info *h,
2920         u32 raw_tag)
2921 {
2922         u32 tag;
2923         struct CommandList *c = NULL;
2924         struct hlist_node *tmp;
2925
2926         tag = hpsa_tag_discard_error_bits(raw_tag);
2927         hlist_for_each_entry(c, tmp, &h->cmpQ, list) {
2928                 if ((c->busaddr & 0xFFFFFFE0) == (tag & 0xFFFFFFE0)) {
2929                         finish_cmd(c, raw_tag);
2930                         return next_command(h);
2931                 }
2932         }
2933         bad_tag(h, h->nr_cmds + 1, raw_tag);
2934         return next_command(h);
2935 }
2936
2937 static irqreturn_t do_hpsa_intr(int irq, void *dev_id)
2938 {
2939         struct ctlr_info *h = dev_id;
2940         unsigned long flags;
2941         u32 raw_tag;
2942
2943         if (interrupt_not_for_us(h))
2944                 return IRQ_NONE;
2945         spin_lock_irqsave(&h->lock, flags);
2946         raw_tag = get_next_completion(h);
2947         while (raw_tag != FIFO_EMPTY) {
2948                 if (hpsa_tag_contains_index(raw_tag))
2949                         raw_tag = process_indexed_cmd(h, raw_tag);
2950                 else
2951                         raw_tag = process_nonindexed_cmd(h, raw_tag);
2952         }
2953         spin_unlock_irqrestore(&h->lock, flags);
2954         return IRQ_HANDLED;
2955 }
2956
2957 /* Send a message CDB to the firmware. */
2958 static __devinit int hpsa_message(struct pci_dev *pdev, unsigned char opcode,
2959                                                 unsigned char type)
2960 {
2961         struct Command {
2962                 struct CommandListHeader CommandHeader;
2963                 struct RequestBlock Request;
2964                 struct ErrDescriptor ErrorDescriptor;
2965         };
2966         struct Command *cmd;
2967         static const size_t cmd_sz = sizeof(*cmd) +
2968                                         sizeof(cmd->ErrorDescriptor);
2969         dma_addr_t paddr64;
2970         uint32_t paddr32, tag;
2971         void __iomem *vaddr;
2972         int i, err;
2973
2974         vaddr = pci_ioremap_bar(pdev, 0);
2975         if (vaddr == NULL)
2976                 return -ENOMEM;
2977
2978         /* The Inbound Post Queue only accepts 32-bit physical addresses for the
2979          * CCISS commands, so they must be allocated from the lower 4GiB of
2980          * memory.
2981          */
2982         err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
2983         if (err) {
2984                 iounmap(vaddr);
2985                 return -ENOMEM;
2986         }
2987
2988         cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
2989         if (cmd == NULL) {
2990                 iounmap(vaddr);
2991                 return -ENOMEM;
2992         }
2993
2994         /* This must fit, because of the 32-bit consistent DMA mask.  Also,
2995          * although there's no guarantee, we assume that the address is at
2996          * least 4-byte aligned (most likely, it's page-aligned).
2997          */
2998         paddr32 = paddr64;
2999
3000         cmd->CommandHeader.ReplyQueue = 0;
3001         cmd->CommandHeader.SGList = 0;
3002         cmd->CommandHeader.SGTotal = 0;
3003         cmd->CommandHeader.Tag.lower = paddr32;
3004         cmd->CommandHeader.Tag.upper = 0;
3005         memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
3006
3007         cmd->Request.CDBLen = 16;
3008         cmd->Request.Type.Type = TYPE_MSG;
3009         cmd->Request.Type.Attribute = ATTR_HEADOFQUEUE;
3010         cmd->Request.Type.Direction = XFER_NONE;
3011         cmd->Request.Timeout = 0; /* Don't time out */
3012         cmd->Request.CDB[0] = opcode;
3013         cmd->Request.CDB[1] = type;
3014         memset(&cmd->Request.CDB[2], 0, 14); /* rest of the CDB is reserved */
3015         cmd->ErrorDescriptor.Addr.lower = paddr32 + sizeof(*cmd);
3016         cmd->ErrorDescriptor.Addr.upper = 0;
3017         cmd->ErrorDescriptor.Len = sizeof(struct ErrorInfo);
3018
3019         writel(paddr32, vaddr + SA5_REQUEST_PORT_OFFSET);
3020
3021         for (i = 0; i < HPSA_MSG_SEND_RETRY_LIMIT; i++) {
3022                 tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
3023                 if (hpsa_tag_discard_error_bits(tag) == paddr32)
3024                         break;
3025                 msleep(HPSA_MSG_SEND_RETRY_INTERVAL_MSECS);
3026         }
3027
3028         iounmap(vaddr);
3029
3030         /* we leak the DMA buffer here ... no choice since the controller could
3031          *  still complete the command.
3032          */
3033         if (i == HPSA_MSG_SEND_RETRY_LIMIT) {
3034                 dev_err(&pdev->dev, "controller message %02x:%02x timed out\n",
3035                         opcode, type);
3036                 return -ETIMEDOUT;
3037         }
3038
3039         pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
3040
3041         if (tag & HPSA_ERROR_BIT) {
3042                 dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
3043                         opcode, type);
3044                 return -EIO;
3045         }
3046
3047         dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
3048                 opcode, type);
3049         return 0;
3050 }
3051
3052 #define hpsa_soft_reset_controller(p) hpsa_message(p, 1, 0)
3053 #define hpsa_noop(p) hpsa_message(p, 3, 0)
3054
3055 static __devinit int hpsa_reset_msi(struct pci_dev *pdev)
3056 {
3057 /* the #defines are stolen from drivers/pci/msi.h. */
3058 #define msi_control_reg(base)           (base + PCI_MSI_FLAGS)
3059 #define PCI_MSIX_FLAGS_ENABLE           (1 << 15)
3060
3061         int pos;
3062         u16 control = 0;
3063
3064         pos = pci_find_capability(pdev, PCI_CAP_ID_MSI);
3065         if (pos) {
3066                 pci_read_config_word(pdev, msi_control_reg(pos), &control);
3067                 if (control & PCI_MSI_FLAGS_ENABLE) {
3068                         dev_info(&pdev->dev, "resetting MSI\n");
3069                         pci_write_config_word(pdev, msi_control_reg(pos),
3070                                         control & ~PCI_MSI_FLAGS_ENABLE);
3071                 }
3072         }
3073
3074         pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
3075         if (pos) {
3076                 pci_read_config_word(pdev, msi_control_reg(pos), &control);
3077                 if (control & PCI_MSIX_FLAGS_ENABLE) {
3078                         dev_info(&pdev->dev, "resetting MSI-X\n");
3079                         pci_write_config_word(pdev, msi_control_reg(pos),
3080                                         control & ~PCI_MSIX_FLAGS_ENABLE);
3081                 }
3082         }
3083
3084         return 0;
3085 }
3086
3087 static int hpsa_controller_hard_reset(struct pci_dev *pdev,
3088         void * __iomem vaddr, bool use_doorbell)
3089 {
3090         u16 pmcsr;
3091         int pos;
3092
3093         if (use_doorbell) {
3094                 /* For everything after the P600, the PCI power state method
3095                  * of resetting the controller doesn't work, so we have this
3096                  * other way using the doorbell register.
3097                  */
3098                 dev_info(&pdev->dev, "using doorbell to reset controller\n");
3099                 writel(DOORBELL_CTLR_RESET, vaddr + SA5_DOORBELL);
3100                 msleep(1000);
3101         } else { /* Try to do it the PCI power state way */
3102
3103                 /* Quoting from the Open CISS Specification: "The Power
3104                  * Management Control/Status Register (CSR) controls the power
3105                  * state of the device.  The normal operating state is D0,
3106                  * CSR=00h.  The software off state is D3, CSR=03h.  To reset
3107                  * the controller, place the interface device in D3 then to D0,
3108                  * this causes a secondary PCI reset which will reset the
3109                  * controller." */
3110
3111                 pos = pci_find_capability(pdev, PCI_CAP_ID_PM);
3112                 if (pos == 0) {
3113                         dev_err(&pdev->dev,
3114                                 "hpsa_reset_controller: "
3115                                 "PCI PM not supported\n");
3116                         return -ENODEV;
3117                 }
3118                 dev_info(&pdev->dev, "using PCI PM to reset controller\n");
3119                 /* enter the D3hot power management state */
3120                 pci_read_config_word(pdev, pos + PCI_PM_CTRL, &pmcsr);
3121                 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
3122                 pmcsr |= PCI_D3hot;
3123                 pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
3124
3125                 msleep(500);
3126
3127                 /* enter the D0 power management state */
3128                 pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
3129                 pmcsr |= PCI_D0;
3130                 pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
3131
3132                 msleep(500);
3133         }
3134         return 0;
3135 }
3136
3137 /* This does a hard reset of the controller using PCI power management
3138  * states or the using the doorbell register.
3139  */
3140 static __devinit int hpsa_kdump_hard_reset_controller(struct pci_dev *pdev)
3141 {
3142         u16 saved_config_space[32];
3143         u64 cfg_offset;
3144         u32 cfg_base_addr;
3145         u64 cfg_base_addr_index;
3146         void __iomem *vaddr;
3147         unsigned long paddr;
3148         u32 misc_fw_support, active_transport;
3149         int rc, i;
3150         struct CfgTable __iomem *cfgtable;
3151         bool use_doorbell;
3152         u32 board_id;
3153
3154         /* For controllers as old as the P600, this is very nearly
3155          * the same thing as
3156          *
3157          * pci_save_state(pci_dev);
3158          * pci_set_power_state(pci_dev, PCI_D3hot);
3159          * pci_set_power_state(pci_dev, PCI_D0);
3160          * pci_restore_state(pci_dev);
3161          *
3162          * but we can't use these nice canned kernel routines on
3163          * kexec, because they also check the MSI/MSI-X state in PCI
3164          * configuration space and do the wrong thing when it is
3165          * set/cleared.  Also, the pci_save/restore_state functions
3166          * violate the ordering requirements for restoring the
3167          * configuration space from the CCISS document (see the
3168          * comment below).  So we roll our own ....
3169          *
3170          * For controllers newer than the P600, the pci power state
3171          * method of resetting doesn't work so we have another way
3172          * using the doorbell register.
3173          */
3174
3175         /* Exclude 640x boards.  These are two pci devices in one slot
3176          * which share a battery backed cache module.  One controls the
3177          * cache, the other accesses the cache through the one that controls
3178          * it.  If we reset the one controlling the cache, the other will
3179          * likely not be happy.  Just forbid resetting this conjoined mess.
3180          * The 640x isn't really supported by hpsa anyway.
3181          */
3182         hpsa_lookup_board_id(pdev, &board_id);
3183         if (board_id == 0x409C0E11 || board_id == 0x409D0E11)
3184                 return -ENOTSUPP;
3185
3186         for (i = 0; i < 32; i++)
3187                 pci_read_config_word(pdev, 2*i, &saved_config_space[i]);
3188
3189
3190         /* find the first memory BAR, so we can find the cfg table */
3191         rc = hpsa_pci_find_memory_BAR(pdev, &paddr);
3192         if (rc)
3193                 return rc;
3194         vaddr = remap_pci_mem(paddr, 0x250);
3195         if (!vaddr)
3196                 return -ENOMEM;
3197
3198         /* find cfgtable in order to check if reset via doorbell is supported */
3199         rc = hpsa_find_cfg_addrs(pdev, vaddr, &cfg_base_addr,
3200                                         &cfg_base_addr_index, &cfg_offset);
3201         if (rc)
3202                 goto unmap_vaddr;
3203         cfgtable = remap_pci_mem(pci_resource_start(pdev,
3204                        cfg_base_addr_index) + cfg_offset, sizeof(*cfgtable));
3205         if (!cfgtable) {
3206                 rc = -ENOMEM;
3207                 goto unmap_vaddr;
3208         }
3209
3210         /* If reset via doorbell register is supported, use that. */
3211         misc_fw_support = readl(&cfgtable->misc_fw_support);
3212         use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET;
3213
3214         rc = hpsa_controller_hard_reset(pdev, vaddr, use_doorbell);
3215         if (rc)
3216                 goto unmap_cfgtable;
3217
3218         /* Restore the PCI configuration space.  The Open CISS
3219          * Specification says, "Restore the PCI Configuration
3220          * Registers, offsets 00h through 60h. It is important to
3221          * restore the command register, 16-bits at offset 04h,
3222          * last. Do not restore the configuration status register,
3223          * 16-bits at offset 06h."  Note that the offset is 2*i.
3224          */
3225         for (i = 0; i < 32; i++) {
3226                 if (i == 2 || i == 3)
3227                         continue;
3228                 pci_write_config_word(pdev, 2*i, saved_config_space[i]);
3229         }
3230         wmb();
3231         pci_write_config_word(pdev, 4, saved_config_space[2]);
3232
3233         /* Some devices (notably the HP Smart Array 5i Controller)
3234            need a little pause here */
3235         msleep(HPSA_POST_RESET_PAUSE_MSECS);
3236
3237         /* Controller should be in simple mode at this point.  If it's not,
3238          * It means we're on one of those controllers which doesn't support
3239          * the doorbell reset method and on which the PCI power management reset
3240          * method doesn't work (P800, for example.)
3241          * In those cases, pretend the reset worked and hope for the best.
3242          */
3243         active_transport = readl(&cfgtable->TransportActive);
3244         if (active_transport & PERFORMANT_MODE) {
3245                 dev_warn(&pdev->dev, "Unable to successfully reset controller,"
3246                         " proceeding anyway.\n");
3247                 rc = -ENOTSUPP;
3248         }
3249
3250 unmap_cfgtable:
3251         iounmap(cfgtable);
3252
3253 unmap_vaddr:
3254         iounmap(vaddr);
3255         return rc;
3256 }
3257
3258 /*
3259  *  We cannot read the structure directly, for portability we must use
3260  *   the io functions.
3261  *   This is for debug only.
3262  */
3263 static void print_cfg_table(struct device *dev, struct CfgTable *tb)
3264 {
3265 #ifdef HPSA_DEBUG
3266         int i;
3267         char temp_name[17];
3268
3269         dev_info(dev, "Controller Configuration information\n");
3270         dev_info(dev, "------------------------------------\n");
3271         for (i = 0; i < 4; i++)
3272                 temp_name[i] = readb(&(tb->Signature[i]));
3273         temp_name[4] = '\0';
3274         dev_info(dev, "   Signature = %s\n", temp_name);
3275         dev_info(dev, "   Spec Number = %d\n", readl(&(tb->SpecValence)));
3276         dev_info(dev, "   Transport methods supported = 0x%x\n",
3277                readl(&(tb->TransportSupport)));
3278         dev_info(dev, "   Transport methods active = 0x%x\n",
3279                readl(&(tb->TransportActive)));
3280         dev_info(dev, "   Requested transport Method = 0x%x\n",
3281                readl(&(tb->HostWrite.TransportRequest)));
3282         dev_info(dev, "   Coalesce Interrupt Delay = 0x%x\n",
3283                readl(&(tb->HostWrite.CoalIntDelay)));
3284         dev_info(dev, "   Coalesce Interrupt Count = 0x%x\n",
3285                readl(&(tb->HostWrite.CoalIntCount)));
3286         dev_info(dev, "   Max outstanding commands = 0x%d\n",
3287                readl(&(tb->CmdsOutMax)));
3288         dev_info(dev, "   Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
3289         for (i = 0; i < 16; i++)
3290                 temp_name[i] = readb(&(tb->ServerName[i]));
3291         temp_name[16] = '\0';
3292         dev_info(dev, "   Server Name = %s\n", temp_name);
3293         dev_info(dev, "   Heartbeat Counter = 0x%x\n\n\n",
3294                 readl(&(tb->HeartBeat)));
3295 #endif                          /* HPSA_DEBUG */
3296 }
3297
3298 static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
3299 {
3300         int i, offset, mem_type, bar_type;
3301
3302         if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
3303                 return 0;
3304         offset = 0;
3305         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3306                 bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
3307                 if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
3308                         offset += 4;
3309                 else {
3310                         mem_type = pci_resource_flags(pdev, i) &
3311                             PCI_BASE_ADDRESS_MEM_TYPE_MASK;
3312                         switch (mem_type) {
3313                         case PCI_BASE_ADDRESS_MEM_TYPE_32:
3314                         case PCI_BASE_ADDRESS_MEM_TYPE_1M:
3315                                 offset += 4;    /* 32 bit */
3316                                 break;
3317                         case PCI_BASE_ADDRESS_MEM_TYPE_64:
3318                                 offset += 8;
3319                                 break;
3320                         default:        /* reserved in PCI 2.2 */
3321                                 dev_warn(&pdev->dev,
3322                                        "base address is invalid\n");
3323                                 return -1;
3324                                 break;
3325                         }
3326                 }
3327                 if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
3328                         return i + 1;
3329         }
3330         return -1;
3331 }
3332
3333 /* If MSI/MSI-X is supported by the kernel we will try to enable it on
3334  * controllers that are capable. If not, we use IO-APIC mode.
3335  */
3336
3337 static void __devinit hpsa_interrupt_mode(struct ctlr_info *h)
3338 {
3339 #ifdef CONFIG_PCI_MSI
3340         int err;
3341         struct msix_entry hpsa_msix_entries[4] = { {0, 0}, {0, 1},
3342         {0, 2}, {0, 3}
3343         };
3344
3345         /* Some boards advertise MSI but don't really support it */
3346         if ((h->board_id == 0x40700E11) || (h->board_id == 0x40800E11) ||
3347             (h->board_id == 0x40820E11) || (h->board_id == 0x40830E11))
3348                 goto default_int_mode;
3349         if (pci_find_capability(h->pdev, PCI_CAP_ID_MSIX)) {
3350                 dev_info(&h->pdev->dev, "MSIX\n");
3351                 err = pci_enable_msix(h->pdev, hpsa_msix_entries, 4);
3352                 if (!err) {
3353                         h->intr[0] = hpsa_msix_entries[0].vector;
3354                         h->intr[1] = hpsa_msix_entries[1].vector;
3355                         h->intr[2] = hpsa_msix_entries[2].vector;
3356                         h->intr[3] = hpsa_msix_entries[3].vector;
3357                         h->msix_vector = 1;
3358                         return;
3359                 }
3360                 if (err > 0) {
3361                         dev_warn(&h->pdev->dev, "only %d MSI-X vectors "
3362                                "available\n", err);
3363                         goto default_int_mode;
3364                 } else {
3365                         dev_warn(&h->pdev->dev, "MSI-X init failed %d\n",
3366                                err);
3367                         goto default_int_mode;
3368                 }
3369         }
3370         if (pci_find_capability(h->pdev, PCI_CAP_ID_MSI)) {
3371                 dev_info(&h->pdev->dev, "MSI\n");
3372                 if (!pci_enable_msi(h->pdev))
3373                         h->msi_vector = 1;
3374                 else
3375                         dev_warn(&h->pdev->dev, "MSI init failed\n");
3376         }
3377 default_int_mode:
3378 #endif                          /* CONFIG_PCI_MSI */
3379         /* if we get here we're going to use the default interrupt mode */
3380         h->intr[PERF_MODE_INT] = h->pdev->irq;
3381 }
3382
3383 static int __devinit hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id)
3384 {
3385         int i;
3386         u32 subsystem_vendor_id, subsystem_device_id;
3387
3388         subsystem_vendor_id = pdev->subsystem_vendor;
3389         subsystem_device_id = pdev->subsystem_device;
3390         *board_id = ((subsystem_device_id << 16) & 0xffff0000) |
3391                     subsystem_vendor_id;
3392
3393         for (i = 0; i < ARRAY_SIZE(products); i++)
3394                 if (*board_id == products[i].board_id)
3395                         return i;
3396
3397         if ((subsystem_vendor_id != PCI_VENDOR_ID_HP &&
3398                 subsystem_vendor_id != PCI_VENDOR_ID_COMPAQ) ||
3399                 !hpsa_allow_any) {
3400                 dev_warn(&pdev->dev, "unrecognized board ID: "
3401                         "0x%08x, ignoring.\n", *board_id);
3402                         return -ENODEV;
3403         }
3404         return ARRAY_SIZE(products) - 1; /* generic unknown smart array */
3405 }
3406
3407 static inline bool hpsa_board_disabled(struct pci_dev *pdev)
3408 {
3409         u16 command;
3410
3411         (void) pci_read_config_word(pdev, PCI_COMMAND, &command);
3412         return ((command & PCI_COMMAND_MEMORY) == 0);
3413 }
3414
3415 static int __devinit hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
3416         unsigned long *memory_bar)
3417 {
3418         int i;
3419
3420         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
3421                 if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
3422                         /* addressing mode bits already removed */
3423                         *memory_bar = pci_resource_start(pdev, i);
3424                         dev_dbg(&pdev->dev, "memory BAR = %lx\n",
3425                                 *memory_bar);
3426                         return 0;
3427                 }
3428         dev_warn(&pdev->dev, "no memory BAR found\n");
3429         return -ENODEV;
3430 }
3431
3432 static int __devinit hpsa_wait_for_board_ready(struct ctlr_info *h)
3433 {
3434         int i;
3435         u32 scratchpad;
3436
3437         for (i = 0; i < HPSA_BOARD_READY_ITERATIONS; i++) {
3438                 scratchpad = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
3439                 if (scratchpad == HPSA_FIRMWARE_READY)
3440                         return 0;
3441                 msleep(HPSA_BOARD_READY_POLL_INTERVAL_MSECS);
3442         }
3443         dev_warn(&h->pdev->dev, "board not ready, timed out.\n");
3444         return -ENODEV;
3445 }
3446
3447 static int __devinit hpsa_find_cfg_addrs(struct pci_dev *pdev,
3448         void __iomem *vaddr, u32 *cfg_base_addr, u64 *cfg_base_addr_index,
3449         u64 *cfg_offset)
3450 {
3451         *cfg_base_addr = readl(vaddr + SA5_CTCFG_OFFSET);
3452         *cfg_offset = readl(vaddr + SA5_CTMEM_OFFSET);
3453         *cfg_base_addr &= (u32) 0x0000ffff;
3454         *cfg_base_addr_index = find_PCI_BAR_index(pdev, *cfg_base_addr);
3455         if (*cfg_base_addr_index == -1) {
3456                 dev_warn(&pdev->dev, "cannot find cfg_base_addr_index\n");
3457                 return -ENODEV;
3458         }
3459         return 0;
3460 }
3461
3462 static int __devinit hpsa_find_cfgtables(struct ctlr_info *h)
3463 {
3464         u64 cfg_offset;
3465         u32 cfg_base_addr;
3466         u64 cfg_base_addr_index;
3467         u32 trans_offset;
3468         int rc;
3469
3470         rc = hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
3471                 &cfg_base_addr_index, &cfg_offset);
3472         if (rc)
3473                 return rc;
3474         h->cfgtable = remap_pci_mem(pci_resource_start(h->pdev,
3475                        cfg_base_addr_index) + cfg_offset, sizeof(*h->cfgtable));
3476         if (!h->cfgtable)
3477                 return -ENOMEM;
3478         /* Find performant mode table. */
3479         trans_offset = readl(&h->cfgtable->TransMethodOffset);
3480         h->transtable = remap_pci_mem(pci_resource_start(h->pdev,
3481                                 cfg_base_addr_index)+cfg_offset+trans_offset,
3482                                 sizeof(*h->transtable));
3483         if (!h->transtable)
3484                 return -ENOMEM;
3485         return 0;
3486 }
3487
3488 /* Interrogate the hardware for some limits:
3489  * max commands, max SG elements without chaining, and with chaining,
3490  * SG chain block size, etc.
3491  */
3492 static void __devinit hpsa_find_board_params(struct ctlr_info *h)
3493 {
3494         h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
3495         h->nr_cmds = h->max_commands - 4; /* Allow room for some ioctls */
3496         h->maxsgentries = readl(&(h->cfgtable->MaxScatterGatherElements));
3497         /*
3498          * Limit in-command s/g elements to 32 save dma'able memory.
3499          * Howvever spec says if 0, use 31
3500          */
3501         h->max_cmd_sg_entries = 31;
3502         if (h->maxsgentries > 512) {
3503                 h->max_cmd_sg_entries = 32;
3504                 h->chainsize = h->maxsgentries - h->max_cmd_sg_entries + 1;
3505                 h->maxsgentries--; /* save one for chain pointer */
3506         } else {
3507                 h->maxsgentries = 31; /* default to traditional values */
3508                 h->chainsize = 0;
3509         }
3510 }
3511
3512 static inline bool hpsa_CISS_signature_present(struct ctlr_info *h)
3513 {
3514         if ((readb(&h->cfgtable->Signature[0]) != 'C') ||
3515             (readb(&h->cfgtable->Signature[1]) != 'I') ||
3516             (readb(&h->cfgtable->Signature[2]) != 'S') ||
3517             (readb(&h->cfgtable->Signature[3]) != 'S')) {
3518                 dev_warn(&h->pdev->dev, "not a valid CISS config table\n");
3519                 return false;
3520         }
3521         return true;
3522 }
3523
3524 /* Need to enable prefetch in the SCSI core for 6400 in x86 */
3525 static inline void hpsa_enable_scsi_prefetch(struct ctlr_info *h)
3526 {
3527 #ifdef CONFIG_X86
3528         u32 prefetch;
3529
3530         prefetch = readl(&(h->cfgtable->SCSI_Prefetch));
3531         prefetch |= 0x100;
3532         writel(prefetch, &(h->cfgtable->SCSI_Prefetch));
3533 #endif
3534 }
3535
3536 /* Disable DMA prefetch for the P600.  Otherwise an ASIC bug may result
3537  * in a prefetch beyond physical memory.
3538  */
3539 static inline void hpsa_p600_dma_prefetch_quirk(struct ctlr_info *h)
3540 {
3541         u32 dma_prefetch;
3542
3543         if (h->board_id != 0x3225103C)
3544                 return;
3545         dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
3546         dma_prefetch |= 0x8000;
3547         writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
3548 }
3549
3550 static void __devinit hpsa_wait_for_mode_change_ack(struct ctlr_info *h)
3551 {
3552         int i;
3553
3554         /* under certain very rare conditions, this can take awhile.
3555          * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
3556          * as we enter this code.)
3557          */
3558         for (i = 0; i < MAX_CONFIG_WAIT; i++) {
3559                 if (!(readl(h->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
3560                         break;
3561                 /* delay and try again */
3562                 msleep(10);
3563         }
3564 }
3565
3566 static int __devinit hpsa_enter_simple_mode(struct ctlr_info *h)
3567 {
3568         u32 trans_support;
3569
3570         trans_support = readl(&(h->cfgtable->TransportSupport));
3571         if (!(trans_support & SIMPLE_MODE))
3572                 return -ENOTSUPP;
3573
3574         h->max_commands = readl(&(h->cfgtable->CmdsOutMax));
3575         /* Update the field, and then ring the doorbell */
3576         writel(CFGTBL_Trans_Simple, &(h->cfgtable->HostWrite.TransportRequest));
3577         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
3578         hpsa_wait_for_mode_change_ack(h);
3579         print_cfg_table(&h->pdev->dev, h->cfgtable);
3580         if (!(readl(&(h->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
3581                 dev_warn(&h->pdev->dev,
3582                         "unable to get board into simple mode\n");
3583                 return -ENODEV;
3584         }
3585         return 0;
3586 }
3587
3588 static int __devinit hpsa_pci_init(struct ctlr_info *h)
3589 {
3590         int prod_index, err;
3591
3592         prod_index = hpsa_lookup_board_id(h->pdev, &h->board_id);
3593         if (prod_index < 0)
3594                 return -ENODEV;
3595         h->product_name = products[prod_index].product_name;
3596         h->access = *(products[prod_index].access);
3597
3598         if (hpsa_board_disabled(h->pdev)) {
3599                 dev_warn(&h->pdev->dev, "controller appears to be disabled\n");
3600                 return -ENODEV;
3601         }
3602         err = pci_enable_device(h->pdev);
3603         if (err) {
3604                 dev_warn(&h->pdev->dev, "unable to enable PCI device\n");
3605                 return err;
3606         }
3607
3608         err = pci_request_regions(h->pdev, "hpsa");
3609         if (err) {
3610                 dev_err(&h->pdev->dev,
3611                         "cannot obtain PCI resources, aborting\n");
3612                 return err;
3613         }
3614         hpsa_interrupt_mode(h);
3615         err = hpsa_pci_find_memory_BAR(h->pdev, &h->paddr);
3616         if (err)
3617                 goto err_out_free_res;
3618         h->vaddr = remap_pci_mem(h->paddr, 0x250);
3619         if (!h->vaddr) {
3620                 err = -ENOMEM;
3621                 goto err_out_free_res;
3622         }
3623         err = hpsa_wait_for_board_ready(h);
3624         if (err)
3625                 goto err_out_free_res;
3626         err = hpsa_find_cfgtables(h);
3627         if (err)
3628                 goto err_out_free_res;
3629         hpsa_find_board_params(h);
3630
3631         if (!hpsa_CISS_signature_present(h)) {
3632                 err = -ENODEV;
3633                 goto err_out_free_res;
3634         }
3635         hpsa_enable_scsi_prefetch(h);
3636         hpsa_p600_dma_prefetch_quirk(h);
3637         err = hpsa_enter_simple_mode(h);
3638         if (err)
3639                 goto err_out_free_res;
3640         return 0;
3641
3642 err_out_free_res:
3643         if (h->transtable)
3644                 iounmap(h->transtable);
3645         if (h->cfgtable)
3646                 iounmap(h->cfgtable);
3647         if (h->vaddr)
3648                 iounmap(h->vaddr);
3649         /*
3650          * Deliberately omit pci_disable_device(): it does something nasty to
3651          * Smart Array controllers that pci_enable_device does not undo
3652          */
3653         pci_release_regions(h->pdev);
3654         return err;
3655 }
3656
3657 static void __devinit hpsa_hba_inquiry(struct ctlr_info *h)
3658 {
3659         int rc;
3660
3661 #define HBA_INQUIRY_BYTE_COUNT 64
3662         h->hba_inquiry_data = kmalloc(HBA_INQUIRY_BYTE_COUNT, GFP_KERNEL);
3663         if (!h->hba_inquiry_data)
3664                 return;
3665         rc = hpsa_scsi_do_inquiry(h, RAID_CTLR_LUNID, 0,
3666                 h->hba_inquiry_data, HBA_INQUIRY_BYTE_COUNT);
3667         if (rc != 0) {
3668                 kfree(h->hba_inquiry_data);
3669                 h->hba_inquiry_data = NULL;
3670         }
3671 }
3672
3673 static __devinit int hpsa_init_reset_devices(struct pci_dev *pdev)
3674 {
3675         int rc, i;
3676
3677         if (!reset_devices)
3678                 return 0;
3679
3680         /* Reset the controller with a PCI power-cycle or via doorbell */
3681         rc = hpsa_kdump_hard_reset_controller(pdev);
3682
3683         /* -ENOTSUPP here means we cannot reset the controller
3684          * but it's already (and still) up and running in
3685          * "performant mode".  Or, it might be 640x, which can't reset
3686          * due to concerns about shared bbwc between 6402/6404 pair.
3687          */
3688         if (rc == -ENOTSUPP)
3689                 return 0; /* just try to do the kdump anyhow. */
3690         if (rc)
3691                 return -ENODEV;
3692         if (hpsa_reset_msi(pdev))
3693                 return -ENODEV;
3694
3695         /* Now try to get the controller to respond to a no-op */
3696         for (i = 0; i < HPSA_POST_RESET_NOOP_RETRIES; i++) {
3697                 if (hpsa_noop(pdev) == 0)
3698                         break;
3699                 else
3700                         dev_warn(&pdev->dev, "no-op failed%s\n",
3701                                         (i < 11 ? "; re-trying" : ""));
3702         }
3703         return 0;
3704 }
3705
3706 static int __devinit hpsa_init_one(struct pci_dev *pdev,
3707                                     const struct pci_device_id *ent)
3708 {
3709         int dac, rc;
3710         struct ctlr_info *h;
3711
3712         if (number_of_controllers == 0)
3713                 printk(KERN_INFO DRIVER_NAME "\n");
3714
3715         rc = hpsa_init_reset_devices(pdev);
3716         if (rc)
3717                 return rc;
3718
3719         /* Command structures must be aligned on a 32-byte boundary because
3720          * the 5 lower bits of the address are used by the hardware. and by
3721          * the driver.  See comments in hpsa.h for more info.
3722          */
3723 #define COMMANDLIST_ALIGNMENT 32
3724         BUILD_BUG_ON(sizeof(struct CommandList) % COMMANDLIST_ALIGNMENT);
3725         h = kzalloc(sizeof(*h), GFP_KERNEL);
3726         if (!h)
3727                 return -ENOMEM;
3728
3729         h->pdev = pdev;
3730         h->busy_initializing = 1;
3731         INIT_HLIST_HEAD(&h->cmpQ);
3732         INIT_HLIST_HEAD(&h->reqQ);
3733         rc = hpsa_pci_init(h);
3734         if (rc != 0)
3735                 goto clean1;
3736
3737         sprintf(h->devname, "hpsa%d", number_of_controllers);
3738         h->ctlr = number_of_controllers;
3739         number_of_controllers++;
3740
3741         /* configure PCI DMA stuff */
3742         rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
3743         if (rc == 0) {
3744                 dac = 1;
3745         } else {
3746                 rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
3747                 if (rc == 0) {
3748                         dac = 0;
3749                 } else {
3750                         dev_err(&pdev->dev, "no suitable DMA available\n");
3751                         goto clean1;
3752                 }
3753         }
3754
3755         /* make sure the board interrupts are off */
3756         h->access.set_intr_mask(h, HPSA_INTR_OFF);
3757         rc = request_irq(h->intr[PERF_MODE_INT], do_hpsa_intr,
3758                         IRQF_DISABLED, h->devname, h);
3759         if (rc) {
3760                 dev_err(&pdev->dev, "unable to get irq %d for %s\n",
3761                        h->intr[PERF_MODE_INT], h->devname);
3762                 goto clean2;
3763         }
3764
3765         dev_info(&pdev->dev, "%s: <0x%x> at IRQ %d%s using DAC\n",
3766                h->devname, pdev->device,
3767                h->intr[PERF_MODE_INT], dac ? "" : " not");
3768
3769         h->cmd_pool_bits =
3770             kmalloc(((h->nr_cmds + BITS_PER_LONG -
3771                       1) / BITS_PER_LONG) * sizeof(unsigned long), GFP_KERNEL);
3772         h->cmd_pool = pci_alloc_consistent(h->pdev,
3773                     h->nr_cmds * sizeof(*h->cmd_pool),
3774                     &(h->cmd_pool_dhandle));
3775         h->errinfo_pool = pci_alloc_consistent(h->pdev,
3776                     h->nr_cmds * sizeof(*h->errinfo_pool),
3777                     &(h->errinfo_pool_dhandle));
3778         if ((h->cmd_pool_bits == NULL)
3779             || (h->cmd_pool == NULL)
3780             || (h->errinfo_pool == NULL)) {
3781                 dev_err(&pdev->dev, "out of memory");
3782                 rc = -ENOMEM;
3783                 goto clean4;
3784         }
3785         if (hpsa_allocate_sg_chain_blocks(h))
3786                 goto clean4;
3787         spin_lock_init(&h->lock);
3788         spin_lock_init(&h->scan_lock);
3789         init_waitqueue_head(&h->scan_wait_queue);
3790         h->scan_finished = 1; /* no scan currently in progress */
3791
3792         pci_set_drvdata(pdev, h);
3793         memset(h->cmd_pool_bits, 0,
3794                ((h->nr_cmds + BITS_PER_LONG -
3795                  1) / BITS_PER_LONG) * sizeof(unsigned long));
3796
3797         hpsa_scsi_setup(h);
3798
3799         /* Turn the interrupts on so we can service requests */
3800         h->access.set_intr_mask(h, HPSA_INTR_ON);
3801
3802         hpsa_put_ctlr_into_performant_mode(h);
3803         hpsa_hba_inquiry(h);
3804         hpsa_register_scsi(h);  /* hook ourselves into SCSI subsystem */
3805         h->busy_initializing = 0;
3806         return 1;
3807
3808 clean4:
3809         hpsa_free_sg_chain_blocks(h);
3810         kfree(h->cmd_pool_bits);
3811         if (h->cmd_pool)
3812                 pci_free_consistent(h->pdev,
3813                             h->nr_cmds * sizeof(struct CommandList),
3814                             h->cmd_pool, h->cmd_pool_dhandle);
3815         if (h->errinfo_pool)
3816                 pci_free_consistent(h->pdev,
3817                             h->nr_cmds * sizeof(struct ErrorInfo),
3818                             h->errinfo_pool,
3819                             h->errinfo_pool_dhandle);
3820         free_irq(h->intr[PERF_MODE_INT], h);
3821 clean2:
3822 clean1:
3823         h->busy_initializing = 0;
3824         kfree(h);
3825         return rc;
3826 }
3827
3828 static void hpsa_flush_cache(struct ctlr_info *h)
3829 {
3830         char *flush_buf;
3831         struct CommandList *c;
3832
3833         flush_buf = kzalloc(4, GFP_KERNEL);
3834         if (!flush_buf)
3835                 return;
3836
3837         c = cmd_special_alloc(h);
3838         if (!c) {
3839                 dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
3840                 goto out_of_memory;
3841         }
3842         fill_cmd(c, HPSA_CACHE_FLUSH, h, flush_buf, 4, 0,
3843                 RAID_CTLR_LUNID, TYPE_CMD);
3844         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_TODEVICE);
3845         if (c->err_info->CommandStatus != 0)
3846                 dev_warn(&h->pdev->dev,
3847                         "error flushing cache on controller\n");
3848         cmd_special_free(h, c);
3849 out_of_memory:
3850         kfree(flush_buf);
3851 }
3852
3853 static void hpsa_shutdown(struct pci_dev *pdev)
3854 {
3855         struct ctlr_info *h;
3856
3857         h = pci_get_drvdata(pdev);
3858         /* Turn board interrupts off  and send the flush cache command
3859          * sendcmd will turn off interrupt, and send the flush...
3860          * To write all data in the battery backed cache to disks
3861          */
3862         hpsa_flush_cache(h);
3863         h->access.set_intr_mask(h, HPSA_INTR_OFF);
3864         free_irq(h->intr[PERF_MODE_INT], h);
3865 #ifdef CONFIG_PCI_MSI
3866         if (h->msix_vector)
3867                 pci_disable_msix(h->pdev);
3868         else if (h->msi_vector)
3869                 pci_disable_msi(h->pdev);
3870 #endif                          /* CONFIG_PCI_MSI */
3871 }
3872
3873 static void __devexit hpsa_remove_one(struct pci_dev *pdev)
3874 {
3875         struct ctlr_info *h;
3876
3877         if (pci_get_drvdata(pdev) == NULL) {
3878                 dev_err(&pdev->dev, "unable to remove device \n");
3879                 return;
3880         }
3881         h = pci_get_drvdata(pdev);
3882         hpsa_unregister_scsi(h);        /* unhook from SCSI subsystem */
3883         hpsa_shutdown(pdev);
3884         iounmap(h->vaddr);
3885         iounmap(h->transtable);
3886         iounmap(h->cfgtable);
3887         hpsa_free_sg_chain_blocks(h);
3888         pci_free_consistent(h->pdev,
3889                 h->nr_cmds * sizeof(struct CommandList),
3890                 h->cmd_pool, h->cmd_pool_dhandle);
3891         pci_free_consistent(h->pdev,
3892                 h->nr_cmds * sizeof(struct ErrorInfo),
3893                 h->errinfo_pool, h->errinfo_pool_dhandle);
3894         pci_free_consistent(h->pdev, h->reply_pool_size,
3895                 h->reply_pool, h->reply_pool_dhandle);
3896         kfree(h->cmd_pool_bits);
3897         kfree(h->blockFetchTable);
3898         kfree(h->hba_inquiry_data);
3899         /*
3900          * Deliberately omit pci_disable_device(): it does something nasty to
3901          * Smart Array controllers that pci_enable_device does not undo
3902          */
3903         pci_release_regions(pdev);
3904         pci_set_drvdata(pdev, NULL);
3905         kfree(h);
3906 }
3907
3908 static int hpsa_suspend(__attribute__((unused)) struct pci_dev *pdev,
3909         __attribute__((unused)) pm_message_t state)
3910 {
3911         return -ENOSYS;
3912 }
3913
3914 static int hpsa_resume(__attribute__((unused)) struct pci_dev *pdev)
3915 {
3916         return -ENOSYS;
3917 }
3918
3919 static struct pci_driver hpsa_pci_driver = {
3920         .name = "hpsa",
3921         .probe = hpsa_init_one,
3922         .remove = __devexit_p(hpsa_remove_one),
3923         .id_table = hpsa_pci_device_id, /* id_table */
3924         .shutdown = hpsa_shutdown,
3925         .suspend = hpsa_suspend,
3926         .resume = hpsa_resume,
3927 };
3928
3929 /* Fill in bucket_map[], given nsgs (the max number of
3930  * scatter gather elements supported) and bucket[],
3931  * which is an array of 8 integers.  The bucket[] array
3932  * contains 8 different DMA transfer sizes (in 16
3933  * byte increments) which the controller uses to fetch
3934  * commands.  This function fills in bucket_map[], which
3935  * maps a given number of scatter gather elements to one of
3936  * the 8 DMA transfer sizes.  The point of it is to allow the
3937  * controller to only do as much DMA as needed to fetch the
3938  * command, with the DMA transfer size encoded in the lower
3939  * bits of the command address.
3940  */
3941 static void  calc_bucket_map(int bucket[], int num_buckets,
3942         int nsgs, int *bucket_map)
3943 {
3944         int i, j, b, size;
3945
3946         /* even a command with 0 SGs requires 4 blocks */
3947 #define MINIMUM_TRANSFER_BLOCKS 4
3948 #define NUM_BUCKETS 8
3949         /* Note, bucket_map must have nsgs+1 entries. */
3950         for (i = 0; i <= nsgs; i++) {
3951                 /* Compute size of a command with i SG entries */
3952                 size = i + MINIMUM_TRANSFER_BLOCKS;
3953                 b = num_buckets; /* Assume the biggest bucket */
3954                 /* Find the bucket that is just big enough */
3955                 for (j = 0; j < 8; j++) {
3956                         if (bucket[j] >= size) {
3957                                 b = j;
3958                                 break;
3959                         }
3960                 }
3961                 /* for a command with i SG entries, use bucket b. */
3962                 bucket_map[i] = b;
3963         }
3964 }
3965
3966 static __devinit void hpsa_enter_performant_mode(struct ctlr_info *h)
3967 {
3968         int i;
3969         unsigned long register_value;
3970
3971         /* This is a bit complicated.  There are 8 registers on
3972          * the controller which we write to to tell it 8 different
3973          * sizes of commands which there may be.  It's a way of
3974          * reducing the DMA done to fetch each command.  Encoded into
3975          * each command's tag are 3 bits which communicate to the controller
3976          * which of the eight sizes that command fits within.  The size of
3977          * each command depends on how many scatter gather entries there are.
3978          * Each SG entry requires 16 bytes.  The eight registers are programmed
3979          * with the number of 16-byte blocks a command of that size requires.
3980          * The smallest command possible requires 5 such 16 byte blocks.
3981          * the largest command possible requires MAXSGENTRIES + 4 16-byte
3982          * blocks.  Note, this only extends to the SG entries contained
3983          * within the command block, and does not extend to chained blocks
3984          * of SG elements.   bft[] contains the eight values we write to
3985          * the registers.  They are not evenly distributed, but have more
3986          * sizes for small commands, and fewer sizes for larger commands.
3987          */
3988         int bft[8] = {5, 6, 8, 10, 12, 20, 28, MAXSGENTRIES + 4};
3989         BUILD_BUG_ON(28 > MAXSGENTRIES + 4);
3990         /*  5 = 1 s/g entry or 4k
3991          *  6 = 2 s/g entry or 8k
3992          *  8 = 4 s/g entry or 16k
3993          * 10 = 6 s/g entry or 24k
3994          */
3995
3996         h->reply_pool_wraparound = 1; /* spec: init to 1 */
3997
3998         /* Controller spec: zero out this buffer. */
3999         memset(h->reply_pool, 0, h->reply_pool_size);
4000         h->reply_pool_head = h->reply_pool;
4001
4002         bft[7] = h->max_sg_entries + 4;
4003         calc_bucket_map(bft, ARRAY_SIZE(bft), 32, h->blockFetchTable);
4004         for (i = 0; i < 8; i++)
4005                 writel(bft[i], &h->transtable->BlockFetch[i]);
4006
4007         /* size of controller ring buffer */
4008         writel(h->max_commands, &h->transtable->RepQSize);
4009         writel(1, &h->transtable->RepQCount);
4010         writel(0, &h->transtable->RepQCtrAddrLow32);
4011         writel(0, &h->transtable->RepQCtrAddrHigh32);
4012         writel(h->reply_pool_dhandle, &h->transtable->RepQAddr0Low32);
4013         writel(0, &h->transtable->RepQAddr0High32);
4014         writel(CFGTBL_Trans_Performant,
4015                 &(h->cfgtable->HostWrite.TransportRequest));
4016         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
4017         hpsa_wait_for_mode_change_ack(h);
4018         register_value = readl(&(h->cfgtable->TransportActive));
4019         if (!(register_value & CFGTBL_Trans_Performant)) {
4020                 dev_warn(&h->pdev->dev, "unable to get board into"
4021                                         " performant mode\n");
4022                 return;
4023         }
4024 }
4025
4026 static __devinit void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h)
4027 {
4028         u32 trans_support;
4029
4030         trans_support = readl(&(h->cfgtable->TransportSupport));
4031         if (!(trans_support & PERFORMANT_MODE))
4032                 return;
4033
4034         h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
4035         h->max_sg_entries = 32;
4036         /* Performant mode ring buffer and supporting data structures */
4037         h->reply_pool_size = h->max_commands * sizeof(u64);
4038         h->reply_pool = pci_alloc_consistent(h->pdev, h->reply_pool_size,
4039                                 &(h->reply_pool_dhandle));
4040
4041         /* Need a block fetch table for performant mode */
4042         h->blockFetchTable = kmalloc(((h->max_sg_entries+1) *
4043                                 sizeof(u32)), GFP_KERNEL);
4044
4045         if ((h->reply_pool == NULL)
4046                 || (h->blockFetchTable == NULL))
4047                 goto clean_up;
4048
4049         hpsa_enter_performant_mode(h);
4050
4051         /* Change the access methods to the performant access methods */
4052         h->access = SA5_performant_access;
4053         h->transMethod = CFGTBL_Trans_Performant;
4054
4055         return;
4056
4057 clean_up:
4058         if (h->reply_pool)
4059                 pci_free_consistent(h->pdev, h->reply_pool_size,
4060                         h->reply_pool, h->reply_pool_dhandle);
4061         kfree(h->blockFetchTable);
4062 }
4063
4064 /*
4065  *  This is it.  Register the PCI driver information for the cards we control
4066  *  the OS will call our registered routines when it finds one of our cards.
4067  */
4068 static int __init hpsa_init(void)
4069 {
4070         return pci_register_driver(&hpsa_pci_driver);
4071 }
4072
4073 static void __exit hpsa_cleanup(void)
4074 {
4075         pci_unregister_driver(&hpsa_pci_driver);
4076 }
4077
4078 module_init(hpsa_init);
4079 module_exit(hpsa_cleanup);