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