]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/scsi/hpsa.c
[SCSI] hpsa: Don't return DID_NO_CONNECT when a device is merely not ready
[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                                         dev_warn(&h->pdev->dev, "cp %p "
1033                                                 "has check condition: unit "
1034                                                 "not ready, manual "
1035                                                 "intervention required\n", cp);
1036                                         break;
1037                                 }
1038                         }
1039                         if (sense_key == ABORTED_COMMAND) {
1040                                 /* Aborted command is retryable */
1041                                 dev_warn(&h->pdev->dev, "cp %p "
1042                                         "has check condition: aborted command: "
1043                                         "ASC: 0x%x, ASCQ: 0x%x\n",
1044                                         cp, asc, ascq);
1045                                 cmd->result = DID_SOFT_ERROR << 16;
1046                                 break;
1047                         }
1048                         /* Must be some other type of check condition */
1049                         dev_warn(&h->pdev->dev, "cp %p has check condition: "
1050                                         "unknown type: "
1051                                         "Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
1052                                         "Returning result: 0x%x, "
1053                                         "cmd=[%02x %02x %02x %02x %02x "
1054                                         "%02x %02x %02x %02x %02x]\n",
1055                                         cp, sense_key, asc, ascq,
1056                                         cmd->result,
1057                                         cmd->cmnd[0], cmd->cmnd[1],
1058                                         cmd->cmnd[2], cmd->cmnd[3],
1059                                         cmd->cmnd[4], cmd->cmnd[5],
1060                                         cmd->cmnd[6], cmd->cmnd[7],
1061                                         cmd->cmnd[8], cmd->cmnd[9]);
1062                         break;
1063                 }
1064
1065
1066                 /* Problem was not a check condition
1067                  * Pass it up to the upper layers...
1068                  */
1069                 if (ei->ScsiStatus) {
1070                         dev_warn(&h->pdev->dev, "cp %p has status 0x%x "
1071                                 "Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
1072                                 "Returning result: 0x%x\n",
1073                                 cp, ei->ScsiStatus,
1074                                 sense_key, asc, ascq,
1075                                 cmd->result);
1076                 } else {  /* scsi status is zero??? How??? */
1077                         dev_warn(&h->pdev->dev, "cp %p SCSI status was 0. "
1078                                 "Returning no connection.\n", cp),
1079
1080                         /* Ordinarily, this case should never happen,
1081                          * but there is a bug in some released firmware
1082                          * revisions that allows it to happen if, for
1083                          * example, a 4100 backplane loses power and
1084                          * the tape drive is in it.  We assume that
1085                          * it's a fatal error of some kind because we
1086                          * can't show that it wasn't. We will make it
1087                          * look like selection timeout since that is
1088                          * the most common reason for this to occur,
1089                          * and it's severe enough.
1090                          */
1091
1092                         cmd->result = DID_NO_CONNECT << 16;
1093                 }
1094                 break;
1095
1096         case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
1097                 break;
1098         case CMD_DATA_OVERRUN:
1099                 dev_warn(&h->pdev->dev, "cp %p has"
1100                         " completed with data overrun "
1101                         "reported\n", cp);
1102                 break;
1103         case CMD_INVALID: {
1104                 /* print_bytes(cp, sizeof(*cp), 1, 0);
1105                 print_cmd(cp); */
1106                 /* We get CMD_INVALID if you address a non-existent device
1107                  * instead of a selection timeout (no response).  You will
1108                  * see this if you yank out a drive, then try to access it.
1109                  * This is kind of a shame because it means that any other
1110                  * CMD_INVALID (e.g. driver bug) will get interpreted as a
1111                  * missing target. */
1112                 cmd->result = DID_NO_CONNECT << 16;
1113         }
1114                 break;
1115         case CMD_PROTOCOL_ERR:
1116                 dev_warn(&h->pdev->dev, "cp %p has "
1117                         "protocol error \n", cp);
1118                 break;
1119         case CMD_HARDWARE_ERR:
1120                 cmd->result = DID_ERROR << 16;
1121                 dev_warn(&h->pdev->dev, "cp %p had  hardware error\n", cp);
1122                 break;
1123         case CMD_CONNECTION_LOST:
1124                 cmd->result = DID_ERROR << 16;
1125                 dev_warn(&h->pdev->dev, "cp %p had connection lost\n", cp);
1126                 break;
1127         case CMD_ABORTED:
1128                 cmd->result = DID_ABORT << 16;
1129                 dev_warn(&h->pdev->dev, "cp %p was aborted with status 0x%x\n",
1130                                 cp, ei->ScsiStatus);
1131                 break;
1132         case CMD_ABORT_FAILED:
1133                 cmd->result = DID_ERROR << 16;
1134                 dev_warn(&h->pdev->dev, "cp %p reports abort failed\n", cp);
1135                 break;
1136         case CMD_UNSOLICITED_ABORT:
1137                 cmd->result = DID_RESET << 16;
1138                 dev_warn(&h->pdev->dev, "cp %p aborted do to an unsolicited "
1139                         "abort\n", cp);
1140                 break;
1141         case CMD_TIMEOUT:
1142                 cmd->result = DID_TIME_OUT << 16;
1143                 dev_warn(&h->pdev->dev, "cp %p timedout\n", cp);
1144                 break;
1145         default:
1146                 cmd->result = DID_ERROR << 16;
1147                 dev_warn(&h->pdev->dev, "cp %p returned unknown status %x\n",
1148                                 cp, ei->CommandStatus);
1149         }
1150         cmd->scsi_done(cmd);
1151         cmd_free(h, cp);
1152 }
1153
1154 static int hpsa_scsi_detect(struct ctlr_info *h)
1155 {
1156         struct Scsi_Host *sh;
1157         int error;
1158
1159         sh = scsi_host_alloc(&hpsa_driver_template, sizeof(h));
1160         if (sh == NULL)
1161                 goto fail;
1162
1163         sh->io_port = 0;
1164         sh->n_io_port = 0;
1165         sh->this_id = -1;
1166         sh->max_channel = 3;
1167         sh->max_cmd_len = MAX_COMMAND_SIZE;
1168         sh->max_lun = HPSA_MAX_LUN;
1169         sh->max_id = HPSA_MAX_LUN;
1170         sh->can_queue = h->nr_cmds;
1171         sh->cmd_per_lun = h->nr_cmds;
1172         h->scsi_host = sh;
1173         sh->hostdata[0] = (unsigned long) h;
1174         sh->irq = h->intr[PERF_MODE_INT];
1175         sh->unique_id = sh->irq;
1176         error = scsi_add_host(sh, &h->pdev->dev);
1177         if (error)
1178                 goto fail_host_put;
1179         scsi_scan_host(sh);
1180         return 0;
1181
1182  fail_host_put:
1183         dev_err(&h->pdev->dev, "hpsa_scsi_detect: scsi_add_host"
1184                 " failed for controller %d\n", h->ctlr);
1185         scsi_host_put(sh);
1186         return error;
1187  fail:
1188         dev_err(&h->pdev->dev, "hpsa_scsi_detect: scsi_host_alloc"
1189                 " failed for controller %d\n", h->ctlr);
1190         return -ENOMEM;
1191 }
1192
1193 static void hpsa_pci_unmap(struct pci_dev *pdev,
1194         struct CommandList *c, int sg_used, int data_direction)
1195 {
1196         int i;
1197         union u64bit addr64;
1198
1199         for (i = 0; i < sg_used; i++) {
1200                 addr64.val32.lower = c->SG[i].Addr.lower;
1201                 addr64.val32.upper = c->SG[i].Addr.upper;
1202                 pci_unmap_single(pdev, (dma_addr_t) addr64.val, c->SG[i].Len,
1203                         data_direction);
1204         }
1205 }
1206
1207 static void hpsa_map_one(struct pci_dev *pdev,
1208                 struct CommandList *cp,
1209                 unsigned char *buf,
1210                 size_t buflen,
1211                 int data_direction)
1212 {
1213         u64 addr64;
1214
1215         if (buflen == 0 || data_direction == PCI_DMA_NONE) {
1216                 cp->Header.SGList = 0;
1217                 cp->Header.SGTotal = 0;
1218                 return;
1219         }
1220
1221         addr64 = (u64) pci_map_single(pdev, buf, buflen, data_direction);
1222         cp->SG[0].Addr.lower =
1223           (u32) (addr64 & (u64) 0x00000000FFFFFFFF);
1224         cp->SG[0].Addr.upper =
1225           (u32) ((addr64 >> 32) & (u64) 0x00000000FFFFFFFF);
1226         cp->SG[0].Len = buflen;
1227         cp->Header.SGList = (u8) 1;   /* no. SGs contig in this cmd */
1228         cp->Header.SGTotal = (u16) 1; /* total sgs in this cmd list */
1229 }
1230
1231 static inline void hpsa_scsi_do_simple_cmd_core(struct ctlr_info *h,
1232         struct CommandList *c)
1233 {
1234         DECLARE_COMPLETION_ONSTACK(wait);
1235
1236         c->waiting = &wait;
1237         enqueue_cmd_and_start_io(h, c);
1238         wait_for_completion(&wait);
1239 }
1240
1241 static void hpsa_scsi_do_simple_cmd_with_retry(struct ctlr_info *h,
1242         struct CommandList *c, int data_direction)
1243 {
1244         int retry_count = 0;
1245
1246         do {
1247                 memset(c->err_info, 0, sizeof(c->err_info));
1248                 hpsa_scsi_do_simple_cmd_core(h, c);
1249                 retry_count++;
1250         } while (check_for_unit_attention(h, c) && retry_count <= 3);
1251         hpsa_pci_unmap(h->pdev, c, 1, data_direction);
1252 }
1253
1254 static void hpsa_scsi_interpret_error(struct CommandList *cp)
1255 {
1256         struct ErrorInfo *ei;
1257         struct device *d = &cp->h->pdev->dev;
1258
1259         ei = cp->err_info;
1260         switch (ei->CommandStatus) {
1261         case CMD_TARGET_STATUS:
1262                 dev_warn(d, "cmd %p has completed with errors\n", cp);
1263                 dev_warn(d, "cmd %p has SCSI Status = %x\n", cp,
1264                                 ei->ScsiStatus);
1265                 if (ei->ScsiStatus == 0)
1266                         dev_warn(d, "SCSI status is abnormally zero.  "
1267                         "(probably indicates selection timeout "
1268                         "reported incorrectly due to a known "
1269                         "firmware bug, circa July, 2001.)\n");
1270                 break;
1271         case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
1272                         dev_info(d, "UNDERRUN\n");
1273                 break;
1274         case CMD_DATA_OVERRUN:
1275                 dev_warn(d, "cp %p has completed with data overrun\n", cp);
1276                 break;
1277         case CMD_INVALID: {
1278                 /* controller unfortunately reports SCSI passthru's
1279                  * to non-existent targets as invalid commands.
1280                  */
1281                 dev_warn(d, "cp %p is reported invalid (probably means "
1282                         "target device no longer present)\n", cp);
1283                 /* print_bytes((unsigned char *) cp, sizeof(*cp), 1, 0);
1284                 print_cmd(cp);  */
1285                 }
1286                 break;
1287         case CMD_PROTOCOL_ERR:
1288                 dev_warn(d, "cp %p has protocol error \n", cp);
1289                 break;
1290         case CMD_HARDWARE_ERR:
1291                 /* cmd->result = DID_ERROR << 16; */
1292                 dev_warn(d, "cp %p had hardware error\n", cp);
1293                 break;
1294         case CMD_CONNECTION_LOST:
1295                 dev_warn(d, "cp %p had connection lost\n", cp);
1296                 break;
1297         case CMD_ABORTED:
1298                 dev_warn(d, "cp %p was aborted\n", cp);
1299                 break;
1300         case CMD_ABORT_FAILED:
1301                 dev_warn(d, "cp %p reports abort failed\n", cp);
1302                 break;
1303         case CMD_UNSOLICITED_ABORT:
1304                 dev_warn(d, "cp %p aborted due to an unsolicited abort\n", cp);
1305                 break;
1306         case CMD_TIMEOUT:
1307                 dev_warn(d, "cp %p timed out\n", cp);
1308                 break;
1309         default:
1310                 dev_warn(d, "cp %p returned unknown status %x\n", cp,
1311                                 ei->CommandStatus);
1312         }
1313 }
1314
1315 static int hpsa_scsi_do_inquiry(struct ctlr_info *h, unsigned char *scsi3addr,
1316                         unsigned char page, unsigned char *buf,
1317                         unsigned char bufsize)
1318 {
1319         int rc = IO_OK;
1320         struct CommandList *c;
1321         struct ErrorInfo *ei;
1322
1323         c = cmd_special_alloc(h);
1324
1325         if (c == NULL) {                        /* trouble... */
1326                 dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
1327                 return -ENOMEM;
1328         }
1329
1330         fill_cmd(c, HPSA_INQUIRY, h, buf, bufsize, page, scsi3addr, TYPE_CMD);
1331         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
1332         ei = c->err_info;
1333         if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
1334                 hpsa_scsi_interpret_error(c);
1335                 rc = -1;
1336         }
1337         cmd_special_free(h, c);
1338         return rc;
1339 }
1340
1341 static int hpsa_send_reset(struct ctlr_info *h, unsigned char *scsi3addr)
1342 {
1343         int rc = IO_OK;
1344         struct CommandList *c;
1345         struct ErrorInfo *ei;
1346
1347         c = cmd_special_alloc(h);
1348
1349         if (c == NULL) {                        /* trouble... */
1350                 dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
1351                 return -1;
1352         }
1353
1354         fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0, scsi3addr, TYPE_MSG);
1355         hpsa_scsi_do_simple_cmd_core(h, c);
1356         /* no unmap needed here because no data xfer. */
1357
1358         ei = c->err_info;
1359         if (ei->CommandStatus != 0) {
1360                 hpsa_scsi_interpret_error(c);
1361                 rc = -1;
1362         }
1363         cmd_special_free(h, c);
1364         return rc;
1365 }
1366
1367 static void hpsa_get_raid_level(struct ctlr_info *h,
1368         unsigned char *scsi3addr, unsigned char *raid_level)
1369 {
1370         int rc;
1371         unsigned char *buf;
1372
1373         *raid_level = RAID_UNKNOWN;
1374         buf = kzalloc(64, GFP_KERNEL);
1375         if (!buf)
1376                 return;
1377         rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0xC1, buf, 64);
1378         if (rc == 0)
1379                 *raid_level = buf[8];
1380         if (*raid_level > RAID_UNKNOWN)
1381                 *raid_level = RAID_UNKNOWN;
1382         kfree(buf);
1383         return;
1384 }
1385
1386 /* Get the device id from inquiry page 0x83 */
1387 static int hpsa_get_device_id(struct ctlr_info *h, unsigned char *scsi3addr,
1388         unsigned char *device_id, int buflen)
1389 {
1390         int rc;
1391         unsigned char *buf;
1392
1393         if (buflen > 16)
1394                 buflen = 16;
1395         buf = kzalloc(64, GFP_KERNEL);
1396         if (!buf)
1397                 return -1;
1398         rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0x83, buf, 64);
1399         if (rc == 0)
1400                 memcpy(device_id, &buf[8], buflen);
1401         kfree(buf);
1402         return rc != 0;
1403 }
1404
1405 static int hpsa_scsi_do_report_luns(struct ctlr_info *h, int logical,
1406                 struct ReportLUNdata *buf, int bufsize,
1407                 int extended_response)
1408 {
1409         int rc = IO_OK;
1410         struct CommandList *c;
1411         unsigned char scsi3addr[8];
1412         struct ErrorInfo *ei;
1413
1414         c = cmd_special_alloc(h);
1415         if (c == NULL) {                        /* trouble... */
1416                 dev_err(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
1417                 return -1;
1418         }
1419         /* address the controller */
1420         memset(scsi3addr, 0, sizeof(scsi3addr));
1421         fill_cmd(c, logical ? HPSA_REPORT_LOG : HPSA_REPORT_PHYS, h,
1422                 buf, bufsize, 0, scsi3addr, TYPE_CMD);
1423         if (extended_response)
1424                 c->Request.CDB[1] = extended_response;
1425         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
1426         ei = c->err_info;
1427         if (ei->CommandStatus != 0 &&
1428             ei->CommandStatus != CMD_DATA_UNDERRUN) {
1429                 hpsa_scsi_interpret_error(c);
1430                 rc = -1;
1431         }
1432         cmd_special_free(h, c);
1433         return rc;
1434 }
1435
1436 static inline int hpsa_scsi_do_report_phys_luns(struct ctlr_info *h,
1437                 struct ReportLUNdata *buf,
1438                 int bufsize, int extended_response)
1439 {
1440         return hpsa_scsi_do_report_luns(h, 0, buf, bufsize, extended_response);
1441 }
1442
1443 static inline int hpsa_scsi_do_report_log_luns(struct ctlr_info *h,
1444                 struct ReportLUNdata *buf, int bufsize)
1445 {
1446         return hpsa_scsi_do_report_luns(h, 1, buf, bufsize, 0);
1447 }
1448
1449 static inline void hpsa_set_bus_target_lun(struct hpsa_scsi_dev_t *device,
1450         int bus, int target, int lun)
1451 {
1452         device->bus = bus;
1453         device->target = target;
1454         device->lun = lun;
1455 }
1456
1457 static int hpsa_update_device_info(struct ctlr_info *h,
1458         unsigned char scsi3addr[], struct hpsa_scsi_dev_t *this_device)
1459 {
1460 #define OBDR_TAPE_INQ_SIZE 49
1461         unsigned char *inq_buff;
1462
1463         inq_buff = kzalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
1464         if (!inq_buff)
1465                 goto bail_out;
1466
1467         /* Do an inquiry to the device to see what it is. */
1468         if (hpsa_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
1469                 (unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
1470                 /* Inquiry failed (msg printed already) */
1471                 dev_err(&h->pdev->dev,
1472                         "hpsa_update_device_info: inquiry failed\n");
1473                 goto bail_out;
1474         }
1475
1476         /* As a side effect, record the firmware version number
1477          * if we happen to be talking to the RAID controller.
1478          */
1479         if (is_hba_lunid(scsi3addr))
1480                 memcpy(h->firm_ver, &inq_buff[32], 4);
1481
1482         this_device->devtype = (inq_buff[0] & 0x1f);
1483         memcpy(this_device->scsi3addr, scsi3addr, 8);
1484         memcpy(this_device->vendor, &inq_buff[8],
1485                 sizeof(this_device->vendor));
1486         memcpy(this_device->model, &inq_buff[16],
1487                 sizeof(this_device->model));
1488         memcpy(this_device->revision, &inq_buff[32],
1489                 sizeof(this_device->revision));
1490         memset(this_device->device_id, 0,
1491                 sizeof(this_device->device_id));
1492         hpsa_get_device_id(h, scsi3addr, this_device->device_id,
1493                 sizeof(this_device->device_id));
1494
1495         if (this_device->devtype == TYPE_DISK &&
1496                 is_logical_dev_addr_mode(scsi3addr))
1497                 hpsa_get_raid_level(h, scsi3addr, &this_device->raid_level);
1498         else
1499                 this_device->raid_level = RAID_UNKNOWN;
1500
1501         kfree(inq_buff);
1502         return 0;
1503
1504 bail_out:
1505         kfree(inq_buff);
1506         return 1;
1507 }
1508
1509 static unsigned char *msa2xxx_model[] = {
1510         "MSA2012",
1511         "MSA2024",
1512         "MSA2312",
1513         "MSA2324",
1514         NULL,
1515 };
1516
1517 static int is_msa2xxx(struct ctlr_info *h, struct hpsa_scsi_dev_t *device)
1518 {
1519         int i;
1520
1521         for (i = 0; msa2xxx_model[i]; i++)
1522                 if (strncmp(device->model, msa2xxx_model[i],
1523                         strlen(msa2xxx_model[i])) == 0)
1524                         return 1;
1525         return 0;
1526 }
1527
1528 /* Helper function to assign bus, target, lun mapping of devices.
1529  * Puts non-msa2xxx logical volumes on bus 0, msa2xxx logical
1530  * volumes on bus 1, physical devices on bus 2. and the hba on bus 3.
1531  * Logical drive target and lun are assigned at this time, but
1532  * physical device lun and target assignment are deferred (assigned
1533  * in hpsa_find_target_lun, called by hpsa_scsi_add_entry.)
1534  */
1535 static void figure_bus_target_lun(struct ctlr_info *h,
1536         u8 *lunaddrbytes, int *bus, int *target, int *lun,
1537         struct hpsa_scsi_dev_t *device)
1538 {
1539         u32 lunid;
1540
1541         if (is_logical_dev_addr_mode(lunaddrbytes)) {
1542                 /* logical device */
1543                 if (unlikely(is_scsi_rev_5(h))) {
1544                         /* p1210m, logical drives lun assignments
1545                          * match SCSI REPORT LUNS data.
1546                          */
1547                         lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
1548                         *bus = 0;
1549                         *target = 0;
1550                         *lun = (lunid & 0x3fff) + 1;
1551                 } else {
1552                         /* not p1210m... */
1553                         lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
1554                         if (is_msa2xxx(h, device)) {
1555                                 /* msa2xxx way, put logicals on bus 1
1556                                  * and match target/lun numbers box
1557                                  * reports.
1558                                  */
1559                                 *bus = 1;
1560                                 *target = (lunid >> 16) & 0x3fff;
1561                                 *lun = lunid & 0x00ff;
1562                         } else {
1563                                 /* Traditional smart array way. */
1564                                 *bus = 0;
1565                                 *lun = 0;
1566                                 *target = lunid & 0x3fff;
1567                         }
1568                 }
1569         } else {
1570                 /* physical device */
1571                 if (is_hba_lunid(lunaddrbytes))
1572                         if (unlikely(is_scsi_rev_5(h))) {
1573                                 *bus = 0; /* put p1210m ctlr at 0,0,0 */
1574                                 *target = 0;
1575                                 *lun = 0;
1576                                 return;
1577                         } else
1578                                 *bus = 3; /* traditional smartarray */
1579                 else
1580                         *bus = 2; /* physical disk */
1581                 *target = -1;
1582                 *lun = -1; /* we will fill these in later. */
1583         }
1584 }
1585
1586 /*
1587  * If there is no lun 0 on a target, linux won't find any devices.
1588  * For the MSA2xxx boxes, we have to manually detect the enclosure
1589  * which is at lun zero, as CCISS_REPORT_PHYSICAL_LUNS doesn't report
1590  * it for some reason.  *tmpdevice is the target we're adding,
1591  * this_device is a pointer into the current element of currentsd[]
1592  * that we're building up in update_scsi_devices(), below.
1593  * lunzerobits is a bitmap that tracks which targets already have a
1594  * lun 0 assigned.
1595  * Returns 1 if an enclosure was added, 0 if not.
1596  */
1597 static int add_msa2xxx_enclosure_device(struct ctlr_info *h,
1598         struct hpsa_scsi_dev_t *tmpdevice,
1599         struct hpsa_scsi_dev_t *this_device, u8 *lunaddrbytes,
1600         int bus, int target, int lun, unsigned long lunzerobits[],
1601         int *nmsa2xxx_enclosures)
1602 {
1603         unsigned char scsi3addr[8];
1604
1605         if (test_bit(target, lunzerobits))
1606                 return 0; /* There is already a lun 0 on this target. */
1607
1608         if (!is_logical_dev_addr_mode(lunaddrbytes))
1609                 return 0; /* It's the logical targets that may lack lun 0. */
1610
1611         if (!is_msa2xxx(h, tmpdevice))
1612                 return 0; /* It's only the MSA2xxx that have this problem. */
1613
1614         if (lun == 0) /* if lun is 0, then obviously we have a lun 0. */
1615                 return 0;
1616
1617         if (is_hba_lunid(scsi3addr))
1618                 return 0; /* Don't add the RAID controller here. */
1619
1620         if (is_scsi_rev_5(h))
1621                 return 0; /* p1210m doesn't need to do this. */
1622
1623 #define MAX_MSA2XXX_ENCLOSURES 32
1624         if (*nmsa2xxx_enclosures >= MAX_MSA2XXX_ENCLOSURES) {
1625                 dev_warn(&h->pdev->dev, "Maximum number of MSA2XXX "
1626                         "enclosures exceeded.  Check your hardware "
1627                         "configuration.");
1628                 return 0;
1629         }
1630
1631         memset(scsi3addr, 0, 8);
1632         scsi3addr[3] = target;
1633         if (hpsa_update_device_info(h, scsi3addr, this_device))
1634                 return 0;
1635         (*nmsa2xxx_enclosures)++;
1636         hpsa_set_bus_target_lun(this_device, bus, target, 0);
1637         set_bit(target, lunzerobits);
1638         return 1;
1639 }
1640
1641 /*
1642  * Do CISS_REPORT_PHYS and CISS_REPORT_LOG.  Data is returned in physdev,
1643  * logdev.  The number of luns in physdev and logdev are returned in
1644  * *nphysicals and *nlogicals, respectively.
1645  * Returns 0 on success, -1 otherwise.
1646  */
1647 static int hpsa_gather_lun_info(struct ctlr_info *h,
1648         int reportlunsize,
1649         struct ReportLUNdata *physdev, u32 *nphysicals,
1650         struct ReportLUNdata *logdev, u32 *nlogicals)
1651 {
1652         if (hpsa_scsi_do_report_phys_luns(h, physdev, reportlunsize, 0)) {
1653                 dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
1654                 return -1;
1655         }
1656         *nphysicals = be32_to_cpu(*((__be32 *)physdev->LUNListLength)) / 8;
1657         if (*nphysicals > HPSA_MAX_PHYS_LUN) {
1658                 dev_warn(&h->pdev->dev, "maximum physical LUNs (%d) exceeded."
1659                         "  %d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
1660                         *nphysicals - HPSA_MAX_PHYS_LUN);
1661                 *nphysicals = HPSA_MAX_PHYS_LUN;
1662         }
1663         if (hpsa_scsi_do_report_log_luns(h, logdev, reportlunsize)) {
1664                 dev_err(&h->pdev->dev, "report logical LUNs failed.\n");
1665                 return -1;
1666         }
1667         *nlogicals = be32_to_cpu(*((__be32 *) logdev->LUNListLength)) / 8;
1668         /* Reject Logicals in excess of our max capability. */
1669         if (*nlogicals > HPSA_MAX_LUN) {
1670                 dev_warn(&h->pdev->dev,
1671                         "maximum logical LUNs (%d) exceeded.  "
1672                         "%d LUNs ignored.\n", HPSA_MAX_LUN,
1673                         *nlogicals - HPSA_MAX_LUN);
1674                         *nlogicals = HPSA_MAX_LUN;
1675         }
1676         if (*nlogicals + *nphysicals > HPSA_MAX_PHYS_LUN) {
1677                 dev_warn(&h->pdev->dev,
1678                         "maximum logical + physical LUNs (%d) exceeded. "
1679                         "%d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
1680                         *nphysicals + *nlogicals - HPSA_MAX_PHYS_LUN);
1681                 *nlogicals = HPSA_MAX_PHYS_LUN - *nphysicals;
1682         }
1683         return 0;
1684 }
1685
1686 u8 *figure_lunaddrbytes(struct ctlr_info *h, int raid_ctlr_position, int i,
1687         int nphysicals, int nlogicals, struct ReportLUNdata *physdev_list,
1688         struct ReportLUNdata *logdev_list)
1689 {
1690         /* Helper function, figure out where the LUN ID info is coming from
1691          * given index i, lists of physical and logical devices, where in
1692          * the list the raid controller is supposed to appear (first or last)
1693          */
1694
1695         int logicals_start = nphysicals + (raid_ctlr_position == 0);
1696         int last_device = nphysicals + nlogicals + (raid_ctlr_position == 0);
1697
1698         if (i == raid_ctlr_position)
1699                 return RAID_CTLR_LUNID;
1700
1701         if (i < logicals_start)
1702                 return &physdev_list->LUN[i - (raid_ctlr_position == 0)][0];
1703
1704         if (i < last_device)
1705                 return &logdev_list->LUN[i - nphysicals -
1706                         (raid_ctlr_position == 0)][0];
1707         BUG();
1708         return NULL;
1709 }
1710
1711 static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno)
1712 {
1713         /* the idea here is we could get notified
1714          * that some devices have changed, so we do a report
1715          * physical luns and report logical luns cmd, and adjust
1716          * our list of devices accordingly.
1717          *
1718          * The scsi3addr's of devices won't change so long as the
1719          * adapter is not reset.  That means we can rescan and
1720          * tell which devices we already know about, vs. new
1721          * devices, vs.  disappearing devices.
1722          */
1723         struct ReportLUNdata *physdev_list = NULL;
1724         struct ReportLUNdata *logdev_list = NULL;
1725         unsigned char *inq_buff = NULL;
1726         u32 nphysicals = 0;
1727         u32 nlogicals = 0;
1728         u32 ndev_allocated = 0;
1729         struct hpsa_scsi_dev_t **currentsd, *this_device, *tmpdevice;
1730         int ncurrent = 0;
1731         int reportlunsize = sizeof(*physdev_list) + HPSA_MAX_PHYS_LUN * 8;
1732         int i, nmsa2xxx_enclosures, ndevs_to_allocate;
1733         int bus, target, lun;
1734         int raid_ctlr_position;
1735         DECLARE_BITMAP(lunzerobits, HPSA_MAX_TARGETS_PER_CTLR);
1736
1737         currentsd = kzalloc(sizeof(*currentsd) * HPSA_MAX_SCSI_DEVS_PER_HBA,
1738                 GFP_KERNEL);
1739         physdev_list = kzalloc(reportlunsize, GFP_KERNEL);
1740         logdev_list = kzalloc(reportlunsize, GFP_KERNEL);
1741         inq_buff = kmalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
1742         tmpdevice = kzalloc(sizeof(*tmpdevice), GFP_KERNEL);
1743
1744         if (!currentsd || !physdev_list || !logdev_list ||
1745                 !inq_buff || !tmpdevice) {
1746                 dev_err(&h->pdev->dev, "out of memory\n");
1747                 goto out;
1748         }
1749         memset(lunzerobits, 0, sizeof(lunzerobits));
1750
1751         if (hpsa_gather_lun_info(h, reportlunsize, physdev_list, &nphysicals,
1752                         logdev_list, &nlogicals))
1753                 goto out;
1754
1755         /* We might see up to 32 MSA2xxx enclosures, actually 8 of them
1756          * but each of them 4 times through different paths.  The plus 1
1757          * is for the RAID controller.
1758          */
1759         ndevs_to_allocate = nphysicals + nlogicals + MAX_MSA2XXX_ENCLOSURES + 1;
1760
1761         /* Allocate the per device structures */
1762         for (i = 0; i < ndevs_to_allocate; i++) {
1763                 currentsd[i] = kzalloc(sizeof(*currentsd[i]), GFP_KERNEL);
1764                 if (!currentsd[i]) {
1765                         dev_warn(&h->pdev->dev, "out of memory at %s:%d\n",
1766                                 __FILE__, __LINE__);
1767                         goto out;
1768                 }
1769                 ndev_allocated++;
1770         }
1771
1772         if (unlikely(is_scsi_rev_5(h)))
1773                 raid_ctlr_position = 0;
1774         else
1775                 raid_ctlr_position = nphysicals + nlogicals;
1776
1777         /* adjust our table of devices */
1778         nmsa2xxx_enclosures = 0;
1779         for (i = 0; i < nphysicals + nlogicals + 1; i++) {
1780                 u8 *lunaddrbytes;
1781
1782                 /* Figure out where the LUN ID info is coming from */
1783                 lunaddrbytes = figure_lunaddrbytes(h, raid_ctlr_position,
1784                         i, nphysicals, nlogicals, physdev_list, logdev_list);
1785                 /* skip masked physical devices. */
1786                 if (lunaddrbytes[3] & 0xC0 &&
1787                         i < nphysicals + (raid_ctlr_position == 0))
1788                         continue;
1789
1790                 /* Get device type, vendor, model, device id */
1791                 if (hpsa_update_device_info(h, lunaddrbytes, tmpdevice))
1792                         continue; /* skip it if we can't talk to it. */
1793                 figure_bus_target_lun(h, lunaddrbytes, &bus, &target, &lun,
1794                         tmpdevice);
1795                 this_device = currentsd[ncurrent];
1796
1797                 /*
1798                  * For the msa2xxx boxes, we have to insert a LUN 0 which
1799                  * doesn't show up in CCISS_REPORT_PHYSICAL data, but there
1800                  * is nonetheless an enclosure device there.  We have to
1801                  * present that otherwise linux won't find anything if
1802                  * there is no lun 0.
1803                  */
1804                 if (add_msa2xxx_enclosure_device(h, tmpdevice, this_device,
1805                                 lunaddrbytes, bus, target, lun, lunzerobits,
1806                                 &nmsa2xxx_enclosures)) {
1807                         ncurrent++;
1808                         this_device = currentsd[ncurrent];
1809                 }
1810
1811                 *this_device = *tmpdevice;
1812                 hpsa_set_bus_target_lun(this_device, bus, target, lun);
1813
1814                 switch (this_device->devtype) {
1815                 case TYPE_ROM: {
1816                         /* We don't *really* support actual CD-ROM devices,
1817                          * just "One Button Disaster Recovery" tape drive
1818                          * which temporarily pretends to be a CD-ROM drive.
1819                          * So we check that the device is really an OBDR tape
1820                          * device by checking for "$DR-10" in bytes 43-48 of
1821                          * the inquiry data.
1822                          */
1823                                 char obdr_sig[7];
1824 #define OBDR_TAPE_SIG "$DR-10"
1825                                 strncpy(obdr_sig, &inq_buff[43], 6);
1826                                 obdr_sig[6] = '\0';
1827                                 if (strncmp(obdr_sig, OBDR_TAPE_SIG, 6) != 0)
1828                                         /* Not OBDR device, ignore it. */
1829                                         break;
1830                         }
1831                         ncurrent++;
1832                         break;
1833                 case TYPE_DISK:
1834                         if (i < nphysicals)
1835                                 break;
1836                         ncurrent++;
1837                         break;
1838                 case TYPE_TAPE:
1839                 case TYPE_MEDIUM_CHANGER:
1840                         ncurrent++;
1841                         break;
1842                 case TYPE_RAID:
1843                         /* Only present the Smartarray HBA as a RAID controller.
1844                          * If it's a RAID controller other than the HBA itself
1845                          * (an external RAID controller, MSA500 or similar)
1846                          * don't present it.
1847                          */
1848                         if (!is_hba_lunid(lunaddrbytes))
1849                                 break;
1850                         ncurrent++;
1851                         break;
1852                 default:
1853                         break;
1854                 }
1855                 if (ncurrent >= HPSA_MAX_SCSI_DEVS_PER_HBA)
1856                         break;
1857         }
1858         adjust_hpsa_scsi_table(h, hostno, currentsd, ncurrent);
1859 out:
1860         kfree(tmpdevice);
1861         for (i = 0; i < ndev_allocated; i++)
1862                 kfree(currentsd[i]);
1863         kfree(currentsd);
1864         kfree(inq_buff);
1865         kfree(physdev_list);
1866         kfree(logdev_list);
1867 }
1868
1869 /* hpsa_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
1870  * dma mapping  and fills in the scatter gather entries of the
1871  * hpsa command, cp.
1872  */
1873 static int hpsa_scatter_gather(struct pci_dev *pdev,
1874                 struct CommandList *cp,
1875                 struct scsi_cmnd *cmd)
1876 {
1877         unsigned int len;
1878         struct scatterlist *sg;
1879         u64 addr64;
1880         int use_sg, i;
1881
1882         BUG_ON(scsi_sg_count(cmd) > MAXSGENTRIES);
1883
1884         use_sg = scsi_dma_map(cmd);
1885         if (use_sg < 0)
1886                 return use_sg;
1887
1888         if (!use_sg)
1889                 goto sglist_finished;
1890
1891         scsi_for_each_sg(cmd, sg, use_sg, i) {
1892                 addr64 = (u64) sg_dma_address(sg);
1893                 len  = sg_dma_len(sg);
1894                 cp->SG[i].Addr.lower =
1895                         (u32) (addr64 & (u64) 0x00000000FFFFFFFF);
1896                 cp->SG[i].Addr.upper =
1897                         (u32) ((addr64 >> 32) & (u64) 0x00000000FFFFFFFF);
1898                 cp->SG[i].Len = len;
1899                 cp->SG[i].Ext = 0;  /* we are not chaining */
1900         }
1901
1902 sglist_finished:
1903
1904         cp->Header.SGList = (u8) use_sg;   /* no. SGs contig in this cmd */
1905         cp->Header.SGTotal = (u16) use_sg; /* total sgs in this cmd list */
1906         return 0;
1907 }
1908
1909
1910 static int hpsa_scsi_queue_command(struct scsi_cmnd *cmd,
1911         void (*done)(struct scsi_cmnd *))
1912 {
1913         struct ctlr_info *h;
1914         struct hpsa_scsi_dev_t *dev;
1915         unsigned char scsi3addr[8];
1916         struct CommandList *c;
1917         unsigned long flags;
1918
1919         /* Get the ptr to our adapter structure out of cmd->host. */
1920         h = sdev_to_hba(cmd->device);
1921         dev = cmd->device->hostdata;
1922         if (!dev) {
1923                 cmd->result = DID_NO_CONNECT << 16;
1924                 done(cmd);
1925                 return 0;
1926         }
1927         memcpy(scsi3addr, dev->scsi3addr, sizeof(scsi3addr));
1928
1929         /* Need a lock as this is being allocated from the pool */
1930         spin_lock_irqsave(&h->lock, flags);
1931         c = cmd_alloc(h);
1932         spin_unlock_irqrestore(&h->lock, flags);
1933         if (c == NULL) {                        /* trouble... */
1934                 dev_err(&h->pdev->dev, "cmd_alloc returned NULL!\n");
1935                 return SCSI_MLQUEUE_HOST_BUSY;
1936         }
1937
1938         /* Fill in the command list header */
1939
1940         cmd->scsi_done = done;    /* save this for use by completion code */
1941
1942         /* save c in case we have to abort it  */
1943         cmd->host_scribble = (unsigned char *) c;
1944
1945         c->cmd_type = CMD_SCSI;
1946         c->scsi_cmd = cmd;
1947         c->Header.ReplyQueue = 0;  /* unused in simple mode */
1948         memcpy(&c->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
1949         c->Header.Tag.lower = (c->cmdindex << DIRECT_LOOKUP_SHIFT);
1950         c->Header.Tag.lower |= DIRECT_LOOKUP_BIT;
1951
1952         /* Fill in the request block... */
1953
1954         c->Request.Timeout = 0;
1955         memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
1956         BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
1957         c->Request.CDBLen = cmd->cmd_len;
1958         memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
1959         c->Request.Type.Type = TYPE_CMD;
1960         c->Request.Type.Attribute = ATTR_SIMPLE;
1961         switch (cmd->sc_data_direction) {
1962         case DMA_TO_DEVICE:
1963                 c->Request.Type.Direction = XFER_WRITE;
1964                 break;
1965         case DMA_FROM_DEVICE:
1966                 c->Request.Type.Direction = XFER_READ;
1967                 break;
1968         case DMA_NONE:
1969                 c->Request.Type.Direction = XFER_NONE;
1970                 break;
1971         case DMA_BIDIRECTIONAL:
1972                 /* This can happen if a buggy application does a scsi passthru
1973                  * and sets both inlen and outlen to non-zero. ( see
1974                  * ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
1975                  */
1976
1977                 c->Request.Type.Direction = XFER_RSVD;
1978                 /* This is technically wrong, and hpsa controllers should
1979                  * reject it with CMD_INVALID, which is the most correct
1980                  * response, but non-fibre backends appear to let it
1981                  * slide by, and give the same results as if this field
1982                  * were set correctly.  Either way is acceptable for
1983                  * our purposes here.
1984                  */
1985
1986                 break;
1987
1988         default:
1989                 dev_err(&h->pdev->dev, "unknown data direction: %d\n",
1990                         cmd->sc_data_direction);
1991                 BUG();
1992                 break;
1993         }
1994
1995         if (hpsa_scatter_gather(h->pdev, c, cmd) < 0) { /* Fill SG list */
1996                 cmd_free(h, c);
1997                 return SCSI_MLQUEUE_HOST_BUSY;
1998         }
1999         enqueue_cmd_and_start_io(h, c);
2000         /* the cmd'll come back via intr handler in complete_scsi_command()  */
2001         return 0;
2002 }
2003
2004 static void hpsa_unregister_scsi(struct ctlr_info *h)
2005 {
2006         /* we are being forcibly unloaded, and may not refuse. */
2007         scsi_remove_host(h->scsi_host);
2008         scsi_host_put(h->scsi_host);
2009         h->scsi_host = NULL;
2010 }
2011
2012 static int hpsa_register_scsi(struct ctlr_info *h)
2013 {
2014         int rc;
2015
2016         hpsa_update_scsi_devices(h, -1);
2017         rc = hpsa_scsi_detect(h);
2018         if (rc != 0)
2019                 dev_err(&h->pdev->dev, "hpsa_register_scsi: failed"
2020                         " hpsa_scsi_detect(), rc is %d\n", rc);
2021         return rc;
2022 }
2023
2024 static int wait_for_device_to_become_ready(struct ctlr_info *h,
2025         unsigned char lunaddr[])
2026 {
2027         int rc = 0;
2028         int count = 0;
2029         int waittime = 1; /* seconds */
2030         struct CommandList *c;
2031
2032         c = cmd_special_alloc(h);
2033         if (!c) {
2034                 dev_warn(&h->pdev->dev, "out of memory in "
2035                         "wait_for_device_to_become_ready.\n");
2036                 return IO_ERROR;
2037         }
2038
2039         /* Send test unit ready until device ready, or give up. */
2040         while (count < HPSA_TUR_RETRY_LIMIT) {
2041
2042                 /* Wait for a bit.  do this first, because if we send
2043                  * the TUR right away, the reset will just abort it.
2044                  */
2045                 msleep(1000 * waittime);
2046                 count++;
2047
2048                 /* Increase wait time with each try, up to a point. */
2049                 if (waittime < HPSA_MAX_WAIT_INTERVAL_SECS)
2050                         waittime = waittime * 2;
2051
2052                 /* Send the Test Unit Ready */
2053                 fill_cmd(c, TEST_UNIT_READY, h, NULL, 0, 0, lunaddr, TYPE_CMD);
2054                 hpsa_scsi_do_simple_cmd_core(h, c);
2055                 /* no unmap needed here because no data xfer. */
2056
2057                 if (c->err_info->CommandStatus == CMD_SUCCESS)
2058                         break;
2059
2060                 if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
2061                         c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION &&
2062                         (c->err_info->SenseInfo[2] == NO_SENSE ||
2063                         c->err_info->SenseInfo[2] == UNIT_ATTENTION))
2064                         break;
2065
2066                 dev_warn(&h->pdev->dev, "waiting %d secs "
2067                         "for device to become ready.\n", waittime);
2068                 rc = 1; /* device not ready. */
2069         }
2070
2071         if (rc)
2072                 dev_warn(&h->pdev->dev, "giving up on device.\n");
2073         else
2074                 dev_warn(&h->pdev->dev, "device is ready.\n");
2075
2076         cmd_special_free(h, c);
2077         return rc;
2078 }
2079
2080 /* Need at least one of these error handlers to keep ../scsi/hosts.c from
2081  * complaining.  Doing a host- or bus-reset can't do anything good here.
2082  */
2083 static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
2084 {
2085         int rc;
2086         struct ctlr_info *h;
2087         struct hpsa_scsi_dev_t *dev;
2088
2089         /* find the controller to which the command to be aborted was sent */
2090         h = sdev_to_hba(scsicmd->device);
2091         if (h == NULL) /* paranoia */
2092                 return FAILED;
2093         dev_warn(&h->pdev->dev, "resetting drive\n");
2094
2095         dev = scsicmd->device->hostdata;
2096         if (!dev) {
2097                 dev_err(&h->pdev->dev, "hpsa_eh_device_reset_handler: "
2098                         "device lookup failed.\n");
2099                 return FAILED;
2100         }
2101         /* send a reset to the SCSI LUN which the command was sent to */
2102         rc = hpsa_send_reset(h, dev->scsi3addr);
2103         if (rc == 0 && wait_for_device_to_become_ready(h, dev->scsi3addr) == 0)
2104                 return SUCCESS;
2105
2106         dev_warn(&h->pdev->dev, "resetting device failed.\n");
2107         return FAILED;
2108 }
2109
2110 /*
2111  * For operations that cannot sleep, a command block is allocated at init,
2112  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
2113  * which ones are free or in use.  Lock must be held when calling this.
2114  * cmd_free() is the complement.
2115  */
2116 static struct CommandList *cmd_alloc(struct ctlr_info *h)
2117 {
2118         struct CommandList *c;
2119         int i;
2120         union u64bit temp64;
2121         dma_addr_t cmd_dma_handle, err_dma_handle;
2122
2123         do {
2124                 i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
2125                 if (i == h->nr_cmds)
2126                         return NULL;
2127         } while (test_and_set_bit
2128                  (i & (BITS_PER_LONG - 1),
2129                   h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
2130         c = h->cmd_pool + i;
2131         memset(c, 0, sizeof(*c));
2132         cmd_dma_handle = h->cmd_pool_dhandle
2133             + i * sizeof(*c);
2134         c->err_info = h->errinfo_pool + i;
2135         memset(c->err_info, 0, sizeof(*c->err_info));
2136         err_dma_handle = h->errinfo_pool_dhandle
2137             + i * sizeof(*c->err_info);
2138         h->nr_allocs++;
2139
2140         c->cmdindex = i;
2141
2142         INIT_HLIST_NODE(&c->list);
2143         c->busaddr = (u32) cmd_dma_handle;
2144         temp64.val = (u64) err_dma_handle;
2145         c->ErrDesc.Addr.lower = temp64.val32.lower;
2146         c->ErrDesc.Addr.upper = temp64.val32.upper;
2147         c->ErrDesc.Len = sizeof(*c->err_info);
2148
2149         c->h = h;
2150         return c;
2151 }
2152
2153 /* For operations that can wait for kmalloc to possibly sleep,
2154  * this routine can be called. Lock need not be held to call
2155  * cmd_special_alloc. cmd_special_free() is the complement.
2156  */
2157 static struct CommandList *cmd_special_alloc(struct ctlr_info *h)
2158 {
2159         struct CommandList *c;
2160         union u64bit temp64;
2161         dma_addr_t cmd_dma_handle, err_dma_handle;
2162
2163         c = pci_alloc_consistent(h->pdev, sizeof(*c), &cmd_dma_handle);
2164         if (c == NULL)
2165                 return NULL;
2166         memset(c, 0, sizeof(*c));
2167
2168         c->cmdindex = -1;
2169
2170         c->err_info = pci_alloc_consistent(h->pdev, sizeof(*c->err_info),
2171                     &err_dma_handle);
2172
2173         if (c->err_info == NULL) {
2174                 pci_free_consistent(h->pdev,
2175                         sizeof(*c), c, cmd_dma_handle);
2176                 return NULL;
2177         }
2178         memset(c->err_info, 0, sizeof(*c->err_info));
2179
2180         INIT_HLIST_NODE(&c->list);
2181         c->busaddr = (u32) cmd_dma_handle;
2182         temp64.val = (u64) err_dma_handle;
2183         c->ErrDesc.Addr.lower = temp64.val32.lower;
2184         c->ErrDesc.Addr.upper = temp64.val32.upper;
2185         c->ErrDesc.Len = sizeof(*c->err_info);
2186
2187         c->h = h;
2188         return c;
2189 }
2190
2191 static void cmd_free(struct ctlr_info *h, struct CommandList *c)
2192 {
2193         int i;
2194
2195         i = c - h->cmd_pool;
2196         clear_bit(i & (BITS_PER_LONG - 1),
2197                   h->cmd_pool_bits + (i / BITS_PER_LONG));
2198         h->nr_frees++;
2199 }
2200
2201 static void cmd_special_free(struct ctlr_info *h, struct CommandList *c)
2202 {
2203         union u64bit temp64;
2204
2205         temp64.val32.lower = c->ErrDesc.Addr.lower;
2206         temp64.val32.upper = c->ErrDesc.Addr.upper;
2207         pci_free_consistent(h->pdev, sizeof(*c->err_info),
2208                             c->err_info, (dma_addr_t) temp64.val);
2209         pci_free_consistent(h->pdev, sizeof(*c),
2210                             c, (dma_addr_t) c->busaddr);
2211 }
2212
2213 #ifdef CONFIG_COMPAT
2214
2215 static int do_ioctl(struct scsi_device *dev, int cmd, void *arg)
2216 {
2217         int ret;
2218
2219         lock_kernel();
2220         ret = hpsa_ioctl(dev, cmd, arg);
2221         unlock_kernel();
2222         return ret;
2223 }
2224
2225 static int hpsa_ioctl32_passthru(struct scsi_device *dev, int cmd, void *arg);
2226 static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
2227         int cmd, void *arg);
2228
2229 static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg)
2230 {
2231         switch (cmd) {
2232         case CCISS_GETPCIINFO:
2233         case CCISS_GETINTINFO:
2234         case CCISS_SETINTINFO:
2235         case CCISS_GETNODENAME:
2236         case CCISS_SETNODENAME:
2237         case CCISS_GETHEARTBEAT:
2238         case CCISS_GETBUSTYPES:
2239         case CCISS_GETFIRMVER:
2240         case CCISS_GETDRIVVER:
2241         case CCISS_REVALIDVOLS:
2242         case CCISS_DEREGDISK:
2243         case CCISS_REGNEWDISK:
2244         case CCISS_REGNEWD:
2245         case CCISS_RESCANDISK:
2246         case CCISS_GETLUNINFO:
2247                 return do_ioctl(dev, cmd, arg);
2248
2249         case CCISS_PASSTHRU32:
2250                 return hpsa_ioctl32_passthru(dev, cmd, arg);
2251         case CCISS_BIG_PASSTHRU32:
2252                 return hpsa_ioctl32_big_passthru(dev, cmd, arg);
2253
2254         default:
2255                 return -ENOIOCTLCMD;
2256         }
2257 }
2258
2259 static int hpsa_ioctl32_passthru(struct scsi_device *dev, int cmd, void *arg)
2260 {
2261         IOCTL32_Command_struct __user *arg32 =
2262             (IOCTL32_Command_struct __user *) arg;
2263         IOCTL_Command_struct arg64;
2264         IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
2265         int err;
2266         u32 cp;
2267
2268         err = 0;
2269         err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
2270                            sizeof(arg64.LUN_info));
2271         err |= copy_from_user(&arg64.Request, &arg32->Request,
2272                            sizeof(arg64.Request));
2273         err |= copy_from_user(&arg64.error_info, &arg32->error_info,
2274                            sizeof(arg64.error_info));
2275         err |= get_user(arg64.buf_size, &arg32->buf_size);
2276         err |= get_user(cp, &arg32->buf);
2277         arg64.buf = compat_ptr(cp);
2278         err |= copy_to_user(p, &arg64, sizeof(arg64));
2279
2280         if (err)
2281                 return -EFAULT;
2282
2283         err = do_ioctl(dev, CCISS_PASSTHRU, (void *)p);
2284         if (err)
2285                 return err;
2286         err |= copy_in_user(&arg32->error_info, &p->error_info,
2287                          sizeof(arg32->error_info));
2288         if (err)
2289                 return -EFAULT;
2290         return err;
2291 }
2292
2293 static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
2294         int cmd, void *arg)
2295 {
2296         BIG_IOCTL32_Command_struct __user *arg32 =
2297             (BIG_IOCTL32_Command_struct __user *) arg;
2298         BIG_IOCTL_Command_struct arg64;
2299         BIG_IOCTL_Command_struct __user *p =
2300             compat_alloc_user_space(sizeof(arg64));
2301         int err;
2302         u32 cp;
2303
2304         err = 0;
2305         err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
2306                            sizeof(arg64.LUN_info));
2307         err |= copy_from_user(&arg64.Request, &arg32->Request,
2308                            sizeof(arg64.Request));
2309         err |= copy_from_user(&arg64.error_info, &arg32->error_info,
2310                            sizeof(arg64.error_info));
2311         err |= get_user(arg64.buf_size, &arg32->buf_size);
2312         err |= get_user(arg64.malloc_size, &arg32->malloc_size);
2313         err |= get_user(cp, &arg32->buf);
2314         arg64.buf = compat_ptr(cp);
2315         err |= copy_to_user(p, &arg64, sizeof(arg64));
2316
2317         if (err)
2318                 return -EFAULT;
2319
2320         err = do_ioctl(dev, CCISS_BIG_PASSTHRU, (void *)p);
2321         if (err)
2322                 return err;
2323         err |= copy_in_user(&arg32->error_info, &p->error_info,
2324                          sizeof(arg32->error_info));
2325         if (err)
2326                 return -EFAULT;
2327         return err;
2328 }
2329 #endif
2330
2331 static int hpsa_getpciinfo_ioctl(struct ctlr_info *h, void __user *argp)
2332 {
2333         struct hpsa_pci_info pciinfo;
2334
2335         if (!argp)
2336                 return -EINVAL;
2337         pciinfo.domain = pci_domain_nr(h->pdev->bus);
2338         pciinfo.bus = h->pdev->bus->number;
2339         pciinfo.dev_fn = h->pdev->devfn;
2340         pciinfo.board_id = h->board_id;
2341         if (copy_to_user(argp, &pciinfo, sizeof(pciinfo)))
2342                 return -EFAULT;
2343         return 0;
2344 }
2345
2346 static int hpsa_getdrivver_ioctl(struct ctlr_info *h, void __user *argp)
2347 {
2348         DriverVer_type DriverVer;
2349         unsigned char vmaj, vmin, vsubmin;
2350         int rc;
2351
2352         rc = sscanf(HPSA_DRIVER_VERSION, "%hhu.%hhu.%hhu",
2353                 &vmaj, &vmin, &vsubmin);
2354         if (rc != 3) {
2355                 dev_info(&h->pdev->dev, "driver version string '%s' "
2356                         "unrecognized.", HPSA_DRIVER_VERSION);
2357                 vmaj = 0;
2358                 vmin = 0;
2359                 vsubmin = 0;
2360         }
2361         DriverVer = (vmaj << 16) | (vmin << 8) | vsubmin;
2362         if (!argp)
2363                 return -EINVAL;
2364         if (copy_to_user(argp, &DriverVer, sizeof(DriverVer_type)))
2365                 return -EFAULT;
2366         return 0;
2367 }
2368
2369 static int hpsa_passthru_ioctl(struct ctlr_info *h, void __user *argp)
2370 {
2371         IOCTL_Command_struct iocommand;
2372         struct CommandList *c;
2373         char *buff = NULL;
2374         union u64bit temp64;
2375
2376         if (!argp)
2377                 return -EINVAL;
2378         if (!capable(CAP_SYS_RAWIO))
2379                 return -EPERM;
2380         if (copy_from_user(&iocommand, argp, sizeof(iocommand)))
2381                 return -EFAULT;
2382         if ((iocommand.buf_size < 1) &&
2383             (iocommand.Request.Type.Direction != XFER_NONE)) {
2384                 return -EINVAL;
2385         }
2386         if (iocommand.buf_size > 0) {
2387                 buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
2388                 if (buff == NULL)
2389                         return -EFAULT;
2390         }
2391         if (iocommand.Request.Type.Direction == XFER_WRITE) {
2392                 /* Copy the data into the buffer we created */
2393                 if (copy_from_user(buff, iocommand.buf, iocommand.buf_size)) {
2394                         kfree(buff);
2395                         return -EFAULT;
2396                 }
2397         } else
2398                 memset(buff, 0, iocommand.buf_size);
2399         c = cmd_special_alloc(h);
2400         if (c == NULL) {
2401                 kfree(buff);
2402                 return -ENOMEM;
2403         }
2404         /* Fill in the command type */
2405         c->cmd_type = CMD_IOCTL_PEND;
2406         /* Fill in Command Header */
2407         c->Header.ReplyQueue = 0; /* unused in simple mode */
2408         if (iocommand.buf_size > 0) {   /* buffer to fill */
2409                 c->Header.SGList = 1;
2410                 c->Header.SGTotal = 1;
2411         } else  { /* no buffers to fill */
2412                 c->Header.SGList = 0;
2413                 c->Header.SGTotal = 0;
2414         }
2415         memcpy(&c->Header.LUN, &iocommand.LUN_info, sizeof(c->Header.LUN));
2416         /* use the kernel address the cmd block for tag */
2417         c->Header.Tag.lower = c->busaddr;
2418
2419         /* Fill in Request block */
2420         memcpy(&c->Request, &iocommand.Request,
2421                 sizeof(c->Request));
2422
2423         /* Fill in the scatter gather information */
2424         if (iocommand.buf_size > 0) {
2425                 temp64.val = pci_map_single(h->pdev, buff,
2426                         iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
2427                 c->SG[0].Addr.lower = temp64.val32.lower;
2428                 c->SG[0].Addr.upper = temp64.val32.upper;
2429                 c->SG[0].Len = iocommand.buf_size;
2430                 c->SG[0].Ext = 0; /* we are not chaining*/
2431         }
2432         hpsa_scsi_do_simple_cmd_core(h, c);
2433         hpsa_pci_unmap(h->pdev, c, 1, PCI_DMA_BIDIRECTIONAL);
2434         check_ioctl_unit_attention(h, c);
2435
2436         /* Copy the error information out */
2437         memcpy(&iocommand.error_info, c->err_info,
2438                 sizeof(iocommand.error_info));
2439         if (copy_to_user(argp, &iocommand, sizeof(iocommand))) {
2440                 kfree(buff);
2441                 cmd_special_free(h, c);
2442                 return -EFAULT;
2443         }
2444
2445         if (iocommand.Request.Type.Direction == XFER_READ) {
2446                 /* Copy the data out of the buffer we created */
2447                 if (copy_to_user(iocommand.buf, buff, iocommand.buf_size)) {
2448                         kfree(buff);
2449                         cmd_special_free(h, c);
2450                         return -EFAULT;
2451                 }
2452         }
2453         kfree(buff);
2454         cmd_special_free(h, c);
2455         return 0;
2456 }
2457
2458 static int hpsa_big_passthru_ioctl(struct ctlr_info *h, void __user *argp)
2459 {
2460         BIG_IOCTL_Command_struct *ioc;
2461         struct CommandList *c;
2462         unsigned char **buff = NULL;
2463         int *buff_size = NULL;
2464         union u64bit temp64;
2465         BYTE sg_used = 0;
2466         int status = 0;
2467         int i;
2468         u32 left;
2469         u32 sz;
2470         BYTE __user *data_ptr;
2471
2472         if (!argp)
2473                 return -EINVAL;
2474         if (!capable(CAP_SYS_RAWIO))
2475                 return -EPERM;
2476         ioc = (BIG_IOCTL_Command_struct *)
2477             kmalloc(sizeof(*ioc), GFP_KERNEL);
2478         if (!ioc) {
2479                 status = -ENOMEM;
2480                 goto cleanup1;
2481         }
2482         if (copy_from_user(ioc, argp, sizeof(*ioc))) {
2483                 status = -EFAULT;
2484                 goto cleanup1;
2485         }
2486         if ((ioc->buf_size < 1) &&
2487             (ioc->Request.Type.Direction != XFER_NONE)) {
2488                 status = -EINVAL;
2489                 goto cleanup1;
2490         }
2491         /* Check kmalloc limits  using all SGs */
2492         if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
2493                 status = -EINVAL;
2494                 goto cleanup1;
2495         }
2496         if (ioc->buf_size > ioc->malloc_size * MAXSGENTRIES) {
2497                 status = -EINVAL;
2498                 goto cleanup1;
2499         }
2500         buff = kzalloc(MAXSGENTRIES * sizeof(char *), GFP_KERNEL);
2501         if (!buff) {
2502                 status = -ENOMEM;
2503                 goto cleanup1;
2504         }
2505         buff_size = kmalloc(MAXSGENTRIES * sizeof(int), GFP_KERNEL);
2506         if (!buff_size) {
2507                 status = -ENOMEM;
2508                 goto cleanup1;
2509         }
2510         left = ioc->buf_size;
2511         data_ptr = ioc->buf;
2512         while (left) {
2513                 sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
2514                 buff_size[sg_used] = sz;
2515                 buff[sg_used] = kmalloc(sz, GFP_KERNEL);
2516                 if (buff[sg_used] == NULL) {
2517                         status = -ENOMEM;
2518                         goto cleanup1;
2519                 }
2520                 if (ioc->Request.Type.Direction == XFER_WRITE) {
2521                         if (copy_from_user(buff[sg_used], data_ptr, sz)) {
2522                                 status = -ENOMEM;
2523                                 goto cleanup1;
2524                         }
2525                 } else
2526                         memset(buff[sg_used], 0, sz);
2527                 left -= sz;
2528                 data_ptr += sz;
2529                 sg_used++;
2530         }
2531         c = cmd_special_alloc(h);
2532         if (c == NULL) {
2533                 status = -ENOMEM;
2534                 goto cleanup1;
2535         }
2536         c->cmd_type = CMD_IOCTL_PEND;
2537         c->Header.ReplyQueue = 0;
2538
2539         if (ioc->buf_size > 0) {
2540                 c->Header.SGList = sg_used;
2541                 c->Header.SGTotal = sg_used;
2542         } else {
2543                 c->Header.SGList = 0;
2544                 c->Header.SGTotal = 0;
2545         }
2546         memcpy(&c->Header.LUN, &ioc->LUN_info, sizeof(c->Header.LUN));
2547         c->Header.Tag.lower = c->busaddr;
2548         memcpy(&c->Request, &ioc->Request, sizeof(c->Request));
2549         if (ioc->buf_size > 0) {
2550                 int i;
2551                 for (i = 0; i < sg_used; i++) {
2552                         temp64.val = pci_map_single(h->pdev, buff[i],
2553                                     buff_size[i], PCI_DMA_BIDIRECTIONAL);
2554                         c->SG[i].Addr.lower = temp64.val32.lower;
2555                         c->SG[i].Addr.upper = temp64.val32.upper;
2556                         c->SG[i].Len = buff_size[i];
2557                         /* we are not chaining */
2558                         c->SG[i].Ext = 0;
2559                 }
2560         }
2561         hpsa_scsi_do_simple_cmd_core(h, c);
2562         hpsa_pci_unmap(h->pdev, c, sg_used, PCI_DMA_BIDIRECTIONAL);
2563         check_ioctl_unit_attention(h, c);
2564         /* Copy the error information out */
2565         memcpy(&ioc->error_info, c->err_info, sizeof(ioc->error_info));
2566         if (copy_to_user(argp, ioc, sizeof(*ioc))) {
2567                 cmd_special_free(h, c);
2568                 status = -EFAULT;
2569                 goto cleanup1;
2570         }
2571         if (ioc->Request.Type.Direction == XFER_READ) {
2572                 /* Copy the data out of the buffer we created */
2573                 BYTE __user *ptr = ioc->buf;
2574                 for (i = 0; i < sg_used; i++) {
2575                         if (copy_to_user(ptr, buff[i], buff_size[i])) {
2576                                 cmd_special_free(h, c);
2577                                 status = -EFAULT;
2578                                 goto cleanup1;
2579                         }
2580                         ptr += buff_size[i];
2581                 }
2582         }
2583         cmd_special_free(h, c);
2584         status = 0;
2585 cleanup1:
2586         if (buff) {
2587                 for (i = 0; i < sg_used; i++)
2588                         kfree(buff[i]);
2589                 kfree(buff);
2590         }
2591         kfree(buff_size);
2592         kfree(ioc);
2593         return status;
2594 }
2595
2596 static void check_ioctl_unit_attention(struct ctlr_info *h,
2597         struct CommandList *c)
2598 {
2599         if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
2600                         c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
2601                 (void) check_for_unit_attention(h, c);
2602 }
2603 /*
2604  * ioctl
2605  */
2606 static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg)
2607 {
2608         struct ctlr_info *h;
2609         void __user *argp = (void __user *)arg;
2610
2611         h = sdev_to_hba(dev);
2612
2613         switch (cmd) {
2614         case CCISS_DEREGDISK:
2615         case CCISS_REGNEWDISK:
2616         case CCISS_REGNEWD:
2617                 hpsa_update_scsi_devices(h, dev->host->host_no);
2618                 return 0;
2619         case CCISS_GETPCIINFO:
2620                 return hpsa_getpciinfo_ioctl(h, argp);
2621         case CCISS_GETDRIVVER:
2622                 return hpsa_getdrivver_ioctl(h, argp);
2623         case CCISS_PASSTHRU:
2624                 return hpsa_passthru_ioctl(h, argp);
2625         case CCISS_BIG_PASSTHRU:
2626                 return hpsa_big_passthru_ioctl(h, argp);
2627         default:
2628                 return -ENOTTY;
2629         }
2630 }
2631
2632 static void fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
2633         void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
2634         int cmd_type)
2635 {
2636         int pci_dir = XFER_NONE;
2637
2638         c->cmd_type = CMD_IOCTL_PEND;
2639         c->Header.ReplyQueue = 0;
2640         if (buff != NULL && size > 0) {
2641                 c->Header.SGList = 1;
2642                 c->Header.SGTotal = 1;
2643         } else {
2644                 c->Header.SGList = 0;
2645                 c->Header.SGTotal = 0;
2646         }
2647         c->Header.Tag.lower = c->busaddr;
2648         memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
2649
2650         c->Request.Type.Type = cmd_type;
2651         if (cmd_type == TYPE_CMD) {
2652                 switch (cmd) {
2653                 case HPSA_INQUIRY:
2654                         /* are we trying to read a vital product page */
2655                         if (page_code != 0) {
2656                                 c->Request.CDB[1] = 0x01;
2657                                 c->Request.CDB[2] = page_code;
2658                         }
2659                         c->Request.CDBLen = 6;
2660                         c->Request.Type.Attribute = ATTR_SIMPLE;
2661                         c->Request.Type.Direction = XFER_READ;
2662                         c->Request.Timeout = 0;
2663                         c->Request.CDB[0] = HPSA_INQUIRY;
2664                         c->Request.CDB[4] = size & 0xFF;
2665                         break;
2666                 case HPSA_REPORT_LOG:
2667                 case HPSA_REPORT_PHYS:
2668                         /* Talking to controller so It's a physical command
2669                            mode = 00 target = 0.  Nothing to write.
2670                          */
2671                         c->Request.CDBLen = 12;
2672                         c->Request.Type.Attribute = ATTR_SIMPLE;
2673                         c->Request.Type.Direction = XFER_READ;
2674                         c->Request.Timeout = 0;
2675                         c->Request.CDB[0] = cmd;
2676                         c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
2677                         c->Request.CDB[7] = (size >> 16) & 0xFF;
2678                         c->Request.CDB[8] = (size >> 8) & 0xFF;
2679                         c->Request.CDB[9] = size & 0xFF;
2680                         break;
2681
2682                 case HPSA_READ_CAPACITY:
2683                         c->Request.CDBLen = 10;
2684                         c->Request.Type.Attribute = ATTR_SIMPLE;
2685                         c->Request.Type.Direction = XFER_READ;
2686                         c->Request.Timeout = 0;
2687                         c->Request.CDB[0] = cmd;
2688                         break;
2689                 case HPSA_CACHE_FLUSH:
2690                         c->Request.CDBLen = 12;
2691                         c->Request.Type.Attribute = ATTR_SIMPLE;
2692                         c->Request.Type.Direction = XFER_WRITE;
2693                         c->Request.Timeout = 0;
2694                         c->Request.CDB[0] = BMIC_WRITE;
2695                         c->Request.CDB[6] = BMIC_CACHE_FLUSH;
2696                         break;
2697                 case TEST_UNIT_READY:
2698                         c->Request.CDBLen = 6;
2699                         c->Request.Type.Attribute = ATTR_SIMPLE;
2700                         c->Request.Type.Direction = XFER_NONE;
2701                         c->Request.Timeout = 0;
2702                         break;
2703                 default:
2704                         dev_warn(&h->pdev->dev, "unknown command 0x%c\n", cmd);
2705                         BUG();
2706                         return;
2707                 }
2708         } else if (cmd_type == TYPE_MSG) {
2709                 switch (cmd) {
2710
2711                 case  HPSA_DEVICE_RESET_MSG:
2712                         c->Request.CDBLen = 16;
2713                         c->Request.Type.Type =  1; /* It is a MSG not a CMD */
2714                         c->Request.Type.Attribute = ATTR_SIMPLE;
2715                         c->Request.Type.Direction = XFER_NONE;
2716                         c->Request.Timeout = 0; /* Don't time out */
2717                         c->Request.CDB[0] =  0x01; /* RESET_MSG is 0x01 */
2718                         c->Request.CDB[1] = 0x03;  /* Reset target above */
2719                         /* If bytes 4-7 are zero, it means reset the */
2720                         /* LunID device */
2721                         c->Request.CDB[4] = 0x00;
2722                         c->Request.CDB[5] = 0x00;
2723                         c->Request.CDB[6] = 0x00;
2724                         c->Request.CDB[7] = 0x00;
2725                 break;
2726
2727                 default:
2728                         dev_warn(&h->pdev->dev, "unknown message type %d\n",
2729                                 cmd);
2730                         BUG();
2731                 }
2732         } else {
2733                 dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
2734                 BUG();
2735         }
2736
2737         switch (c->Request.Type.Direction) {
2738         case XFER_READ:
2739                 pci_dir = PCI_DMA_FROMDEVICE;
2740                 break;
2741         case XFER_WRITE:
2742                 pci_dir = PCI_DMA_TODEVICE;
2743                 break;
2744         case XFER_NONE:
2745                 pci_dir = PCI_DMA_NONE;
2746                 break;
2747         default:
2748                 pci_dir = PCI_DMA_BIDIRECTIONAL;
2749         }
2750
2751         hpsa_map_one(h->pdev, c, buff, size, pci_dir);
2752
2753         return;
2754 }
2755
2756 /*
2757  * Map (physical) PCI mem into (virtual) kernel space
2758  */
2759 static void __iomem *remap_pci_mem(ulong base, ulong size)
2760 {
2761         ulong page_base = ((ulong) base) & PAGE_MASK;
2762         ulong page_offs = ((ulong) base) - page_base;
2763         void __iomem *page_remapped = ioremap(page_base, page_offs + size);
2764
2765         return page_remapped ? (page_remapped + page_offs) : NULL;
2766 }
2767
2768 /* Takes cmds off the submission queue and sends them to the hardware,
2769  * then puts them on the queue of cmds waiting for completion.
2770  */
2771 static void start_io(struct ctlr_info *h)
2772 {
2773         struct CommandList *c;
2774
2775         while (!hlist_empty(&h->reqQ)) {
2776                 c = hlist_entry(h->reqQ.first, struct CommandList, list);
2777                 /* can't do anything if fifo is full */
2778                 if ((h->access.fifo_full(h))) {
2779                         dev_warn(&h->pdev->dev, "fifo full\n");
2780                         break;
2781                 }
2782
2783                 /* Get the first entry from the Request Q */
2784                 removeQ(c);
2785                 h->Qdepth--;
2786
2787                 /* Tell the controller execute command */
2788                 h->access.submit_command(h, c);
2789
2790                 /* Put job onto the completed Q */
2791                 addQ(&h->cmpQ, c);
2792         }
2793 }
2794
2795 static inline unsigned long get_next_completion(struct ctlr_info *h)
2796 {
2797         return h->access.command_completed(h);
2798 }
2799
2800 static inline bool interrupt_pending(struct ctlr_info *h)
2801 {
2802         return h->access.intr_pending(h);
2803 }
2804
2805 static inline long interrupt_not_for_us(struct ctlr_info *h)
2806 {
2807         return !(h->msi_vector || h->msix_vector) &&
2808                 ((h->access.intr_pending(h) == 0) ||
2809                 (h->interrupts_enabled == 0));
2810 }
2811
2812 static inline int bad_tag(struct ctlr_info *h, u32 tag_index,
2813         u32 raw_tag)
2814 {
2815         if (unlikely(tag_index >= h->nr_cmds)) {
2816                 dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
2817                 return 1;
2818         }
2819         return 0;
2820 }
2821
2822 static inline void finish_cmd(struct CommandList *c, u32 raw_tag)
2823 {
2824         removeQ(c);
2825         if (likely(c->cmd_type == CMD_SCSI))
2826                 complete_scsi_command(c, 0, raw_tag);
2827         else if (c->cmd_type == CMD_IOCTL_PEND)
2828                 complete(c->waiting);
2829 }
2830
2831 static inline u32 hpsa_tag_contains_index(u32 tag)
2832 {
2833 #define DIRECT_LOOKUP_BIT 0x10
2834         return tag & DIRECT_LOOKUP_BIT;
2835 }
2836
2837 static inline u32 hpsa_tag_to_index(u32 tag)
2838 {
2839 #define DIRECT_LOOKUP_SHIFT 5
2840         return tag >> DIRECT_LOOKUP_SHIFT;
2841 }
2842
2843 static inline u32 hpsa_tag_discard_error_bits(u32 tag)
2844 {
2845 #define HPSA_ERROR_BITS 0x03
2846         return tag & ~HPSA_ERROR_BITS;
2847 }
2848
2849 /* process completion of an indexed ("direct lookup") command */
2850 static inline u32 process_indexed_cmd(struct ctlr_info *h,
2851         u32 raw_tag)
2852 {
2853         u32 tag_index;
2854         struct CommandList *c;
2855
2856         tag_index = hpsa_tag_to_index(raw_tag);
2857         if (bad_tag(h, tag_index, raw_tag))
2858                 return next_command(h);
2859         c = h->cmd_pool + tag_index;
2860         finish_cmd(c, raw_tag);
2861         return next_command(h);
2862 }
2863
2864 /* process completion of a non-indexed command */
2865 static inline u32 process_nonindexed_cmd(struct ctlr_info *h,
2866         u32 raw_tag)
2867 {
2868         u32 tag;
2869         struct CommandList *c = NULL;
2870         struct hlist_node *tmp;
2871
2872         tag = hpsa_tag_discard_error_bits(raw_tag);
2873         hlist_for_each_entry(c, tmp, &h->cmpQ, list) {
2874                 if ((c->busaddr & 0xFFFFFFE0) == (tag & 0xFFFFFFE0)) {
2875                         finish_cmd(c, raw_tag);
2876                         return next_command(h);
2877                 }
2878         }
2879         bad_tag(h, h->nr_cmds + 1, raw_tag);
2880         return next_command(h);
2881 }
2882
2883 static irqreturn_t do_hpsa_intr(int irq, void *dev_id)
2884 {
2885         struct ctlr_info *h = dev_id;
2886         unsigned long flags;
2887         u32 raw_tag;
2888
2889         if (interrupt_not_for_us(h))
2890                 return IRQ_NONE;
2891         spin_lock_irqsave(&h->lock, flags);
2892         raw_tag = get_next_completion(h);
2893         while (raw_tag != FIFO_EMPTY) {
2894                 if (hpsa_tag_contains_index(raw_tag))
2895                         raw_tag = process_indexed_cmd(h, raw_tag);
2896                 else
2897                         raw_tag = process_nonindexed_cmd(h, raw_tag);
2898         }
2899         spin_unlock_irqrestore(&h->lock, flags);
2900         return IRQ_HANDLED;
2901 }
2902
2903 /* Send a message CDB to the firmwart. */
2904 static __devinit int hpsa_message(struct pci_dev *pdev, unsigned char opcode,
2905                                                 unsigned char type)
2906 {
2907         struct Command {
2908                 struct CommandListHeader CommandHeader;
2909                 struct RequestBlock Request;
2910                 struct ErrDescriptor ErrorDescriptor;
2911         };
2912         struct Command *cmd;
2913         static const size_t cmd_sz = sizeof(*cmd) +
2914                                         sizeof(cmd->ErrorDescriptor);
2915         dma_addr_t paddr64;
2916         uint32_t paddr32, tag;
2917         void __iomem *vaddr;
2918         int i, err;
2919
2920         vaddr = pci_ioremap_bar(pdev, 0);
2921         if (vaddr == NULL)
2922                 return -ENOMEM;
2923
2924         /* The Inbound Post Queue only accepts 32-bit physical addresses for the
2925          * CCISS commands, so they must be allocated from the lower 4GiB of
2926          * memory.
2927          */
2928         err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
2929         if (err) {
2930                 iounmap(vaddr);
2931                 return -ENOMEM;
2932         }
2933
2934         cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
2935         if (cmd == NULL) {
2936                 iounmap(vaddr);
2937                 return -ENOMEM;
2938         }
2939
2940         /* This must fit, because of the 32-bit consistent DMA mask.  Also,
2941          * although there's no guarantee, we assume that the address is at
2942          * least 4-byte aligned (most likely, it's page-aligned).
2943          */
2944         paddr32 = paddr64;
2945
2946         cmd->CommandHeader.ReplyQueue = 0;
2947         cmd->CommandHeader.SGList = 0;
2948         cmd->CommandHeader.SGTotal = 0;
2949         cmd->CommandHeader.Tag.lower = paddr32;
2950         cmd->CommandHeader.Tag.upper = 0;
2951         memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
2952
2953         cmd->Request.CDBLen = 16;
2954         cmd->Request.Type.Type = TYPE_MSG;
2955         cmd->Request.Type.Attribute = ATTR_HEADOFQUEUE;
2956         cmd->Request.Type.Direction = XFER_NONE;
2957         cmd->Request.Timeout = 0; /* Don't time out */
2958         cmd->Request.CDB[0] = opcode;
2959         cmd->Request.CDB[1] = type;
2960         memset(&cmd->Request.CDB[2], 0, 14); /* rest of the CDB is reserved */
2961         cmd->ErrorDescriptor.Addr.lower = paddr32 + sizeof(*cmd);
2962         cmd->ErrorDescriptor.Addr.upper = 0;
2963         cmd->ErrorDescriptor.Len = sizeof(struct ErrorInfo);
2964
2965         writel(paddr32, vaddr + SA5_REQUEST_PORT_OFFSET);
2966
2967         for (i = 0; i < HPSA_MSG_SEND_RETRY_LIMIT; i++) {
2968                 tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
2969                 if (hpsa_tag_discard_error_bits(tag) == paddr32)
2970                         break;
2971                 msleep(HPSA_MSG_SEND_RETRY_INTERVAL_MSECS);
2972         }
2973
2974         iounmap(vaddr);
2975
2976         /* we leak the DMA buffer here ... no choice since the controller could
2977          *  still complete the command.
2978          */
2979         if (i == HPSA_MSG_SEND_RETRY_LIMIT) {
2980                 dev_err(&pdev->dev, "controller message %02x:%02x timed out\n",
2981                         opcode, type);
2982                 return -ETIMEDOUT;
2983         }
2984
2985         pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
2986
2987         if (tag & HPSA_ERROR_BIT) {
2988                 dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
2989                         opcode, type);
2990                 return -EIO;
2991         }
2992
2993         dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
2994                 opcode, type);
2995         return 0;
2996 }
2997
2998 #define hpsa_soft_reset_controller(p) hpsa_message(p, 1, 0)
2999 #define hpsa_noop(p) hpsa_message(p, 3, 0)
3000
3001 static __devinit int hpsa_reset_msi(struct pci_dev *pdev)
3002 {
3003 /* the #defines are stolen from drivers/pci/msi.h. */
3004 #define msi_control_reg(base)           (base + PCI_MSI_FLAGS)
3005 #define PCI_MSIX_FLAGS_ENABLE           (1 << 15)
3006
3007         int pos;
3008         u16 control = 0;
3009
3010         pos = pci_find_capability(pdev, PCI_CAP_ID_MSI);
3011         if (pos) {
3012                 pci_read_config_word(pdev, msi_control_reg(pos), &control);
3013                 if (control & PCI_MSI_FLAGS_ENABLE) {
3014                         dev_info(&pdev->dev, "resetting MSI\n");
3015                         pci_write_config_word(pdev, msi_control_reg(pos),
3016                                         control & ~PCI_MSI_FLAGS_ENABLE);
3017                 }
3018         }
3019
3020         pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
3021         if (pos) {
3022                 pci_read_config_word(pdev, msi_control_reg(pos), &control);
3023                 if (control & PCI_MSIX_FLAGS_ENABLE) {
3024                         dev_info(&pdev->dev, "resetting MSI-X\n");
3025                         pci_write_config_word(pdev, msi_control_reg(pos),
3026                                         control & ~PCI_MSIX_FLAGS_ENABLE);
3027                 }
3028         }
3029
3030         return 0;
3031 }
3032
3033 /* This does a hard reset of the controller using PCI power management
3034  * states.
3035  */
3036 static __devinit int hpsa_hard_reset_controller(struct pci_dev *pdev)
3037 {
3038         u16 pmcsr, saved_config_space[32];
3039         int i, pos;
3040
3041         dev_info(&pdev->dev, "using PCI PM to reset controller\n");
3042
3043         /* This is very nearly the same thing as
3044          *
3045          * pci_save_state(pci_dev);
3046          * pci_set_power_state(pci_dev, PCI_D3hot);
3047          * pci_set_power_state(pci_dev, PCI_D0);
3048          * pci_restore_state(pci_dev);
3049          *
3050          * but we can't use these nice canned kernel routines on
3051          * kexec, because they also check the MSI/MSI-X state in PCI
3052          * configuration space and do the wrong thing when it is
3053          * set/cleared.  Also, the pci_save/restore_state functions
3054          * violate the ordering requirements for restoring the
3055          * configuration space from the CCISS document (see the
3056          * comment below).  So we roll our own ....
3057          */
3058
3059         for (i = 0; i < 32; i++)
3060                 pci_read_config_word(pdev, 2*i, &saved_config_space[i]);
3061
3062         pos = pci_find_capability(pdev, PCI_CAP_ID_PM);
3063         if (pos == 0) {
3064                 dev_err(&pdev->dev,
3065                         "hpsa_reset_controller: PCI PM not supported\n");
3066                 return -ENODEV;
3067         }
3068
3069         /* Quoting from the Open CISS Specification: "The Power
3070          * Management Control/Status Register (CSR) controls the power
3071          * state of the device.  The normal operating state is D0,
3072          * CSR=00h.  The software off state is D3, CSR=03h.  To reset
3073          * the controller, place the interface device in D3 then to
3074          * D0, this causes a secondary PCI reset which will reset the
3075          * controller."
3076          */
3077
3078         /* enter the D3hot power management state */
3079         pci_read_config_word(pdev, pos + PCI_PM_CTRL, &pmcsr);
3080         pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
3081         pmcsr |= PCI_D3hot;
3082         pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
3083
3084         msleep(500);
3085
3086         /* enter the D0 power management state */
3087         pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
3088         pmcsr |= PCI_D0;
3089         pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
3090
3091         msleep(500);
3092
3093         /* Restore the PCI configuration space.  The Open CISS
3094          * Specification says, "Restore the PCI Configuration
3095          * Registers, offsets 00h through 60h. It is important to
3096          * restore the command register, 16-bits at offset 04h,
3097          * last. Do not restore the configuration status register,
3098          * 16-bits at offset 06h."  Note that the offset is 2*i.
3099          */
3100         for (i = 0; i < 32; i++) {
3101                 if (i == 2 || i == 3)
3102                         continue;
3103                 pci_write_config_word(pdev, 2*i, saved_config_space[i]);
3104         }
3105         wmb();
3106         pci_write_config_word(pdev, 4, saved_config_space[2]);
3107
3108         return 0;
3109 }
3110
3111 /*
3112  *  We cannot read the structure directly, for portability we must use
3113  *   the io functions.
3114  *   This is for debug only.
3115  */
3116 #ifdef HPSA_DEBUG
3117 static void print_cfg_table(struct device *dev, struct CfgTable *tb)
3118 {
3119         int i;
3120         char temp_name[17];
3121
3122         dev_info(dev, "Controller Configuration information\n");
3123         dev_info(dev, "------------------------------------\n");
3124         for (i = 0; i < 4; i++)
3125                 temp_name[i] = readb(&(tb->Signature[i]));
3126         temp_name[4] = '\0';
3127         dev_info(dev, "   Signature = %s\n", temp_name);
3128         dev_info(dev, "   Spec Number = %d\n", readl(&(tb->SpecValence)));
3129         dev_info(dev, "   Transport methods supported = 0x%x\n",
3130                readl(&(tb->TransportSupport)));
3131         dev_info(dev, "   Transport methods active = 0x%x\n",
3132                readl(&(tb->TransportActive)));
3133         dev_info(dev, "   Requested transport Method = 0x%x\n",
3134                readl(&(tb->HostWrite.TransportRequest)));
3135         dev_info(dev, "   Coalesce Interrupt Delay = 0x%x\n",
3136                readl(&(tb->HostWrite.CoalIntDelay)));
3137         dev_info(dev, "   Coalesce Interrupt Count = 0x%x\n",
3138                readl(&(tb->HostWrite.CoalIntCount)));
3139         dev_info(dev, "   Max outstanding commands = 0x%d\n",
3140                readl(&(tb->CmdsOutMax)));
3141         dev_info(dev, "   Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
3142         for (i = 0; i < 16; i++)
3143                 temp_name[i] = readb(&(tb->ServerName[i]));
3144         temp_name[16] = '\0';
3145         dev_info(dev, "   Server Name = %s\n", temp_name);
3146         dev_info(dev, "   Heartbeat Counter = 0x%x\n\n\n",
3147                 readl(&(tb->HeartBeat)));
3148 }
3149 #endif                          /* HPSA_DEBUG */
3150
3151 static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
3152 {
3153         int i, offset, mem_type, bar_type;
3154
3155         if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
3156                 return 0;
3157         offset = 0;
3158         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3159                 bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
3160                 if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
3161                         offset += 4;
3162                 else {
3163                         mem_type = pci_resource_flags(pdev, i) &
3164                             PCI_BASE_ADDRESS_MEM_TYPE_MASK;
3165                         switch (mem_type) {
3166                         case PCI_BASE_ADDRESS_MEM_TYPE_32:
3167                         case PCI_BASE_ADDRESS_MEM_TYPE_1M:
3168                                 offset += 4;    /* 32 bit */
3169                                 break;
3170                         case PCI_BASE_ADDRESS_MEM_TYPE_64:
3171                                 offset += 8;
3172                                 break;
3173                         default:        /* reserved in PCI 2.2 */
3174                                 dev_warn(&pdev->dev,
3175                                        "base address is invalid\n");
3176                                 return -1;
3177                                 break;
3178                         }
3179                 }
3180                 if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
3181                         return i + 1;
3182         }
3183         return -1;
3184 }
3185
3186 /* If MSI/MSI-X is supported by the kernel we will try to enable it on
3187  * controllers that are capable. If not, we use IO-APIC mode.
3188  */
3189
3190 static void __devinit hpsa_interrupt_mode(struct ctlr_info *h,
3191                                            struct pci_dev *pdev, u32 board_id)
3192 {
3193 #ifdef CONFIG_PCI_MSI
3194         int err;
3195         struct msix_entry hpsa_msix_entries[4] = { {0, 0}, {0, 1},
3196         {0, 2}, {0, 3}
3197         };
3198
3199         /* Some boards advertise MSI but don't really support it */
3200         if ((board_id == 0x40700E11) ||
3201             (board_id == 0x40800E11) ||
3202             (board_id == 0x40820E11) || (board_id == 0x40830E11))
3203                 goto default_int_mode;
3204         if (pci_find_capability(pdev, PCI_CAP_ID_MSIX)) {
3205                 dev_info(&pdev->dev, "MSIX\n");
3206                 err = pci_enable_msix(pdev, hpsa_msix_entries, 4);
3207                 if (!err) {
3208                         h->intr[0] = hpsa_msix_entries[0].vector;
3209                         h->intr[1] = hpsa_msix_entries[1].vector;
3210                         h->intr[2] = hpsa_msix_entries[2].vector;
3211                         h->intr[3] = hpsa_msix_entries[3].vector;
3212                         h->msix_vector = 1;
3213                         return;
3214                 }
3215                 if (err > 0) {
3216                         dev_warn(&pdev->dev, "only %d MSI-X vectors "
3217                                "available\n", err);
3218                         goto default_int_mode;
3219                 } else {
3220                         dev_warn(&pdev->dev, "MSI-X init failed %d\n",
3221                                err);
3222                         goto default_int_mode;
3223                 }
3224         }
3225         if (pci_find_capability(pdev, PCI_CAP_ID_MSI)) {
3226                 dev_info(&pdev->dev, "MSI\n");
3227                 if (!pci_enable_msi(pdev))
3228                         h->msi_vector = 1;
3229                 else
3230                         dev_warn(&pdev->dev, "MSI init failed\n");
3231         }
3232 default_int_mode:
3233 #endif                          /* CONFIG_PCI_MSI */
3234         /* if we get here we're going to use the default interrupt mode */
3235         h->intr[PERF_MODE_INT] = pdev->irq;
3236 }
3237
3238 static int hpsa_pci_init(struct ctlr_info *h, struct pci_dev *pdev)
3239 {
3240         ushort subsystem_vendor_id, subsystem_device_id, command;
3241         u32 board_id, scratchpad = 0;
3242         u64 cfg_offset;
3243         u32 cfg_base_addr;
3244         u64 cfg_base_addr_index;
3245         u32 trans_offset;
3246         int i, prod_index, err;
3247
3248         subsystem_vendor_id = pdev->subsystem_vendor;
3249         subsystem_device_id = pdev->subsystem_device;
3250         board_id = (((u32) (subsystem_device_id << 16) & 0xffff0000) |
3251                     subsystem_vendor_id);
3252
3253         for (i = 0; i < ARRAY_SIZE(products); i++)
3254                 if (board_id == products[i].board_id)
3255                         break;
3256
3257         prod_index = i;
3258
3259         if (prod_index == ARRAY_SIZE(products)) {
3260                 prod_index--;
3261                 if (subsystem_vendor_id != PCI_VENDOR_ID_HP ||
3262                                 !hpsa_allow_any) {
3263                         dev_warn(&pdev->dev, "unrecognized board ID:"
3264                                 " 0x%08lx, ignoring.\n",
3265                                 (unsigned long) board_id);
3266                         return -ENODEV;
3267                 }
3268         }
3269         /* check to see if controller has been disabled
3270          * BEFORE trying to enable it
3271          */
3272         (void)pci_read_config_word(pdev, PCI_COMMAND, &command);
3273         if (!(command & 0x02)) {
3274                 dev_warn(&pdev->dev, "controller appears to be disabled\n");
3275                 return -ENODEV;
3276         }
3277
3278         err = pci_enable_device(pdev);
3279         if (err) {
3280                 dev_warn(&pdev->dev, "unable to enable PCI device\n");
3281                 return err;
3282         }
3283
3284         err = pci_request_regions(pdev, "hpsa");
3285         if (err) {
3286                 dev_err(&pdev->dev, "cannot obtain PCI resources, aborting\n");
3287                 return err;
3288         }
3289
3290         /* If the kernel supports MSI/MSI-X we will try to enable that,
3291          * else we use the IO-APIC interrupt assigned to us by system ROM.
3292          */
3293         hpsa_interrupt_mode(h, pdev, board_id);
3294
3295         /* find the memory BAR */
3296         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3297                 if (pci_resource_flags(pdev, i) & IORESOURCE_MEM)
3298                         break;
3299         }
3300         if (i == DEVICE_COUNT_RESOURCE) {
3301                 dev_warn(&pdev->dev, "no memory BAR found\n");
3302                 err = -ENODEV;
3303                 goto err_out_free_res;
3304         }
3305
3306         h->paddr = pci_resource_start(pdev, i); /* addressing mode bits
3307                                                  * already removed
3308                                                  */
3309
3310         h->vaddr = remap_pci_mem(h->paddr, 0x250);
3311
3312         /* Wait for the board to become ready.  */
3313         for (i = 0; i < HPSA_BOARD_READY_ITERATIONS; i++) {
3314                 scratchpad = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
3315                 if (scratchpad == HPSA_FIRMWARE_READY)
3316                         break;
3317                 msleep(HPSA_BOARD_READY_POLL_INTERVAL_MSECS);
3318         }
3319         if (scratchpad != HPSA_FIRMWARE_READY) {
3320                 dev_warn(&pdev->dev, "board not ready, timed out.\n");
3321                 err = -ENODEV;
3322                 goto err_out_free_res;
3323         }
3324
3325         /* get the address index number */
3326         cfg_base_addr = readl(h->vaddr + SA5_CTCFG_OFFSET);
3327         cfg_base_addr &= (u32) 0x0000ffff;
3328         cfg_base_addr_index = find_PCI_BAR_index(pdev, cfg_base_addr);
3329         if (cfg_base_addr_index == -1) {
3330                 dev_warn(&pdev->dev, "cannot find cfg_base_addr_index\n");
3331                 err = -ENODEV;
3332                 goto err_out_free_res;
3333         }
3334
3335         cfg_offset = readl(h->vaddr + SA5_CTMEM_OFFSET);
3336         h->cfgtable = remap_pci_mem(pci_resource_start(pdev,
3337                                cfg_base_addr_index) + cfg_offset,
3338                                 sizeof(h->cfgtable));
3339         /* Find performant mode table. */
3340         trans_offset = readl(&(h->cfgtable->TransMethodOffset));
3341         h->transtable = remap_pci_mem(pci_resource_start(pdev,
3342                                 cfg_base_addr_index)+cfg_offset+trans_offset,
3343                                 sizeof(*h->transtable));
3344
3345         h->board_id = board_id;
3346         h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
3347         h->product_name = products[prod_index].product_name;
3348         h->access = *(products[prod_index].access);
3349         /* Allow room for some ioctls */
3350         h->nr_cmds = h->max_commands - 4;
3351
3352         if ((readb(&h->cfgtable->Signature[0]) != 'C') ||
3353             (readb(&h->cfgtable->Signature[1]) != 'I') ||
3354             (readb(&h->cfgtable->Signature[2]) != 'S') ||
3355             (readb(&h->cfgtable->Signature[3]) != 'S')) {
3356                 dev_warn(&pdev->dev, "not a valid CISS config table\n");
3357                 err = -ENODEV;
3358                 goto err_out_free_res;
3359         }
3360 #ifdef CONFIG_X86
3361         {
3362                 /* Need to enable prefetch in the SCSI core for 6400 in x86 */
3363                 u32 prefetch;
3364                 prefetch = readl(&(h->cfgtable->SCSI_Prefetch));
3365                 prefetch |= 0x100;
3366                 writel(prefetch, &(h->cfgtable->SCSI_Prefetch));
3367         }
3368 #endif
3369
3370         /* Disabling DMA prefetch for the P600
3371          * An ASIC bug may result in a prefetch beyond
3372          * physical memory.
3373          */
3374         if (board_id == 0x3225103C) {
3375                 u32 dma_prefetch;
3376                 dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
3377                 dma_prefetch |= 0x8000;
3378                 writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
3379         }
3380
3381         h->max_commands = readl(&(h->cfgtable->CmdsOutMax));
3382         /* Update the field, and then ring the doorbell */
3383         writel(CFGTBL_Trans_Simple, &(h->cfgtable->HostWrite.TransportRequest));
3384         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
3385
3386         /* under certain very rare conditions, this can take awhile.
3387          * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
3388          * as we enter this code.)
3389          */
3390         for (i = 0; i < MAX_CONFIG_WAIT; i++) {
3391                 if (!(readl(h->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
3392                         break;
3393                 /* delay and try again */
3394                 msleep(10);
3395         }
3396
3397 #ifdef HPSA_DEBUG
3398         print_cfg_table(&pdev->dev, h->cfgtable);
3399 #endif                          /* HPSA_DEBUG */
3400
3401         if (!(readl(&(h->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
3402                 dev_warn(&pdev->dev, "unable to get board into simple mode\n");
3403                 err = -ENODEV;
3404                 goto err_out_free_res;
3405         }
3406         return 0;
3407
3408 err_out_free_res:
3409         /*
3410          * Deliberately omit pci_disable_device(): it does something nasty to
3411          * Smart Array controllers that pci_enable_device does not undo
3412          */
3413         pci_release_regions(pdev);
3414         return err;
3415 }
3416
3417 static void __devinit hpsa_hba_inquiry(struct ctlr_info *h)
3418 {
3419         int rc;
3420
3421 #define HBA_INQUIRY_BYTE_COUNT 64
3422         h->hba_inquiry_data = kmalloc(HBA_INQUIRY_BYTE_COUNT, GFP_KERNEL);
3423         if (!h->hba_inquiry_data)
3424                 return;
3425         rc = hpsa_scsi_do_inquiry(h, RAID_CTLR_LUNID, 0,
3426                 h->hba_inquiry_data, HBA_INQUIRY_BYTE_COUNT);
3427         if (rc != 0) {
3428                 kfree(h->hba_inquiry_data);
3429                 h->hba_inquiry_data = NULL;
3430         }
3431 }
3432
3433 static int __devinit hpsa_init_one(struct pci_dev *pdev,
3434                                     const struct pci_device_id *ent)
3435 {
3436         int i, rc;
3437         int dac;
3438         struct ctlr_info *h;
3439
3440         if (number_of_controllers == 0)
3441                 printk(KERN_INFO DRIVER_NAME "\n");
3442         if (reset_devices) {
3443                 /* Reset the controller with a PCI power-cycle */
3444                 if (hpsa_hard_reset_controller(pdev) || hpsa_reset_msi(pdev))
3445                         return -ENODEV;
3446
3447                 /* Some devices (notably the HP Smart Array 5i Controller)
3448                    need a little pause here */
3449                 msleep(HPSA_POST_RESET_PAUSE_MSECS);
3450
3451                 /* Now try to get the controller to respond to a no-op */
3452                 for (i = 0; i < HPSA_POST_RESET_NOOP_RETRIES; i++) {
3453                         if (hpsa_noop(pdev) == 0)
3454                                 break;
3455                         else
3456                                 dev_warn(&pdev->dev, "no-op failed%s\n",
3457                                                 (i < 11 ? "; re-trying" : ""));
3458                 }
3459         }
3460
3461         /* Command structures must be aligned on a 32-byte boundary because
3462          * the 5 lower bits of the address are used by the hardware. and by
3463          * the driver.  See comments in hpsa.h for more info.
3464          */
3465 #define COMMANDLIST_ALIGNMENT 32
3466         BUILD_BUG_ON(sizeof(struct CommandList) % COMMANDLIST_ALIGNMENT);
3467         h = kzalloc(sizeof(*h), GFP_KERNEL);
3468         if (!h)
3469                 return -ENOMEM;
3470
3471         h->busy_initializing = 1;
3472         INIT_HLIST_HEAD(&h->cmpQ);
3473         INIT_HLIST_HEAD(&h->reqQ);
3474         mutex_init(&h->busy_shutting_down);
3475         init_completion(&h->scan_wait);
3476         rc = hpsa_pci_init(h, pdev);
3477         if (rc != 0)
3478                 goto clean1;
3479
3480         sprintf(h->devname, "hpsa%d", number_of_controllers);
3481         h->ctlr = number_of_controllers;
3482         number_of_controllers++;
3483         h->pdev = pdev;
3484
3485         /* configure PCI DMA stuff */
3486         rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
3487         if (rc == 0) {
3488                 dac = 1;
3489         } else {
3490                 rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
3491                 if (rc == 0) {
3492                         dac = 0;
3493                 } else {
3494                         dev_err(&pdev->dev, "no suitable DMA available\n");
3495                         goto clean1;
3496                 }
3497         }
3498
3499         /* make sure the board interrupts are off */
3500         h->access.set_intr_mask(h, HPSA_INTR_OFF);
3501         rc = request_irq(h->intr[PERF_MODE_INT], do_hpsa_intr,
3502                         IRQF_DISABLED, h->devname, h);
3503         if (rc) {
3504                 dev_err(&pdev->dev, "unable to get irq %d for %s\n",
3505                        h->intr[PERF_MODE_INT], h->devname);
3506                 goto clean2;
3507         }
3508
3509         dev_info(&pdev->dev, "%s: <0x%x> at IRQ %d%s using DAC\n",
3510                h->devname, pdev->device,
3511                h->intr[PERF_MODE_INT], dac ? "" : " not");
3512
3513         h->cmd_pool_bits =
3514             kmalloc(((h->nr_cmds + BITS_PER_LONG -
3515                       1) / BITS_PER_LONG) * sizeof(unsigned long), GFP_KERNEL);
3516         h->cmd_pool = pci_alloc_consistent(h->pdev,
3517                     h->nr_cmds * sizeof(*h->cmd_pool),
3518                     &(h->cmd_pool_dhandle));
3519         h->errinfo_pool = pci_alloc_consistent(h->pdev,
3520                     h->nr_cmds * sizeof(*h->errinfo_pool),
3521                     &(h->errinfo_pool_dhandle));
3522         if ((h->cmd_pool_bits == NULL)
3523             || (h->cmd_pool == NULL)
3524             || (h->errinfo_pool == NULL)) {
3525                 dev_err(&pdev->dev, "out of memory");
3526                 rc = -ENOMEM;
3527                 goto clean4;
3528         }
3529         spin_lock_init(&h->lock);
3530
3531         pci_set_drvdata(pdev, h);
3532         memset(h->cmd_pool_bits, 0,
3533                ((h->nr_cmds + BITS_PER_LONG -
3534                  1) / BITS_PER_LONG) * sizeof(unsigned long));
3535
3536         hpsa_scsi_setup(h);
3537
3538         /* Turn the interrupts on so we can service requests */
3539         h->access.set_intr_mask(h, HPSA_INTR_ON);
3540
3541         hpsa_put_ctlr_into_performant_mode(h);
3542         hpsa_hba_inquiry(h);
3543         hpsa_register_scsi(h);  /* hook ourselves into SCSI subsystem */
3544         h->busy_initializing = 0;
3545         return 1;
3546
3547 clean4:
3548         kfree(h->cmd_pool_bits);
3549         if (h->cmd_pool)
3550                 pci_free_consistent(h->pdev,
3551                             h->nr_cmds * sizeof(struct CommandList),
3552                             h->cmd_pool, h->cmd_pool_dhandle);
3553         if (h->errinfo_pool)
3554                 pci_free_consistent(h->pdev,
3555                             h->nr_cmds * sizeof(struct ErrorInfo),
3556                             h->errinfo_pool,
3557                             h->errinfo_pool_dhandle);
3558         free_irq(h->intr[PERF_MODE_INT], h);
3559 clean2:
3560 clean1:
3561         h->busy_initializing = 0;
3562         kfree(h);
3563         return rc;
3564 }
3565
3566 static void hpsa_flush_cache(struct ctlr_info *h)
3567 {
3568         char *flush_buf;
3569         struct CommandList *c;
3570
3571         flush_buf = kzalloc(4, GFP_KERNEL);
3572         if (!flush_buf)
3573                 return;
3574
3575         c = cmd_special_alloc(h);
3576         if (!c) {
3577                 dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
3578                 goto out_of_memory;
3579         }
3580         fill_cmd(c, HPSA_CACHE_FLUSH, h, flush_buf, 4, 0,
3581                 RAID_CTLR_LUNID, TYPE_CMD);
3582         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_TODEVICE);
3583         if (c->err_info->CommandStatus != 0)
3584                 dev_warn(&h->pdev->dev,
3585                         "error flushing cache on controller\n");
3586         cmd_special_free(h, c);
3587 out_of_memory:
3588         kfree(flush_buf);
3589 }
3590
3591 static void hpsa_shutdown(struct pci_dev *pdev)
3592 {
3593         struct ctlr_info *h;
3594
3595         h = pci_get_drvdata(pdev);
3596         /* Turn board interrupts off  and send the flush cache command
3597          * sendcmd will turn off interrupt, and send the flush...
3598          * To write all data in the battery backed cache to disks
3599          */
3600         hpsa_flush_cache(h);
3601         h->access.set_intr_mask(h, HPSA_INTR_OFF);
3602         free_irq(h->intr[PERF_MODE_INT], h);
3603 #ifdef CONFIG_PCI_MSI
3604         if (h->msix_vector)
3605                 pci_disable_msix(h->pdev);
3606         else if (h->msi_vector)
3607                 pci_disable_msi(h->pdev);
3608 #endif                          /* CONFIG_PCI_MSI */
3609 }
3610
3611 static void __devexit hpsa_remove_one(struct pci_dev *pdev)
3612 {
3613         struct ctlr_info *h;
3614
3615         if (pci_get_drvdata(pdev) == NULL) {
3616                 dev_err(&pdev->dev, "unable to remove device \n");
3617                 return;
3618         }
3619         h = pci_get_drvdata(pdev);
3620         mutex_lock(&h->busy_shutting_down);
3621         remove_from_scan_list(h);
3622         hpsa_unregister_scsi(h);        /* unhook from SCSI subsystem */
3623         hpsa_shutdown(pdev);
3624         iounmap(h->vaddr);
3625         pci_free_consistent(h->pdev,
3626                 h->nr_cmds * sizeof(struct CommandList),
3627                 h->cmd_pool, h->cmd_pool_dhandle);
3628         pci_free_consistent(h->pdev,
3629                 h->nr_cmds * sizeof(struct ErrorInfo),
3630                 h->errinfo_pool, h->errinfo_pool_dhandle);
3631         pci_free_consistent(h->pdev, h->reply_pool_size,
3632                 h->reply_pool, h->reply_pool_dhandle);
3633         kfree(h->cmd_pool_bits);
3634         kfree(h->blockFetchTable);
3635         kfree(h->hba_inquiry_data);
3636         /*
3637          * Deliberately omit pci_disable_device(): it does something nasty to
3638          * Smart Array controllers that pci_enable_device does not undo
3639          */
3640         pci_release_regions(pdev);
3641         pci_set_drvdata(pdev, NULL);
3642         mutex_unlock(&h->busy_shutting_down);
3643         kfree(h);
3644 }
3645
3646 static int hpsa_suspend(__attribute__((unused)) struct pci_dev *pdev,
3647         __attribute__((unused)) pm_message_t state)
3648 {
3649         return -ENOSYS;
3650 }
3651
3652 static int hpsa_resume(__attribute__((unused)) struct pci_dev *pdev)
3653 {
3654         return -ENOSYS;
3655 }
3656
3657 static struct pci_driver hpsa_pci_driver = {
3658         .name = "hpsa",
3659         .probe = hpsa_init_one,
3660         .remove = __devexit_p(hpsa_remove_one),
3661         .id_table = hpsa_pci_device_id, /* id_table */
3662         .shutdown = hpsa_shutdown,
3663         .suspend = hpsa_suspend,
3664         .resume = hpsa_resume,
3665 };
3666
3667 /* Fill in bucket_map[], given nsgs (the max number of
3668  * scatter gather elements supported) and bucket[],
3669  * which is an array of 8 integers.  The bucket[] array
3670  * contains 8 different DMA transfer sizes (in 16
3671  * byte increments) which the controller uses to fetch
3672  * commands.  This function fills in bucket_map[], which
3673  * maps a given number of scatter gather elements to one of
3674  * the 8 DMA transfer sizes.  The point of it is to allow the
3675  * controller to only do as much DMA as needed to fetch the
3676  * command, with the DMA transfer size encoded in the lower
3677  * bits of the command address.
3678  */
3679 static void  calc_bucket_map(int bucket[], int num_buckets,
3680         int nsgs, int *bucket_map)
3681 {
3682         int i, j, b, size;
3683
3684         /* even a command with 0 SGs requires 4 blocks */
3685 #define MINIMUM_TRANSFER_BLOCKS 4
3686 #define NUM_BUCKETS 8
3687         /* Note, bucket_map must have nsgs+1 entries. */
3688         for (i = 0; i <= nsgs; i++) {
3689                 /* Compute size of a command with i SG entries */
3690                 size = i + MINIMUM_TRANSFER_BLOCKS;
3691                 b = num_buckets; /* Assume the biggest bucket */
3692                 /* Find the bucket that is just big enough */
3693                 for (j = 0; j < 8; j++) {
3694                         if (bucket[j] >= size) {
3695                                 b = j;
3696                                 break;
3697                         }
3698                 }
3699                 /* for a command with i SG entries, use bucket b. */
3700                 bucket_map[i] = b;
3701         }
3702 }
3703
3704 static void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h)
3705 {
3706         u32 trans_support;
3707         u64 trans_offset;
3708         /*  5 = 1 s/g entry or 4k
3709          *  6 = 2 s/g entry or 8k
3710          *  8 = 4 s/g entry or 16k
3711          * 10 = 6 s/g entry or 24k
3712          */
3713         int bft[8] = {5, 6, 8, 10, 12, 20, 28, 35}; /* for scatter/gathers */
3714         int i = 0;
3715         int l = 0;
3716         unsigned long register_value;
3717
3718         trans_support = readl(&(h->cfgtable->TransportSupport));
3719         if (!(trans_support & PERFORMANT_MODE))
3720                 return;
3721
3722         h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
3723         h->max_sg_entries = 32;
3724         /* Performant mode ring buffer and supporting data structures */
3725         h->reply_pool_size = h->max_commands * sizeof(u64);
3726         h->reply_pool = pci_alloc_consistent(h->pdev, h->reply_pool_size,
3727                                 &(h->reply_pool_dhandle));
3728
3729         /* Need a block fetch table for performant mode */
3730         h->blockFetchTable = kmalloc(((h->max_sg_entries+1) *
3731                                 sizeof(u32)), GFP_KERNEL);
3732
3733         if ((h->reply_pool == NULL)
3734                 || (h->blockFetchTable == NULL))
3735                 goto clean_up;
3736
3737         h->reply_pool_wraparound = 1; /* spec: init to 1 */
3738
3739         /* Controller spec: zero out this buffer. */
3740         memset(h->reply_pool, 0, h->reply_pool_size);
3741         h->reply_pool_head = h->reply_pool;
3742
3743         trans_offset = readl(&(h->cfgtable->TransMethodOffset));
3744         bft[7] = h->max_sg_entries + 4;
3745         calc_bucket_map(bft, ARRAY_SIZE(bft), 32, h->blockFetchTable);
3746         for (i = 0; i < 8; i++)
3747                 writel(bft[i], &h->transtable->BlockFetch[i]);
3748
3749         /* size of controller ring buffer */
3750         writel(h->max_commands, &h->transtable->RepQSize);
3751         writel(1, &h->transtable->RepQCount);
3752         writel(0, &h->transtable->RepQCtrAddrLow32);
3753         writel(0, &h->transtable->RepQCtrAddrHigh32);
3754         writel(h->reply_pool_dhandle, &h->transtable->RepQAddr0Low32);
3755         writel(0, &h->transtable->RepQAddr0High32);
3756         writel(CFGTBL_Trans_Performant,
3757                 &(h->cfgtable->HostWrite.TransportRequest));
3758         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
3759         /* under certain very rare conditions, this can take awhile.
3760          * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
3761          * as we enter this code.) */
3762         for (l = 0; l < MAX_CONFIG_WAIT; l++) {
3763                 register_value = readl(h->vaddr + SA5_DOORBELL);
3764                 if (!(register_value & CFGTBL_ChangeReq))
3765                         break;
3766                 /* delay and try again */
3767                 set_current_state(TASK_INTERRUPTIBLE);
3768                 schedule_timeout(10);
3769         }
3770         register_value = readl(&(h->cfgtable->TransportActive));
3771         if (!(register_value & CFGTBL_Trans_Performant)) {
3772                 dev_warn(&h->pdev->dev, "unable to get board into"
3773                                         " performant mode\n");
3774                 return;
3775         }
3776
3777         /* Change the access methods to the performant access methods */
3778         h->access = SA5_performant_access;
3779         h->transMethod = CFGTBL_Trans_Performant;
3780
3781         return;
3782
3783 clean_up:
3784         if (h->reply_pool)
3785                 pci_free_consistent(h->pdev, h->reply_pool_size,
3786                         h->reply_pool, h->reply_pool_dhandle);
3787         kfree(h->blockFetchTable);
3788 }
3789
3790 /*
3791  *  This is it.  Register the PCI driver information for the cards we control
3792  *  the OS will call our registered routines when it finds one of our cards.
3793  */
3794 static int __init hpsa_init(void)
3795 {
3796         int err;
3797         /* Start the scan thread */
3798         hpsa_scan_thread = kthread_run(hpsa_scan_func, NULL, "hpsa_scan");
3799         if (IS_ERR(hpsa_scan_thread)) {
3800                 err = PTR_ERR(hpsa_scan_thread);
3801                 return -ENODEV;
3802         }
3803         err = pci_register_driver(&hpsa_pci_driver);
3804         if (err)
3805                 kthread_stop(hpsa_scan_thread);
3806         return err;
3807 }
3808
3809 static void __exit hpsa_cleanup(void)
3810 {
3811         pci_unregister_driver(&hpsa_pci_driver);
3812         kthread_stop(hpsa_scan_thread);
3813 }
3814
3815 module_init(hpsa_init);
3816 module_exit(hpsa_cleanup);