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