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