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