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