hpsa: use helper routines for finishing commands
[firefly-linux-kernel-4.4.55.git] / drivers / scsi / hpsa.c
1 /*
2  *    Disk Array driver for HP Smart Array SAS controllers
3  *    Copyright 2000, 2014 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/pci-aspm.h>
27 #include <linux/kernel.h>
28 #include <linux/slab.h>
29 #include <linux/delay.h>
30 #include <linux/fs.h>
31 #include <linux/timer.h>
32 #include <linux/init.h>
33 #include <linux/spinlock.h>
34 #include <linux/compat.h>
35 #include <linux/blktrace_api.h>
36 #include <linux/uaccess.h>
37 #include <linux/io.h>
38 #include <linux/dma-mapping.h>
39 #include <linux/completion.h>
40 #include <linux/moduleparam.h>
41 #include <scsi/scsi.h>
42 #include <scsi/scsi_cmnd.h>
43 #include <scsi/scsi_device.h>
44 #include <scsi/scsi_host.h>
45 #include <scsi/scsi_tcq.h>
46 #include <scsi/scsi_eh.h>
47 #include <linux/cciss_ioctl.h>
48 #include <linux/string.h>
49 #include <linux/bitmap.h>
50 #include <linux/atomic.h>
51 #include <linux/jiffies.h>
52 #include <linux/percpu-defs.h>
53 #include <linux/percpu.h>
54 #include <asm/unaligned.h>
55 #include <asm/div64.h>
56 #include "hpsa_cmd.h"
57 #include "hpsa.h"
58
59 /* HPSA_DRIVER_VERSION must be 3 byte values (0-255) separated by '.' */
60 #define HPSA_DRIVER_VERSION "3.4.4-1"
61 #define DRIVER_NAME "HP HPSA Driver (v " HPSA_DRIVER_VERSION ")"
62 #define HPSA "hpsa"
63
64 /* How long to wait for CISS doorbell communication */
65 #define CLEAR_EVENT_WAIT_INTERVAL 20    /* ms for each msleep() call */
66 #define MODE_CHANGE_WAIT_INTERVAL 10    /* ms for each msleep() call */
67 #define MAX_CLEAR_EVENT_WAIT 30000      /* times 20 ms = 600 s */
68 #define MAX_MODE_CHANGE_WAIT 2000       /* times 10 ms = 20 s */
69 #define MAX_IOCTL_CONFIG_WAIT 1000
70
71 /*define how many times we will try a command because of bus resets */
72 #define MAX_CMD_RETRIES 3
73
74 /* Embedded module documentation macros - see modules.h */
75 MODULE_AUTHOR("Hewlett-Packard Company");
76 MODULE_DESCRIPTION("Driver for HP Smart Array Controller version " \
77         HPSA_DRIVER_VERSION);
78 MODULE_SUPPORTED_DEVICE("HP Smart Array Controllers");
79 MODULE_VERSION(HPSA_DRIVER_VERSION);
80 MODULE_LICENSE("GPL");
81
82 static int hpsa_allow_any;
83 module_param(hpsa_allow_any, int, S_IRUGO|S_IWUSR);
84 MODULE_PARM_DESC(hpsa_allow_any,
85                 "Allow hpsa driver to access unknown HP Smart Array hardware");
86 static int hpsa_simple_mode;
87 module_param(hpsa_simple_mode, int, S_IRUGO|S_IWUSR);
88 MODULE_PARM_DESC(hpsa_simple_mode,
89         "Use 'simple mode' rather than 'performant mode'");
90
91 /* define the PCI info for the cards we can control */
92 static const struct pci_device_id hpsa_pci_device_id[] = {
93         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3241},
94         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3243},
95         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3245},
96         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3247},
97         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3249},
98         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324A},
99         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324B},
100         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3233},
101         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3350},
102         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3351},
103         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3352},
104         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3353},
105         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3354},
106         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3355},
107         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSF,     0x103C, 0x3356},
108         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1921},
109         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1922},
110         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1923},
111         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1924},
112         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1926},
113         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1928},
114         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSH,     0x103C, 0x1929},
115         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21BD},
116         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21BE},
117         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21BF},
118         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C0},
119         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C1},
120         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C2},
121         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C3},
122         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C4},
123         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C5},
124         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C6},
125         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C7},
126         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C8},
127         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21C9},
128         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21CA},
129         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21CB},
130         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21CC},
131         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21CD},
132         {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSI,     0x103C, 0x21CE},
133         {PCI_VENDOR_ID_HP_3PAR, 0x0075, 0x1590, 0x0076},
134         {PCI_VENDOR_ID_HP_3PAR, 0x0075, 0x1590, 0x0087},
135         {PCI_VENDOR_ID_HP_3PAR, 0x0075, 0x1590, 0x007D},
136         {PCI_VENDOR_ID_HP_3PAR, 0x0075, 0x1590, 0x0088},
137         {PCI_VENDOR_ID_HP, 0x333f, 0x103c, 0x333f},
138         {PCI_VENDOR_ID_HP,     PCI_ANY_ID,      PCI_ANY_ID, PCI_ANY_ID,
139                 PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
140         {0,}
141 };
142
143 MODULE_DEVICE_TABLE(pci, hpsa_pci_device_id);
144
145 /*  board_id = Subsystem Device ID & Vendor ID
146  *  product = Marketing Name for the board
147  *  access = Address of the struct of function pointers
148  */
149 static struct board_type products[] = {
150         {0x3241103C, "Smart Array P212", &SA5_access},
151         {0x3243103C, "Smart Array P410", &SA5_access},
152         {0x3245103C, "Smart Array P410i", &SA5_access},
153         {0x3247103C, "Smart Array P411", &SA5_access},
154         {0x3249103C, "Smart Array P812", &SA5_access},
155         {0x324A103C, "Smart Array P712m", &SA5_access},
156         {0x324B103C, "Smart Array P711m", &SA5_access},
157         {0x3233103C, "HP StorageWorks 1210m", &SA5_access}, /* alias of 333f */
158         {0x3350103C, "Smart Array P222", &SA5_access},
159         {0x3351103C, "Smart Array P420", &SA5_access},
160         {0x3352103C, "Smart Array P421", &SA5_access},
161         {0x3353103C, "Smart Array P822", &SA5_access},
162         {0x3354103C, "Smart Array P420i", &SA5_access},
163         {0x3355103C, "Smart Array P220i", &SA5_access},
164         {0x3356103C, "Smart Array P721m", &SA5_access},
165         {0x1921103C, "Smart Array P830i", &SA5_access},
166         {0x1922103C, "Smart Array P430", &SA5_access},
167         {0x1923103C, "Smart Array P431", &SA5_access},
168         {0x1924103C, "Smart Array P830", &SA5_access},
169         {0x1926103C, "Smart Array P731m", &SA5_access},
170         {0x1928103C, "Smart Array P230i", &SA5_access},
171         {0x1929103C, "Smart Array P530", &SA5_access},
172         {0x21BD103C, "Smart Array P244br", &SA5_access},
173         {0x21BE103C, "Smart Array P741m", &SA5_access},
174         {0x21BF103C, "Smart HBA H240ar", &SA5_access},
175         {0x21C0103C, "Smart Array P440ar", &SA5_access},
176         {0x21C1103C, "Smart Array P840ar", &SA5_access},
177         {0x21C2103C, "Smart Array P440", &SA5_access},
178         {0x21C3103C, "Smart Array P441", &SA5_access},
179         {0x21C4103C, "Smart Array", &SA5_access},
180         {0x21C5103C, "Smart Array P841", &SA5_access},
181         {0x21C6103C, "Smart HBA H244br", &SA5_access},
182         {0x21C7103C, "Smart HBA H240", &SA5_access},
183         {0x21C8103C, "Smart HBA H241", &SA5_access},
184         {0x21C9103C, "Smart Array", &SA5_access},
185         {0x21CA103C, "Smart Array P246br", &SA5_access},
186         {0x21CB103C, "Smart Array P840", &SA5_access},
187         {0x21CC103C, "Smart Array", &SA5_access},
188         {0x21CD103C, "Smart Array", &SA5_access},
189         {0x21CE103C, "Smart HBA", &SA5_access},
190         {0x00761590, "HP Storage P1224 Array Controller", &SA5_access},
191         {0x00871590, "HP Storage P1224e Array Controller", &SA5_access},
192         {0x007D1590, "HP Storage P1228 Array Controller", &SA5_access},
193         {0x00881590, "HP Storage P1228e Array Controller", &SA5_access},
194         {0x333f103c, "HP StorageWorks 1210m Array Controller", &SA5_access},
195         {0xFFFF103C, "Unknown Smart Array", &SA5_access},
196 };
197
198 static int number_of_controllers;
199
200 static irqreturn_t do_hpsa_intr_intx(int irq, void *dev_id);
201 static irqreturn_t do_hpsa_intr_msi(int irq, void *dev_id);
202 static int hpsa_ioctl(struct scsi_device *dev, int cmd, void __user *arg);
203
204 #ifdef CONFIG_COMPAT
205 static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd,
206         void __user *arg);
207 #endif
208
209 static void cmd_free(struct ctlr_info *h, struct CommandList *c);
210 static struct CommandList *cmd_alloc(struct ctlr_info *h);
211 static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
212         void *buff, size_t size, u16 page_code, unsigned char *scsi3addr,
213         int cmd_type);
214 static void hpsa_free_cmd_pool(struct ctlr_info *h);
215 #define VPD_PAGE (1 << 8)
216
217 static int hpsa_scsi_queue_command(struct Scsi_Host *h, struct scsi_cmnd *cmd);
218 static void hpsa_scan_start(struct Scsi_Host *);
219 static int hpsa_scan_finished(struct Scsi_Host *sh,
220         unsigned long elapsed_time);
221 static int hpsa_change_queue_depth(struct scsi_device *sdev, int qdepth);
222
223 static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd);
224 static int hpsa_eh_abort_handler(struct scsi_cmnd *scsicmd);
225 static int hpsa_slave_alloc(struct scsi_device *sdev);
226 static int hpsa_slave_configure(struct scsi_device *sdev);
227 static void hpsa_slave_destroy(struct scsi_device *sdev);
228
229 static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno);
230 static int check_for_unit_attention(struct ctlr_info *h,
231         struct CommandList *c);
232 static void check_ioctl_unit_attention(struct ctlr_info *h,
233         struct CommandList *c);
234 /* performant mode helper functions */
235 static void calc_bucket_map(int *bucket, int num_buckets,
236         int nsgs, int min_blocks, u32 *bucket_map);
237 static void hpsa_free_performant_mode(struct ctlr_info *h);
238 static int hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h);
239 static inline u32 next_command(struct ctlr_info *h, u8 q);
240 static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
241                                u32 *cfg_base_addr, u64 *cfg_base_addr_index,
242                                u64 *cfg_offset);
243 static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
244                                     unsigned long *memory_bar);
245 static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id);
246 static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
247                                      int wait_for_ready);
248 static inline void finish_cmd(struct CommandList *c);
249 static int hpsa_wait_for_mode_change_ack(struct ctlr_info *h);
250 #define BOARD_NOT_READY 0
251 #define BOARD_READY 1
252 static void hpsa_drain_accel_commands(struct ctlr_info *h);
253 static void hpsa_flush_cache(struct ctlr_info *h);
254 static int hpsa_scsi_ioaccel_queue_command(struct ctlr_info *h,
255         struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
256         u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk);
257 static void hpsa_command_resubmit_worker(struct work_struct *work);
258 static u32 lockup_detected(struct ctlr_info *h);
259 static int detect_controller_lockup(struct ctlr_info *h);
260
261 static inline struct ctlr_info *sdev_to_hba(struct scsi_device *sdev)
262 {
263         unsigned long *priv = shost_priv(sdev->host);
264         return (struct ctlr_info *) *priv;
265 }
266
267 static inline struct ctlr_info *shost_to_hba(struct Scsi_Host *sh)
268 {
269         unsigned long *priv = shost_priv(sh);
270         return (struct ctlr_info *) *priv;
271 }
272
273 /* extract sense key, asc, and ascq from sense data.  -1 means invalid. */
274 static void decode_sense_data(const u8 *sense_data, int sense_data_len,
275                         u8 *sense_key, u8 *asc, u8 *ascq)
276 {
277         struct scsi_sense_hdr sshdr;
278         bool rc;
279
280         *sense_key = -1;
281         *asc = -1;
282         *ascq = -1;
283
284         if (sense_data_len < 1)
285                 return;
286
287         rc = scsi_normalize_sense(sense_data, sense_data_len, &sshdr);
288         if (rc) {
289                 *sense_key = sshdr.sense_key;
290                 *asc = sshdr.asc;
291                 *ascq = sshdr.ascq;
292         }
293 }
294
295 static int check_for_unit_attention(struct ctlr_info *h,
296         struct CommandList *c)
297 {
298         u8 sense_key, asc, ascq;
299         int sense_len;
300
301         if (c->err_info->SenseLen > sizeof(c->err_info->SenseInfo))
302                 sense_len = sizeof(c->err_info->SenseInfo);
303         else
304                 sense_len = c->err_info->SenseLen;
305
306         decode_sense_data(c->err_info->SenseInfo, sense_len,
307                                 &sense_key, &asc, &ascq);
308         if (sense_key != UNIT_ATTENTION || asc == -1)
309                 return 0;
310
311         switch (asc) {
312         case STATE_CHANGED:
313                 dev_warn(&h->pdev->dev,
314                         HPSA "%d: a state change detected, command retried\n",
315                         h->ctlr);
316                 break;
317         case LUN_FAILED:
318                 dev_warn(&h->pdev->dev,
319                         HPSA "%d: LUN failure detected\n", h->ctlr);
320                 break;
321         case REPORT_LUNS_CHANGED:
322                 dev_warn(&h->pdev->dev,
323                         HPSA "%d: report LUN data changed\n", h->ctlr);
324         /*
325          * Note: this REPORT_LUNS_CHANGED condition only occurs on the external
326          * target (array) devices.
327          */
328                 break;
329         case POWER_OR_RESET:
330                 dev_warn(&h->pdev->dev, HPSA "%d: a power on "
331                         "or device reset detected\n", h->ctlr);
332                 break;
333         case UNIT_ATTENTION_CLEARED:
334                 dev_warn(&h->pdev->dev, HPSA "%d: unit attention "
335                     "cleared by another initiator\n", h->ctlr);
336                 break;
337         default:
338                 dev_warn(&h->pdev->dev, HPSA "%d: unknown "
339                         "unit attention detected\n", h->ctlr);
340                 break;
341         }
342         return 1;
343 }
344
345 static int check_for_busy(struct ctlr_info *h, struct CommandList *c)
346 {
347         if (c->err_info->CommandStatus != CMD_TARGET_STATUS ||
348                 (c->err_info->ScsiStatus != SAM_STAT_BUSY &&
349                  c->err_info->ScsiStatus != SAM_STAT_TASK_SET_FULL))
350                 return 0;
351         dev_warn(&h->pdev->dev, HPSA "device busy");
352         return 1;
353 }
354
355 static u32 lockup_detected(struct ctlr_info *h);
356 static ssize_t host_show_lockup_detected(struct device *dev,
357                 struct device_attribute *attr, char *buf)
358 {
359         int ld;
360         struct ctlr_info *h;
361         struct Scsi_Host *shost = class_to_shost(dev);
362
363         h = shost_to_hba(shost);
364         ld = lockup_detected(h);
365
366         return sprintf(buf, "ld=%d\n", ld);
367 }
368
369 static ssize_t host_store_hp_ssd_smart_path_status(struct device *dev,
370                                          struct device_attribute *attr,
371                                          const char *buf, size_t count)
372 {
373         int status, len;
374         struct ctlr_info *h;
375         struct Scsi_Host *shost = class_to_shost(dev);
376         char tmpbuf[10];
377
378         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
379                 return -EACCES;
380         len = count > sizeof(tmpbuf) - 1 ? sizeof(tmpbuf) - 1 : count;
381         strncpy(tmpbuf, buf, len);
382         tmpbuf[len] = '\0';
383         if (sscanf(tmpbuf, "%d", &status) != 1)
384                 return -EINVAL;
385         h = shost_to_hba(shost);
386         h->acciopath_status = !!status;
387         dev_warn(&h->pdev->dev,
388                 "hpsa: HP SSD Smart Path %s via sysfs update.\n",
389                 h->acciopath_status ? "enabled" : "disabled");
390         return count;
391 }
392
393 static ssize_t host_store_raid_offload_debug(struct device *dev,
394                                          struct device_attribute *attr,
395                                          const char *buf, size_t count)
396 {
397         int debug_level, len;
398         struct ctlr_info *h;
399         struct Scsi_Host *shost = class_to_shost(dev);
400         char tmpbuf[10];
401
402         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
403                 return -EACCES;
404         len = count > sizeof(tmpbuf) - 1 ? sizeof(tmpbuf) - 1 : count;
405         strncpy(tmpbuf, buf, len);
406         tmpbuf[len] = '\0';
407         if (sscanf(tmpbuf, "%d", &debug_level) != 1)
408                 return -EINVAL;
409         if (debug_level < 0)
410                 debug_level = 0;
411         h = shost_to_hba(shost);
412         h->raid_offload_debug = debug_level;
413         dev_warn(&h->pdev->dev, "hpsa: Set raid_offload_debug level = %d\n",
414                 h->raid_offload_debug);
415         return count;
416 }
417
418 static ssize_t host_store_rescan(struct device *dev,
419                                  struct device_attribute *attr,
420                                  const char *buf, size_t count)
421 {
422         struct ctlr_info *h;
423         struct Scsi_Host *shost = class_to_shost(dev);
424         h = shost_to_hba(shost);
425         hpsa_scan_start(h->scsi_host);
426         return count;
427 }
428
429 static ssize_t host_show_firmware_revision(struct device *dev,
430              struct device_attribute *attr, char *buf)
431 {
432         struct ctlr_info *h;
433         struct Scsi_Host *shost = class_to_shost(dev);
434         unsigned char *fwrev;
435
436         h = shost_to_hba(shost);
437         if (!h->hba_inquiry_data)
438                 return 0;
439         fwrev = &h->hba_inquiry_data[32];
440         return snprintf(buf, 20, "%c%c%c%c\n",
441                 fwrev[0], fwrev[1], fwrev[2], fwrev[3]);
442 }
443
444 static ssize_t host_show_commands_outstanding(struct device *dev,
445              struct device_attribute *attr, char *buf)
446 {
447         struct Scsi_Host *shost = class_to_shost(dev);
448         struct ctlr_info *h = shost_to_hba(shost);
449
450         return snprintf(buf, 20, "%d\n",
451                         atomic_read(&h->commands_outstanding));
452 }
453
454 static ssize_t host_show_transport_mode(struct device *dev,
455         struct device_attribute *attr, char *buf)
456 {
457         struct ctlr_info *h;
458         struct Scsi_Host *shost = class_to_shost(dev);
459
460         h = shost_to_hba(shost);
461         return snprintf(buf, 20, "%s\n",
462                 h->transMethod & CFGTBL_Trans_Performant ?
463                         "performant" : "simple");
464 }
465
466 static ssize_t host_show_hp_ssd_smart_path_status(struct device *dev,
467         struct device_attribute *attr, char *buf)
468 {
469         struct ctlr_info *h;
470         struct Scsi_Host *shost = class_to_shost(dev);
471
472         h = shost_to_hba(shost);
473         return snprintf(buf, 30, "HP SSD Smart Path %s\n",
474                 (h->acciopath_status == 1) ?  "enabled" : "disabled");
475 }
476
477 /* List of controllers which cannot be hard reset on kexec with reset_devices */
478 static u32 unresettable_controller[] = {
479         0x324a103C, /* Smart Array P712m */
480         0x324b103C, /* Smart Array P711m */
481         0x3223103C, /* Smart Array P800 */
482         0x3234103C, /* Smart Array P400 */
483         0x3235103C, /* Smart Array P400i */
484         0x3211103C, /* Smart Array E200i */
485         0x3212103C, /* Smart Array E200 */
486         0x3213103C, /* Smart Array E200i */
487         0x3214103C, /* Smart Array E200i */
488         0x3215103C, /* Smart Array E200i */
489         0x3237103C, /* Smart Array E500 */
490         0x323D103C, /* Smart Array P700m */
491         0x40800E11, /* Smart Array 5i */
492         0x409C0E11, /* Smart Array 6400 */
493         0x409D0E11, /* Smart Array 6400 EM */
494         0x40700E11, /* Smart Array 5300 */
495         0x40820E11, /* Smart Array 532 */
496         0x40830E11, /* Smart Array 5312 */
497         0x409A0E11, /* Smart Array 641 */
498         0x409B0E11, /* Smart Array 642 */
499         0x40910E11, /* Smart Array 6i */
500 };
501
502 /* List of controllers which cannot even be soft reset */
503 static u32 soft_unresettable_controller[] = {
504         0x40800E11, /* Smart Array 5i */
505         0x40700E11, /* Smart Array 5300 */
506         0x40820E11, /* Smart Array 532 */
507         0x40830E11, /* Smart Array 5312 */
508         0x409A0E11, /* Smart Array 641 */
509         0x409B0E11, /* Smart Array 642 */
510         0x40910E11, /* Smart Array 6i */
511         /* Exclude 640x boards.  These are two pci devices in one slot
512          * which share a battery backed cache module.  One controls the
513          * cache, the other accesses the cache through the one that controls
514          * it.  If we reset the one controlling the cache, the other will
515          * likely not be happy.  Just forbid resetting this conjoined mess.
516          * The 640x isn't really supported by hpsa anyway.
517          */
518         0x409C0E11, /* Smart Array 6400 */
519         0x409D0E11, /* Smart Array 6400 EM */
520 };
521
522 static u32 needs_abort_tags_swizzled[] = {
523         0x323D103C, /* Smart Array P700m */
524         0x324a103C, /* Smart Array P712m */
525         0x324b103C, /* SmartArray P711m */
526 };
527
528 static int board_id_in_array(u32 a[], int nelems, u32 board_id)
529 {
530         int i;
531
532         for (i = 0; i < nelems; i++)
533                 if (a[i] == board_id)
534                         return 1;
535         return 0;
536 }
537
538 static int ctlr_is_hard_resettable(u32 board_id)
539 {
540         return !board_id_in_array(unresettable_controller,
541                         ARRAY_SIZE(unresettable_controller), board_id);
542 }
543
544 static int ctlr_is_soft_resettable(u32 board_id)
545 {
546         return !board_id_in_array(soft_unresettable_controller,
547                         ARRAY_SIZE(soft_unresettable_controller), board_id);
548 }
549
550 static int ctlr_is_resettable(u32 board_id)
551 {
552         return ctlr_is_hard_resettable(board_id) ||
553                 ctlr_is_soft_resettable(board_id);
554 }
555
556 static int ctlr_needs_abort_tags_swizzled(u32 board_id)
557 {
558         return board_id_in_array(needs_abort_tags_swizzled,
559                         ARRAY_SIZE(needs_abort_tags_swizzled), board_id);
560 }
561
562 static ssize_t host_show_resettable(struct device *dev,
563         struct device_attribute *attr, char *buf)
564 {
565         struct ctlr_info *h;
566         struct Scsi_Host *shost = class_to_shost(dev);
567
568         h = shost_to_hba(shost);
569         return snprintf(buf, 20, "%d\n", ctlr_is_resettable(h->board_id));
570 }
571
572 static inline int is_logical_dev_addr_mode(unsigned char scsi3addr[])
573 {
574         return (scsi3addr[3] & 0xC0) == 0x40;
575 }
576
577 static const char * const raid_label[] = { "0", "4", "1(+0)", "5", "5+1", "6",
578         "1(+0)ADM", "UNKNOWN"
579 };
580 #define HPSA_RAID_0     0
581 #define HPSA_RAID_4     1
582 #define HPSA_RAID_1     2       /* also used for RAID 10 */
583 #define HPSA_RAID_5     3       /* also used for RAID 50 */
584 #define HPSA_RAID_51    4
585 #define HPSA_RAID_6     5       /* also used for RAID 60 */
586 #define HPSA_RAID_ADM   6       /* also used for RAID 1+0 ADM */
587 #define RAID_UNKNOWN (ARRAY_SIZE(raid_label) - 1)
588
589 static ssize_t raid_level_show(struct device *dev,
590              struct device_attribute *attr, char *buf)
591 {
592         ssize_t l = 0;
593         unsigned char rlevel;
594         struct ctlr_info *h;
595         struct scsi_device *sdev;
596         struct hpsa_scsi_dev_t *hdev;
597         unsigned long flags;
598
599         sdev = to_scsi_device(dev);
600         h = sdev_to_hba(sdev);
601         spin_lock_irqsave(&h->lock, flags);
602         hdev = sdev->hostdata;
603         if (!hdev) {
604                 spin_unlock_irqrestore(&h->lock, flags);
605                 return -ENODEV;
606         }
607
608         /* Is this even a logical drive? */
609         if (!is_logical_dev_addr_mode(hdev->scsi3addr)) {
610                 spin_unlock_irqrestore(&h->lock, flags);
611                 l = snprintf(buf, PAGE_SIZE, "N/A\n");
612                 return l;
613         }
614
615         rlevel = hdev->raid_level;
616         spin_unlock_irqrestore(&h->lock, flags);
617         if (rlevel > RAID_UNKNOWN)
618                 rlevel = RAID_UNKNOWN;
619         l = snprintf(buf, PAGE_SIZE, "RAID %s\n", raid_label[rlevel]);
620         return l;
621 }
622
623 static ssize_t lunid_show(struct device *dev,
624              struct device_attribute *attr, char *buf)
625 {
626         struct ctlr_info *h;
627         struct scsi_device *sdev;
628         struct hpsa_scsi_dev_t *hdev;
629         unsigned long flags;
630         unsigned char lunid[8];
631
632         sdev = to_scsi_device(dev);
633         h = sdev_to_hba(sdev);
634         spin_lock_irqsave(&h->lock, flags);
635         hdev = sdev->hostdata;
636         if (!hdev) {
637                 spin_unlock_irqrestore(&h->lock, flags);
638                 return -ENODEV;
639         }
640         memcpy(lunid, hdev->scsi3addr, sizeof(lunid));
641         spin_unlock_irqrestore(&h->lock, flags);
642         return snprintf(buf, 20, "0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
643                 lunid[0], lunid[1], lunid[2], lunid[3],
644                 lunid[4], lunid[5], lunid[6], lunid[7]);
645 }
646
647 static ssize_t unique_id_show(struct device *dev,
648              struct device_attribute *attr, char *buf)
649 {
650         struct ctlr_info *h;
651         struct scsi_device *sdev;
652         struct hpsa_scsi_dev_t *hdev;
653         unsigned long flags;
654         unsigned char sn[16];
655
656         sdev = to_scsi_device(dev);
657         h = sdev_to_hba(sdev);
658         spin_lock_irqsave(&h->lock, flags);
659         hdev = sdev->hostdata;
660         if (!hdev) {
661                 spin_unlock_irqrestore(&h->lock, flags);
662                 return -ENODEV;
663         }
664         memcpy(sn, hdev->device_id, sizeof(sn));
665         spin_unlock_irqrestore(&h->lock, flags);
666         return snprintf(buf, 16 * 2 + 2,
667                         "%02X%02X%02X%02X%02X%02X%02X%02X"
668                         "%02X%02X%02X%02X%02X%02X%02X%02X\n",
669                         sn[0], sn[1], sn[2], sn[3],
670                         sn[4], sn[5], sn[6], sn[7],
671                         sn[8], sn[9], sn[10], sn[11],
672                         sn[12], sn[13], sn[14], sn[15]);
673 }
674
675 static ssize_t host_show_hp_ssd_smart_path_enabled(struct device *dev,
676              struct device_attribute *attr, char *buf)
677 {
678         struct ctlr_info *h;
679         struct scsi_device *sdev;
680         struct hpsa_scsi_dev_t *hdev;
681         unsigned long flags;
682         int offload_enabled;
683
684         sdev = to_scsi_device(dev);
685         h = sdev_to_hba(sdev);
686         spin_lock_irqsave(&h->lock, flags);
687         hdev = sdev->hostdata;
688         if (!hdev) {
689                 spin_unlock_irqrestore(&h->lock, flags);
690                 return -ENODEV;
691         }
692         offload_enabled = hdev->offload_enabled;
693         spin_unlock_irqrestore(&h->lock, flags);
694         return snprintf(buf, 20, "%d\n", offload_enabled);
695 }
696
697 static DEVICE_ATTR(raid_level, S_IRUGO, raid_level_show, NULL);
698 static DEVICE_ATTR(lunid, S_IRUGO, lunid_show, NULL);
699 static DEVICE_ATTR(unique_id, S_IRUGO, unique_id_show, NULL);
700 static DEVICE_ATTR(rescan, S_IWUSR, NULL, host_store_rescan);
701 static DEVICE_ATTR(hp_ssd_smart_path_enabled, S_IRUGO,
702                         host_show_hp_ssd_smart_path_enabled, NULL);
703 static DEVICE_ATTR(hp_ssd_smart_path_status, S_IWUSR|S_IRUGO|S_IROTH,
704                 host_show_hp_ssd_smart_path_status,
705                 host_store_hp_ssd_smart_path_status);
706 static DEVICE_ATTR(raid_offload_debug, S_IWUSR, NULL,
707                         host_store_raid_offload_debug);
708 static DEVICE_ATTR(firmware_revision, S_IRUGO,
709         host_show_firmware_revision, NULL);
710 static DEVICE_ATTR(commands_outstanding, S_IRUGO,
711         host_show_commands_outstanding, NULL);
712 static DEVICE_ATTR(transport_mode, S_IRUGO,
713         host_show_transport_mode, NULL);
714 static DEVICE_ATTR(resettable, S_IRUGO,
715         host_show_resettable, NULL);
716 static DEVICE_ATTR(lockup_detected, S_IRUGO,
717         host_show_lockup_detected, NULL);
718
719 static struct device_attribute *hpsa_sdev_attrs[] = {
720         &dev_attr_raid_level,
721         &dev_attr_lunid,
722         &dev_attr_unique_id,
723         &dev_attr_hp_ssd_smart_path_enabled,
724         &dev_attr_lockup_detected,
725         NULL,
726 };
727
728 static struct device_attribute *hpsa_shost_attrs[] = {
729         &dev_attr_rescan,
730         &dev_attr_firmware_revision,
731         &dev_attr_commands_outstanding,
732         &dev_attr_transport_mode,
733         &dev_attr_resettable,
734         &dev_attr_hp_ssd_smart_path_status,
735         &dev_attr_raid_offload_debug,
736         NULL,
737 };
738
739 #define HPSA_NRESERVED_CMDS     (HPSA_CMDS_RESERVED_FOR_ABORTS + \
740                 HPSA_CMDS_RESERVED_FOR_DRIVER + HPSA_MAX_CONCURRENT_PASSTHRUS)
741
742 static struct scsi_host_template hpsa_driver_template = {
743         .module                 = THIS_MODULE,
744         .name                   = HPSA,
745         .proc_name              = HPSA,
746         .queuecommand           = hpsa_scsi_queue_command,
747         .scan_start             = hpsa_scan_start,
748         .scan_finished          = hpsa_scan_finished,
749         .change_queue_depth     = hpsa_change_queue_depth,
750         .this_id                = -1,
751         .use_clustering         = ENABLE_CLUSTERING,
752         .eh_abort_handler       = hpsa_eh_abort_handler,
753         .eh_device_reset_handler = hpsa_eh_device_reset_handler,
754         .ioctl                  = hpsa_ioctl,
755         .slave_alloc            = hpsa_slave_alloc,
756         .slave_configure        = hpsa_slave_configure,
757         .slave_destroy          = hpsa_slave_destroy,
758 #ifdef CONFIG_COMPAT
759         .compat_ioctl           = hpsa_compat_ioctl,
760 #endif
761         .sdev_attrs = hpsa_sdev_attrs,
762         .shost_attrs = hpsa_shost_attrs,
763         .max_sectors = 8192,
764         .no_write_same = 1,
765 };
766
767 static inline u32 next_command(struct ctlr_info *h, u8 q)
768 {
769         u32 a;
770         struct reply_queue_buffer *rq = &h->reply_queue[q];
771
772         if (h->transMethod & CFGTBL_Trans_io_accel1)
773                 return h->access.command_completed(h, q);
774
775         if (unlikely(!(h->transMethod & CFGTBL_Trans_Performant)))
776                 return h->access.command_completed(h, q);
777
778         if ((rq->head[rq->current_entry] & 1) == rq->wraparound) {
779                 a = rq->head[rq->current_entry];
780                 rq->current_entry++;
781                 atomic_dec(&h->commands_outstanding);
782         } else {
783                 a = FIFO_EMPTY;
784         }
785         /* Check for wraparound */
786         if (rq->current_entry == h->max_commands) {
787                 rq->current_entry = 0;
788                 rq->wraparound ^= 1;
789         }
790         return a;
791 }
792
793 /*
794  * There are some special bits in the bus address of the
795  * command that we have to set for the controller to know
796  * how to process the command:
797  *
798  * Normal performant mode:
799  * bit 0: 1 means performant mode, 0 means simple mode.
800  * bits 1-3 = block fetch table entry
801  * bits 4-6 = command type (== 0)
802  *
803  * ioaccel1 mode:
804  * bit 0 = "performant mode" bit.
805  * bits 1-3 = block fetch table entry
806  * bits 4-6 = command type (== 110)
807  * (command type is needed because ioaccel1 mode
808  * commands are submitted through the same register as normal
809  * mode commands, so this is how the controller knows whether
810  * the command is normal mode or ioaccel1 mode.)
811  *
812  * ioaccel2 mode:
813  * bit 0 = "performant mode" bit.
814  * bits 1-4 = block fetch table entry (note extra bit)
815  * bits 4-6 = not needed, because ioaccel2 mode has
816  * a separate special register for submitting commands.
817  */
818
819 /*
820  * set_performant_mode: Modify the tag for cciss performant
821  * set bit 0 for pull model, bits 3-1 for block fetch
822  * register number
823  */
824 #define DEFAULT_REPLY_QUEUE (-1)
825 static void set_performant_mode(struct ctlr_info *h, struct CommandList *c,
826                                         int reply_queue)
827 {
828         if (likely(h->transMethod & CFGTBL_Trans_Performant)) {
829                 c->busaddr |= 1 | (h->blockFetchTable[c->Header.SGList] << 1);
830                 if (unlikely(!h->msix_vector))
831                         return;
832                 if (likely(reply_queue == DEFAULT_REPLY_QUEUE))
833                         c->Header.ReplyQueue =
834                                 raw_smp_processor_id() % h->nreply_queues;
835                 else
836                         c->Header.ReplyQueue = reply_queue % h->nreply_queues;
837         }
838 }
839
840 static void set_ioaccel1_performant_mode(struct ctlr_info *h,
841                                                 struct CommandList *c,
842                                                 int reply_queue)
843 {
844         struct io_accel1_cmd *cp = &h->ioaccel_cmd_pool[c->cmdindex];
845
846         /*
847          * Tell the controller to post the reply to the queue for this
848          * processor.  This seems to give the best I/O throughput.
849          */
850         if (likely(reply_queue == DEFAULT_REPLY_QUEUE))
851                 cp->ReplyQueue = smp_processor_id() % h->nreply_queues;
852         else
853                 cp->ReplyQueue = reply_queue % h->nreply_queues;
854         /*
855          * Set the bits in the address sent down to include:
856          *  - performant mode bit (bit 0)
857          *  - pull count (bits 1-3)
858          *  - command type (bits 4-6)
859          */
860         c->busaddr |= 1 | (h->ioaccel1_blockFetchTable[c->Header.SGList] << 1) |
861                                         IOACCEL1_BUSADDR_CMDTYPE;
862 }
863
864 static void set_ioaccel2_tmf_performant_mode(struct ctlr_info *h,
865                                                 struct CommandList *c,
866                                                 int reply_queue)
867 {
868         struct hpsa_tmf_struct *cp = (struct hpsa_tmf_struct *)
869                 &h->ioaccel2_cmd_pool[c->cmdindex];
870
871         /* Tell the controller to post the reply to the queue for this
872          * processor.  This seems to give the best I/O throughput.
873          */
874         if (likely(reply_queue == DEFAULT_REPLY_QUEUE))
875                 cp->reply_queue = smp_processor_id() % h->nreply_queues;
876         else
877                 cp->reply_queue = reply_queue % h->nreply_queues;
878         /* Set the bits in the address sent down to include:
879          *  - performant mode bit not used in ioaccel mode 2
880          *  - pull count (bits 0-3)
881          *  - command type isn't needed for ioaccel2
882          */
883         c->busaddr |= h->ioaccel2_blockFetchTable[0];
884 }
885
886 static void set_ioaccel2_performant_mode(struct ctlr_info *h,
887                                                 struct CommandList *c,
888                                                 int reply_queue)
889 {
890         struct io_accel2_cmd *cp = &h->ioaccel2_cmd_pool[c->cmdindex];
891
892         /*
893          * Tell the controller to post the reply to the queue for this
894          * processor.  This seems to give the best I/O throughput.
895          */
896         if (likely(reply_queue == DEFAULT_REPLY_QUEUE))
897                 cp->reply_queue = smp_processor_id() % h->nreply_queues;
898         else
899                 cp->reply_queue = reply_queue % h->nreply_queues;
900         /*
901          * Set the bits in the address sent down to include:
902          *  - performant mode bit not used in ioaccel mode 2
903          *  - pull count (bits 0-3)
904          *  - command type isn't needed for ioaccel2
905          */
906         c->busaddr |= (h->ioaccel2_blockFetchTable[cp->sg_count]);
907 }
908
909 static int is_firmware_flash_cmd(u8 *cdb)
910 {
911         return cdb[0] == BMIC_WRITE && cdb[6] == BMIC_FLASH_FIRMWARE;
912 }
913
914 /*
915  * During firmware flash, the heartbeat register may not update as frequently
916  * as it should.  So we dial down lockup detection during firmware flash. and
917  * dial it back up when firmware flash completes.
918  */
919 #define HEARTBEAT_SAMPLE_INTERVAL_DURING_FLASH (240 * HZ)
920 #define HEARTBEAT_SAMPLE_INTERVAL (30 * HZ)
921 static void dial_down_lockup_detection_during_fw_flash(struct ctlr_info *h,
922                 struct CommandList *c)
923 {
924         if (!is_firmware_flash_cmd(c->Request.CDB))
925                 return;
926         atomic_inc(&h->firmware_flash_in_progress);
927         h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL_DURING_FLASH;
928 }
929
930 static void dial_up_lockup_detection_on_fw_flash_complete(struct ctlr_info *h,
931                 struct CommandList *c)
932 {
933         if (is_firmware_flash_cmd(c->Request.CDB) &&
934                 atomic_dec_and_test(&h->firmware_flash_in_progress))
935                 h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
936 }
937
938 static void __enqueue_cmd_and_start_io(struct ctlr_info *h,
939         struct CommandList *c, int reply_queue)
940 {
941         dial_down_lockup_detection_during_fw_flash(h, c);
942         atomic_inc(&h->commands_outstanding);
943         switch (c->cmd_type) {
944         case CMD_IOACCEL1:
945                 set_ioaccel1_performant_mode(h, c, reply_queue);
946                 writel(c->busaddr, h->vaddr + SA5_REQUEST_PORT_OFFSET);
947                 break;
948         case CMD_IOACCEL2:
949                 set_ioaccel2_performant_mode(h, c, reply_queue);
950                 writel(c->busaddr, h->vaddr + IOACCEL2_INBOUND_POSTQ_32);
951                 break;
952         case IOACCEL2_TMF:
953                 set_ioaccel2_tmf_performant_mode(h, c, reply_queue);
954                 writel(c->busaddr, h->vaddr + IOACCEL2_INBOUND_POSTQ_32);
955                 break;
956         default:
957                 set_performant_mode(h, c, reply_queue);
958                 h->access.submit_command(h, c);
959         }
960 }
961
962 static void enqueue_cmd_and_start_io(struct ctlr_info *h,
963                                         struct CommandList *c)
964 {
965         __enqueue_cmd_and_start_io(h, c, DEFAULT_REPLY_QUEUE);
966 }
967
968 static inline int is_hba_lunid(unsigned char scsi3addr[])
969 {
970         return memcmp(scsi3addr, RAID_CTLR_LUNID, 8) == 0;
971 }
972
973 static inline int is_scsi_rev_5(struct ctlr_info *h)
974 {
975         if (!h->hba_inquiry_data)
976                 return 0;
977         if ((h->hba_inquiry_data[2] & 0x07) == 5)
978                 return 1;
979         return 0;
980 }
981
982 static int hpsa_find_target_lun(struct ctlr_info *h,
983         unsigned char scsi3addr[], int bus, int *target, int *lun)
984 {
985         /* finds an unused bus, target, lun for a new physical device
986          * assumes h->devlock is held
987          */
988         int i, found = 0;
989         DECLARE_BITMAP(lun_taken, HPSA_MAX_DEVICES);
990
991         bitmap_zero(lun_taken, HPSA_MAX_DEVICES);
992
993         for (i = 0; i < h->ndevices; i++) {
994                 if (h->dev[i]->bus == bus && h->dev[i]->target != -1)
995                         __set_bit(h->dev[i]->target, lun_taken);
996         }
997
998         i = find_first_zero_bit(lun_taken, HPSA_MAX_DEVICES);
999         if (i < HPSA_MAX_DEVICES) {
1000                 /* *bus = 1; */
1001                 *target = i;
1002                 *lun = 0;
1003                 found = 1;
1004         }
1005         return !found;
1006 }
1007
1008 static inline void hpsa_show_dev_msg(const char *level, struct ctlr_info *h,
1009         struct hpsa_scsi_dev_t *dev, char *description)
1010 {
1011         dev_printk(level, &h->pdev->dev,
1012                         "scsi %d:%d:%d:%d: %s %s %.8s %.16s RAID-%s SSDSmartPathCap%c En%c Exp=%d\n",
1013                         h->scsi_host->host_no, dev->bus, dev->target, dev->lun,
1014                         description,
1015                         scsi_device_type(dev->devtype),
1016                         dev->vendor,
1017                         dev->model,
1018                         dev->raid_level > RAID_UNKNOWN ?
1019                                 "RAID-?" : raid_label[dev->raid_level],
1020                         dev->offload_config ? '+' : '-',
1021                         dev->offload_enabled ? '+' : '-',
1022                         dev->expose_state);
1023 }
1024
1025 /* Add an entry into h->dev[] array. */
1026 static int hpsa_scsi_add_entry(struct ctlr_info *h, int hostno,
1027                 struct hpsa_scsi_dev_t *device,
1028                 struct hpsa_scsi_dev_t *added[], int *nadded)
1029 {
1030         /* assumes h->devlock is held */
1031         int n = h->ndevices;
1032         int i;
1033         unsigned char addr1[8], addr2[8];
1034         struct hpsa_scsi_dev_t *sd;
1035
1036         if (n >= HPSA_MAX_DEVICES) {
1037                 dev_err(&h->pdev->dev, "too many devices, some will be "
1038                         "inaccessible.\n");
1039                 return -1;
1040         }
1041
1042         /* physical devices do not have lun or target assigned until now. */
1043         if (device->lun != -1)
1044                 /* Logical device, lun is already assigned. */
1045                 goto lun_assigned;
1046
1047         /* If this device a non-zero lun of a multi-lun device
1048          * byte 4 of the 8-byte LUN addr will contain the logical
1049          * unit no, zero otherwise.
1050          */
1051         if (device->scsi3addr[4] == 0) {
1052                 /* This is not a non-zero lun of a multi-lun device */
1053                 if (hpsa_find_target_lun(h, device->scsi3addr,
1054                         device->bus, &device->target, &device->lun) != 0)
1055                         return -1;
1056                 goto lun_assigned;
1057         }
1058
1059         /* This is a non-zero lun of a multi-lun device.
1060          * Search through our list and find the device which
1061          * has the same 8 byte LUN address, excepting byte 4.
1062          * Assign the same bus and target for this new LUN.
1063          * Use the logical unit number from the firmware.
1064          */
1065         memcpy(addr1, device->scsi3addr, 8);
1066         addr1[4] = 0;
1067         for (i = 0; i < n; i++) {
1068                 sd = h->dev[i];
1069                 memcpy(addr2, sd->scsi3addr, 8);
1070                 addr2[4] = 0;
1071                 /* differ only in byte 4? */
1072                 if (memcmp(addr1, addr2, 8) == 0) {
1073                         device->bus = sd->bus;
1074                         device->target = sd->target;
1075                         device->lun = device->scsi3addr[4];
1076                         break;
1077                 }
1078         }
1079         if (device->lun == -1) {
1080                 dev_warn(&h->pdev->dev, "physical device with no LUN=0,"
1081                         " suspect firmware bug or unsupported hardware "
1082                         "configuration.\n");
1083                         return -1;
1084         }
1085
1086 lun_assigned:
1087
1088         h->dev[n] = device;
1089         h->ndevices++;
1090         added[*nadded] = device;
1091         (*nadded)++;
1092         hpsa_show_dev_msg(KERN_INFO, h, device,
1093                 device->expose_state & HPSA_SCSI_ADD ? "added" : "masked");
1094         device->offload_to_be_enabled = device->offload_enabled;
1095         device->offload_enabled = 0;
1096         return 0;
1097 }
1098
1099 /* Update an entry in h->dev[] array. */
1100 static void hpsa_scsi_update_entry(struct ctlr_info *h, int hostno,
1101         int entry, struct hpsa_scsi_dev_t *new_entry)
1102 {
1103         int offload_enabled;
1104         /* assumes h->devlock is held */
1105         BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
1106
1107         /* Raid level changed. */
1108         h->dev[entry]->raid_level = new_entry->raid_level;
1109
1110         /* Raid offload parameters changed.  Careful about the ordering. */
1111         if (new_entry->offload_config && new_entry->offload_enabled) {
1112                 /*
1113                  * if drive is newly offload_enabled, we want to copy the
1114                  * raid map data first.  If previously offload_enabled and
1115                  * offload_config were set, raid map data had better be
1116                  * the same as it was before.  if raid map data is changed
1117                  * then it had better be the case that
1118                  * h->dev[entry]->offload_enabled is currently 0.
1119                  */
1120                 h->dev[entry]->raid_map = new_entry->raid_map;
1121                 h->dev[entry]->ioaccel_handle = new_entry->ioaccel_handle;
1122         }
1123         if (new_entry->hba_ioaccel_enabled) {
1124                 h->dev[entry]->ioaccel_handle = new_entry->ioaccel_handle;
1125                 wmb(); /* set ioaccel_handle *before* hba_ioaccel_enabled */
1126         }
1127         h->dev[entry]->hba_ioaccel_enabled = new_entry->hba_ioaccel_enabled;
1128         h->dev[entry]->offload_config = new_entry->offload_config;
1129         h->dev[entry]->offload_to_mirror = new_entry->offload_to_mirror;
1130         h->dev[entry]->queue_depth = new_entry->queue_depth;
1131
1132         /*
1133          * We can turn off ioaccel offload now, but need to delay turning
1134          * it on until we can update h->dev[entry]->phys_disk[], but we
1135          * can't do that until all the devices are updated.
1136          */
1137         h->dev[entry]->offload_to_be_enabled = new_entry->offload_enabled;
1138         if (!new_entry->offload_enabled)
1139                 h->dev[entry]->offload_enabled = 0;
1140
1141         offload_enabled = h->dev[entry]->offload_enabled;
1142         h->dev[entry]->offload_enabled = h->dev[entry]->offload_to_be_enabled;
1143         hpsa_show_dev_msg(KERN_INFO, h, h->dev[entry], "updated");
1144         h->dev[entry]->offload_enabled = offload_enabled;
1145 }
1146
1147 /* Replace an entry from h->dev[] array. */
1148 static void hpsa_scsi_replace_entry(struct ctlr_info *h, int hostno,
1149         int entry, struct hpsa_scsi_dev_t *new_entry,
1150         struct hpsa_scsi_dev_t *added[], int *nadded,
1151         struct hpsa_scsi_dev_t *removed[], int *nremoved)
1152 {
1153         /* assumes h->devlock is held */
1154         BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
1155         removed[*nremoved] = h->dev[entry];
1156         (*nremoved)++;
1157
1158         /*
1159          * New physical devices won't have target/lun assigned yet
1160          * so we need to preserve the values in the slot we are replacing.
1161          */
1162         if (new_entry->target == -1) {
1163                 new_entry->target = h->dev[entry]->target;
1164                 new_entry->lun = h->dev[entry]->lun;
1165         }
1166
1167         h->dev[entry] = new_entry;
1168         added[*nadded] = new_entry;
1169         (*nadded)++;
1170         hpsa_show_dev_msg(KERN_INFO, h, new_entry, "replaced");
1171         new_entry->offload_to_be_enabled = new_entry->offload_enabled;
1172         new_entry->offload_enabled = 0;
1173 }
1174
1175 /* Remove an entry from h->dev[] array. */
1176 static void hpsa_scsi_remove_entry(struct ctlr_info *h, int hostno, int entry,
1177         struct hpsa_scsi_dev_t *removed[], int *nremoved)
1178 {
1179         /* assumes h->devlock is held */
1180         int i;
1181         struct hpsa_scsi_dev_t *sd;
1182
1183         BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
1184
1185         sd = h->dev[entry];
1186         removed[*nremoved] = h->dev[entry];
1187         (*nremoved)++;
1188
1189         for (i = entry; i < h->ndevices-1; i++)
1190                 h->dev[i] = h->dev[i+1];
1191         h->ndevices--;
1192         hpsa_show_dev_msg(KERN_INFO, h, sd, "removed");
1193 }
1194
1195 #define SCSI3ADDR_EQ(a, b) ( \
1196         (a)[7] == (b)[7] && \
1197         (a)[6] == (b)[6] && \
1198         (a)[5] == (b)[5] && \
1199         (a)[4] == (b)[4] && \
1200         (a)[3] == (b)[3] && \
1201         (a)[2] == (b)[2] && \
1202         (a)[1] == (b)[1] && \
1203         (a)[0] == (b)[0])
1204
1205 static void fixup_botched_add(struct ctlr_info *h,
1206         struct hpsa_scsi_dev_t *added)
1207 {
1208         /* called when scsi_add_device fails in order to re-adjust
1209          * h->dev[] to match the mid layer's view.
1210          */
1211         unsigned long flags;
1212         int i, j;
1213
1214         spin_lock_irqsave(&h->lock, flags);
1215         for (i = 0; i < h->ndevices; i++) {
1216                 if (h->dev[i] == added) {
1217                         for (j = i; j < h->ndevices-1; j++)
1218                                 h->dev[j] = h->dev[j+1];
1219                         h->ndevices--;
1220                         break;
1221                 }
1222         }
1223         spin_unlock_irqrestore(&h->lock, flags);
1224         kfree(added);
1225 }
1226
1227 static inline int device_is_the_same(struct hpsa_scsi_dev_t *dev1,
1228         struct hpsa_scsi_dev_t *dev2)
1229 {
1230         /* we compare everything except lun and target as these
1231          * are not yet assigned.  Compare parts likely
1232          * to differ first
1233          */
1234         if (memcmp(dev1->scsi3addr, dev2->scsi3addr,
1235                 sizeof(dev1->scsi3addr)) != 0)
1236                 return 0;
1237         if (memcmp(dev1->device_id, dev2->device_id,
1238                 sizeof(dev1->device_id)) != 0)
1239                 return 0;
1240         if (memcmp(dev1->model, dev2->model, sizeof(dev1->model)) != 0)
1241                 return 0;
1242         if (memcmp(dev1->vendor, dev2->vendor, sizeof(dev1->vendor)) != 0)
1243                 return 0;
1244         if (dev1->devtype != dev2->devtype)
1245                 return 0;
1246         if (dev1->bus != dev2->bus)
1247                 return 0;
1248         return 1;
1249 }
1250
1251 static inline int device_updated(struct hpsa_scsi_dev_t *dev1,
1252         struct hpsa_scsi_dev_t *dev2)
1253 {
1254         /* Device attributes that can change, but don't mean
1255          * that the device is a different device, nor that the OS
1256          * needs to be told anything about the change.
1257          */
1258         if (dev1->raid_level != dev2->raid_level)
1259                 return 1;
1260         if (dev1->offload_config != dev2->offload_config)
1261                 return 1;
1262         if (dev1->offload_enabled != dev2->offload_enabled)
1263                 return 1;
1264         if (dev1->queue_depth != dev2->queue_depth)
1265                 return 1;
1266         return 0;
1267 }
1268
1269 /* Find needle in haystack.  If exact match found, return DEVICE_SAME,
1270  * and return needle location in *index.  If scsi3addr matches, but not
1271  * vendor, model, serial num, etc. return DEVICE_CHANGED, and return needle
1272  * location in *index.
1273  * In the case of a minor device attribute change, such as RAID level, just
1274  * return DEVICE_UPDATED, along with the updated device's location in index.
1275  * If needle not found, return DEVICE_NOT_FOUND.
1276  */
1277 static int hpsa_scsi_find_entry(struct hpsa_scsi_dev_t *needle,
1278         struct hpsa_scsi_dev_t *haystack[], int haystack_size,
1279         int *index)
1280 {
1281         int i;
1282 #define DEVICE_NOT_FOUND 0
1283 #define DEVICE_CHANGED 1
1284 #define DEVICE_SAME 2
1285 #define DEVICE_UPDATED 3
1286         for (i = 0; i < haystack_size; i++) {
1287                 if (haystack[i] == NULL) /* previously removed. */
1288                         continue;
1289                 if (SCSI3ADDR_EQ(needle->scsi3addr, haystack[i]->scsi3addr)) {
1290                         *index = i;
1291                         if (device_is_the_same(needle, haystack[i])) {
1292                                 if (device_updated(needle, haystack[i]))
1293                                         return DEVICE_UPDATED;
1294                                 return DEVICE_SAME;
1295                         } else {
1296                                 /* Keep offline devices offline */
1297                                 if (needle->volume_offline)
1298                                         return DEVICE_NOT_FOUND;
1299                                 return DEVICE_CHANGED;
1300                         }
1301                 }
1302         }
1303         *index = -1;
1304         return DEVICE_NOT_FOUND;
1305 }
1306
1307 static void hpsa_monitor_offline_device(struct ctlr_info *h,
1308                                         unsigned char scsi3addr[])
1309 {
1310         struct offline_device_entry *device;
1311         unsigned long flags;
1312
1313         /* Check to see if device is already on the list */
1314         spin_lock_irqsave(&h->offline_device_lock, flags);
1315         list_for_each_entry(device, &h->offline_device_list, offline_list) {
1316                 if (memcmp(device->scsi3addr, scsi3addr,
1317                         sizeof(device->scsi3addr)) == 0) {
1318                         spin_unlock_irqrestore(&h->offline_device_lock, flags);
1319                         return;
1320                 }
1321         }
1322         spin_unlock_irqrestore(&h->offline_device_lock, flags);
1323
1324         /* Device is not on the list, add it. */
1325         device = kmalloc(sizeof(*device), GFP_KERNEL);
1326         if (!device) {
1327                 dev_warn(&h->pdev->dev, "out of memory in %s\n", __func__);
1328                 return;
1329         }
1330         memcpy(device->scsi3addr, scsi3addr, sizeof(device->scsi3addr));
1331         spin_lock_irqsave(&h->offline_device_lock, flags);
1332         list_add_tail(&device->offline_list, &h->offline_device_list);
1333         spin_unlock_irqrestore(&h->offline_device_lock, flags);
1334 }
1335
1336 /* Print a message explaining various offline volume states */
1337 static void hpsa_show_volume_status(struct ctlr_info *h,
1338         struct hpsa_scsi_dev_t *sd)
1339 {
1340         if (sd->volume_offline == HPSA_VPD_LV_STATUS_UNSUPPORTED)
1341                 dev_info(&h->pdev->dev,
1342                         "C%d:B%d:T%d:L%d Volume status is not available through vital product data pages.\n",
1343                         h->scsi_host->host_no,
1344                         sd->bus, sd->target, sd->lun);
1345         switch (sd->volume_offline) {
1346         case HPSA_LV_OK:
1347                 break;
1348         case HPSA_LV_UNDERGOING_ERASE:
1349                 dev_info(&h->pdev->dev,
1350                         "C%d:B%d:T%d:L%d Volume is undergoing background erase process.\n",
1351                         h->scsi_host->host_no,
1352                         sd->bus, sd->target, sd->lun);
1353                 break;
1354         case HPSA_LV_UNDERGOING_RPI:
1355                 dev_info(&h->pdev->dev,
1356                         "C%d:B%d:T%d:L%d Volume is undergoing rapid parity initialization process.\n",
1357                         h->scsi_host->host_no,
1358                         sd->bus, sd->target, sd->lun);
1359                 break;
1360         case HPSA_LV_PENDING_RPI:
1361                 dev_info(&h->pdev->dev,
1362                                 "C%d:B%d:T%d:L%d Volume is queued for rapid parity initialization process.\n",
1363                                 h->scsi_host->host_no,
1364                                 sd->bus, sd->target, sd->lun);
1365                 break;
1366         case HPSA_LV_ENCRYPTED_NO_KEY:
1367                 dev_info(&h->pdev->dev,
1368                         "C%d:B%d:T%d:L%d Volume is encrypted and cannot be accessed because key is not present.\n",
1369                         h->scsi_host->host_no,
1370                         sd->bus, sd->target, sd->lun);
1371                 break;
1372         case HPSA_LV_PLAINTEXT_IN_ENCRYPT_ONLY_CONTROLLER:
1373                 dev_info(&h->pdev->dev,
1374                         "C%d:B%d:T%d:L%d Volume is not encrypted and cannot be accessed because controller is in encryption-only mode.\n",
1375                         h->scsi_host->host_no,
1376                         sd->bus, sd->target, sd->lun);
1377                 break;
1378         case HPSA_LV_UNDERGOING_ENCRYPTION:
1379                 dev_info(&h->pdev->dev,
1380                         "C%d:B%d:T%d:L%d Volume is undergoing encryption process.\n",
1381                         h->scsi_host->host_no,
1382                         sd->bus, sd->target, sd->lun);
1383                 break;
1384         case HPSA_LV_UNDERGOING_ENCRYPTION_REKEYING:
1385                 dev_info(&h->pdev->dev,
1386                         "C%d:B%d:T%d:L%d Volume is undergoing encryption re-keying process.\n",
1387                         h->scsi_host->host_no,
1388                         sd->bus, sd->target, sd->lun);
1389                 break;
1390         case HPSA_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
1391                 dev_info(&h->pdev->dev,
1392                         "C%d:B%d:T%d:L%d Volume is encrypted and cannot be accessed because controller does not have encryption enabled.\n",
1393                         h->scsi_host->host_no,
1394                         sd->bus, sd->target, sd->lun);
1395                 break;
1396         case HPSA_LV_PENDING_ENCRYPTION:
1397                 dev_info(&h->pdev->dev,
1398                         "C%d:B%d:T%d:L%d Volume is pending migration to encrypted state, but process has not started.\n",
1399                         h->scsi_host->host_no,
1400                         sd->bus, sd->target, sd->lun);
1401                 break;
1402         case HPSA_LV_PENDING_ENCRYPTION_REKEYING:
1403                 dev_info(&h->pdev->dev,
1404                         "C%d:B%d:T%d:L%d Volume is encrypted and is pending encryption rekeying.\n",
1405                         h->scsi_host->host_no,
1406                         sd->bus, sd->target, sd->lun);
1407                 break;
1408         }
1409 }
1410
1411 /*
1412  * Figure the list of physical drive pointers for a logical drive with
1413  * raid offload configured.
1414  */
1415 static void hpsa_figure_phys_disk_ptrs(struct ctlr_info *h,
1416                                 struct hpsa_scsi_dev_t *dev[], int ndevices,
1417                                 struct hpsa_scsi_dev_t *logical_drive)
1418 {
1419         struct raid_map_data *map = &logical_drive->raid_map;
1420         struct raid_map_disk_data *dd = &map->data[0];
1421         int i, j;
1422         int total_disks_per_row = le16_to_cpu(map->data_disks_per_row) +
1423                                 le16_to_cpu(map->metadata_disks_per_row);
1424         int nraid_map_entries = le16_to_cpu(map->row_cnt) *
1425                                 le16_to_cpu(map->layout_map_count) *
1426                                 total_disks_per_row;
1427         int nphys_disk = le16_to_cpu(map->layout_map_count) *
1428                                 total_disks_per_row;
1429         int qdepth;
1430
1431         if (nraid_map_entries > RAID_MAP_MAX_ENTRIES)
1432                 nraid_map_entries = RAID_MAP_MAX_ENTRIES;
1433
1434         qdepth = 0;
1435         for (i = 0; i < nraid_map_entries; i++) {
1436                 logical_drive->phys_disk[i] = NULL;
1437                 if (!logical_drive->offload_config)
1438                         continue;
1439                 for (j = 0; j < ndevices; j++) {
1440                         if (dev[j]->devtype != TYPE_DISK)
1441                                 continue;
1442                         if (is_logical_dev_addr_mode(dev[j]->scsi3addr))
1443                                 continue;
1444                         if (dev[j]->ioaccel_handle != dd[i].ioaccel_handle)
1445                                 continue;
1446
1447                         logical_drive->phys_disk[i] = dev[j];
1448                         if (i < nphys_disk)
1449                                 qdepth = min(h->nr_cmds, qdepth +
1450                                     logical_drive->phys_disk[i]->queue_depth);
1451                         break;
1452                 }
1453
1454                 /*
1455                  * This can happen if a physical drive is removed and
1456                  * the logical drive is degraded.  In that case, the RAID
1457                  * map data will refer to a physical disk which isn't actually
1458                  * present.  And in that case offload_enabled should already
1459                  * be 0, but we'll turn it off here just in case
1460                  */
1461                 if (!logical_drive->phys_disk[i]) {
1462                         logical_drive->offload_enabled = 0;
1463                         logical_drive->offload_to_be_enabled = 0;
1464                         logical_drive->queue_depth = 8;
1465                 }
1466         }
1467         if (nraid_map_entries)
1468                 /*
1469                  * This is correct for reads, too high for full stripe writes,
1470                  * way too high for partial stripe writes
1471                  */
1472                 logical_drive->queue_depth = qdepth;
1473         else
1474                 logical_drive->queue_depth = h->nr_cmds;
1475 }
1476
1477 static void hpsa_update_log_drive_phys_drive_ptrs(struct ctlr_info *h,
1478                                 struct hpsa_scsi_dev_t *dev[], int ndevices)
1479 {
1480         int i;
1481
1482         for (i = 0; i < ndevices; i++) {
1483                 if (dev[i]->devtype != TYPE_DISK)
1484                         continue;
1485                 if (!is_logical_dev_addr_mode(dev[i]->scsi3addr))
1486                         continue;
1487
1488                 /*
1489                  * If offload is currently enabled, the RAID map and
1490                  * phys_disk[] assignment *better* not be changing
1491                  * and since it isn't changing, we do not need to
1492                  * update it.
1493                  */
1494                 if (dev[i]->offload_enabled)
1495                         continue;
1496
1497                 hpsa_figure_phys_disk_ptrs(h, dev, ndevices, dev[i]);
1498         }
1499 }
1500
1501 static void adjust_hpsa_scsi_table(struct ctlr_info *h, int hostno,
1502         struct hpsa_scsi_dev_t *sd[], int nsds)
1503 {
1504         /* sd contains scsi3 addresses and devtypes, and inquiry
1505          * data.  This function takes what's in sd to be the current
1506          * reality and updates h->dev[] to reflect that reality.
1507          */
1508         int i, entry, device_change, changes = 0;
1509         struct hpsa_scsi_dev_t *csd;
1510         unsigned long flags;
1511         struct hpsa_scsi_dev_t **added, **removed;
1512         int nadded, nremoved;
1513         struct Scsi_Host *sh = NULL;
1514
1515         added = kzalloc(sizeof(*added) * HPSA_MAX_DEVICES, GFP_KERNEL);
1516         removed = kzalloc(sizeof(*removed) * HPSA_MAX_DEVICES, GFP_KERNEL);
1517
1518         if (!added || !removed) {
1519                 dev_warn(&h->pdev->dev, "out of memory in "
1520                         "adjust_hpsa_scsi_table\n");
1521                 goto free_and_out;
1522         }
1523
1524         spin_lock_irqsave(&h->devlock, flags);
1525
1526         /* find any devices in h->dev[] that are not in
1527          * sd[] and remove them from h->dev[], and for any
1528          * devices which have changed, remove the old device
1529          * info and add the new device info.
1530          * If minor device attributes change, just update
1531          * the existing device structure.
1532          */
1533         i = 0;
1534         nremoved = 0;
1535         nadded = 0;
1536         while (i < h->ndevices) {
1537                 csd = h->dev[i];
1538                 device_change = hpsa_scsi_find_entry(csd, sd, nsds, &entry);
1539                 if (device_change == DEVICE_NOT_FOUND) {
1540                         changes++;
1541                         hpsa_scsi_remove_entry(h, hostno, i,
1542                                 removed, &nremoved);
1543                         continue; /* remove ^^^, hence i not incremented */
1544                 } else if (device_change == DEVICE_CHANGED) {
1545                         changes++;
1546                         hpsa_scsi_replace_entry(h, hostno, i, sd[entry],
1547                                 added, &nadded, removed, &nremoved);
1548                         /* Set it to NULL to prevent it from being freed
1549                          * at the bottom of hpsa_update_scsi_devices()
1550                          */
1551                         sd[entry] = NULL;
1552                 } else if (device_change == DEVICE_UPDATED) {
1553                         hpsa_scsi_update_entry(h, hostno, i, sd[entry]);
1554                 }
1555                 i++;
1556         }
1557
1558         /* Now, make sure every device listed in sd[] is also
1559          * listed in h->dev[], adding them if they aren't found
1560          */
1561
1562         for (i = 0; i < nsds; i++) {
1563                 if (!sd[i]) /* if already added above. */
1564                         continue;
1565
1566                 /* Don't add devices which are NOT READY, FORMAT IN PROGRESS
1567                  * as the SCSI mid-layer does not handle such devices well.
1568                  * It relentlessly loops sending TUR at 3Hz, then READ(10)
1569                  * at 160Hz, and prevents the system from coming up.
1570                  */
1571                 if (sd[i]->volume_offline) {
1572                         hpsa_show_volume_status(h, sd[i]);
1573                         hpsa_show_dev_msg(KERN_INFO, h, sd[i], "offline");
1574                         continue;
1575                 }
1576
1577                 device_change = hpsa_scsi_find_entry(sd[i], h->dev,
1578                                         h->ndevices, &entry);
1579                 if (device_change == DEVICE_NOT_FOUND) {
1580                         changes++;
1581                         if (hpsa_scsi_add_entry(h, hostno, sd[i],
1582                                 added, &nadded) != 0)
1583                                 break;
1584                         sd[i] = NULL; /* prevent from being freed later. */
1585                 } else if (device_change == DEVICE_CHANGED) {
1586                         /* should never happen... */
1587                         changes++;
1588                         dev_warn(&h->pdev->dev,
1589                                 "device unexpectedly changed.\n");
1590                         /* but if it does happen, we just ignore that device */
1591                 }
1592         }
1593         hpsa_update_log_drive_phys_drive_ptrs(h, h->dev, h->ndevices);
1594
1595         /* Now that h->dev[]->phys_disk[] is coherent, we can enable
1596          * any logical drives that need it enabled.
1597          */
1598         for (i = 0; i < h->ndevices; i++)
1599                 h->dev[i]->offload_enabled = h->dev[i]->offload_to_be_enabled;
1600
1601         spin_unlock_irqrestore(&h->devlock, flags);
1602
1603         /* Monitor devices which are in one of several NOT READY states to be
1604          * brought online later. This must be done without holding h->devlock,
1605          * so don't touch h->dev[]
1606          */
1607         for (i = 0; i < nsds; i++) {
1608                 if (!sd[i]) /* if already added above. */
1609                         continue;
1610                 if (sd[i]->volume_offline)
1611                         hpsa_monitor_offline_device(h, sd[i]->scsi3addr);
1612         }
1613
1614         /* Don't notify scsi mid layer of any changes the first time through
1615          * (or if there are no changes) scsi_scan_host will do it later the
1616          * first time through.
1617          */
1618         if (hostno == -1 || !changes)
1619                 goto free_and_out;
1620
1621         sh = h->scsi_host;
1622         /* Notify scsi mid layer of any removed devices */
1623         for (i = 0; i < nremoved; i++) {
1624                 if (removed[i]->expose_state & HPSA_SCSI_ADD) {
1625                         struct scsi_device *sdev =
1626                                 scsi_device_lookup(sh, removed[i]->bus,
1627                                         removed[i]->target, removed[i]->lun);
1628                         if (sdev != NULL) {
1629                                 scsi_remove_device(sdev);
1630                                 scsi_device_put(sdev);
1631                         } else {
1632                                 /*
1633                                  * We don't expect to get here.
1634                                  * future cmds to this device will get selection
1635                                  * timeout as if the device was gone.
1636                                  */
1637                                 hpsa_show_dev_msg(KERN_WARNING, h, removed[i],
1638                                         "didn't find device for removal.");
1639                         }
1640                 }
1641                 kfree(removed[i]);
1642                 removed[i] = NULL;
1643         }
1644
1645         /* Notify scsi mid layer of any added devices */
1646         for (i = 0; i < nadded; i++) {
1647                 if (!(added[i]->expose_state & HPSA_SCSI_ADD))
1648                         continue;
1649                 if (scsi_add_device(sh, added[i]->bus,
1650                         added[i]->target, added[i]->lun) == 0)
1651                         continue;
1652                 hpsa_show_dev_msg(KERN_WARNING, h, added[i],
1653                                         "addition failed, device not added.");
1654                 /* now we have to remove it from h->dev,
1655                  * since it didn't get added to scsi mid layer
1656                  */
1657                 fixup_botched_add(h, added[i]);
1658                 added[i] = NULL;
1659         }
1660
1661 free_and_out:
1662         kfree(added);
1663         kfree(removed);
1664 }
1665
1666 /*
1667  * Lookup bus/target/lun and return corresponding struct hpsa_scsi_dev_t *
1668  * Assume's h->devlock is held.
1669  */
1670 static struct hpsa_scsi_dev_t *lookup_hpsa_scsi_dev(struct ctlr_info *h,
1671         int bus, int target, int lun)
1672 {
1673         int i;
1674         struct hpsa_scsi_dev_t *sd;
1675
1676         for (i = 0; i < h->ndevices; i++) {
1677                 sd = h->dev[i];
1678                 if (sd->bus == bus && sd->target == target && sd->lun == lun)
1679                         return sd;
1680         }
1681         return NULL;
1682 }
1683
1684 static int hpsa_slave_alloc(struct scsi_device *sdev)
1685 {
1686         struct hpsa_scsi_dev_t *sd;
1687         unsigned long flags;
1688         struct ctlr_info *h;
1689
1690         h = sdev_to_hba(sdev);
1691         spin_lock_irqsave(&h->devlock, flags);
1692         sd = lookup_hpsa_scsi_dev(h, sdev_channel(sdev),
1693                 sdev_id(sdev), sdev->lun);
1694         if (likely(sd)) {
1695                 atomic_set(&sd->ioaccel_cmds_out, 0);
1696                 sdev->hostdata = (sd->expose_state & HPSA_SCSI_ADD) ? sd : NULL;
1697         } else
1698                 sdev->hostdata = NULL;
1699         spin_unlock_irqrestore(&h->devlock, flags);
1700         return 0;
1701 }
1702
1703 /* configure scsi device based on internal per-device structure */
1704 static int hpsa_slave_configure(struct scsi_device *sdev)
1705 {
1706         struct hpsa_scsi_dev_t *sd;
1707         int queue_depth;
1708
1709         sd = sdev->hostdata;
1710         sdev->no_uld_attach = !sd || !(sd->expose_state & HPSA_ULD_ATTACH);
1711
1712         if (sd)
1713                 queue_depth = sd->queue_depth != 0 ?
1714                         sd->queue_depth : sdev->host->can_queue;
1715         else
1716                 queue_depth = sdev->host->can_queue;
1717
1718         scsi_change_queue_depth(sdev, queue_depth);
1719
1720         return 0;
1721 }
1722
1723 static void hpsa_slave_destroy(struct scsi_device *sdev)
1724 {
1725         /* nothing to do. */
1726 }
1727
1728 static void hpsa_free_ioaccel2_sg_chain_blocks(struct ctlr_info *h)
1729 {
1730         int i;
1731
1732         if (!h->ioaccel2_cmd_sg_list)
1733                 return;
1734         for (i = 0; i < h->nr_cmds; i++) {
1735                 kfree(h->ioaccel2_cmd_sg_list[i]);
1736                 h->ioaccel2_cmd_sg_list[i] = NULL;
1737         }
1738         kfree(h->ioaccel2_cmd_sg_list);
1739         h->ioaccel2_cmd_sg_list = NULL;
1740 }
1741
1742 static int hpsa_allocate_ioaccel2_sg_chain_blocks(struct ctlr_info *h)
1743 {
1744         int i;
1745
1746         if (h->chainsize <= 0)
1747                 return 0;
1748
1749         h->ioaccel2_cmd_sg_list =
1750                 kzalloc(sizeof(*h->ioaccel2_cmd_sg_list) * h->nr_cmds,
1751                                         GFP_KERNEL);
1752         if (!h->ioaccel2_cmd_sg_list)
1753                 return -ENOMEM;
1754         for (i = 0; i < h->nr_cmds; i++) {
1755                 h->ioaccel2_cmd_sg_list[i] =
1756                         kmalloc(sizeof(*h->ioaccel2_cmd_sg_list[i]) *
1757                                         h->maxsgentries, GFP_KERNEL);
1758                 if (!h->ioaccel2_cmd_sg_list[i])
1759                         goto clean;
1760         }
1761         return 0;
1762
1763 clean:
1764         hpsa_free_ioaccel2_sg_chain_blocks(h);
1765         return -ENOMEM;
1766 }
1767
1768 static void hpsa_free_sg_chain_blocks(struct ctlr_info *h)
1769 {
1770         int i;
1771
1772         if (!h->cmd_sg_list)
1773                 return;
1774         for (i = 0; i < h->nr_cmds; i++) {
1775                 kfree(h->cmd_sg_list[i]);
1776                 h->cmd_sg_list[i] = NULL;
1777         }
1778         kfree(h->cmd_sg_list);
1779         h->cmd_sg_list = NULL;
1780 }
1781
1782 static int hpsa_alloc_sg_chain_blocks(struct ctlr_info *h)
1783 {
1784         int i;
1785
1786         if (h->chainsize <= 0)
1787                 return 0;
1788
1789         h->cmd_sg_list = kzalloc(sizeof(*h->cmd_sg_list) * h->nr_cmds,
1790                                 GFP_KERNEL);
1791         if (!h->cmd_sg_list) {
1792                 dev_err(&h->pdev->dev, "Failed to allocate SG list\n");
1793                 return -ENOMEM;
1794         }
1795         for (i = 0; i < h->nr_cmds; i++) {
1796                 h->cmd_sg_list[i] = kmalloc(sizeof(*h->cmd_sg_list[i]) *
1797                                                 h->chainsize, GFP_KERNEL);
1798                 if (!h->cmd_sg_list[i]) {
1799                         dev_err(&h->pdev->dev, "Failed to allocate cmd SG\n");
1800                         goto clean;
1801                 }
1802         }
1803         return 0;
1804
1805 clean:
1806         hpsa_free_sg_chain_blocks(h);
1807         return -ENOMEM;
1808 }
1809
1810 static int hpsa_map_ioaccel2_sg_chain_block(struct ctlr_info *h,
1811         struct io_accel2_cmd *cp, struct CommandList *c)
1812 {
1813         struct ioaccel2_sg_element *chain_block;
1814         u64 temp64;
1815         u32 chain_size;
1816
1817         chain_block = h->ioaccel2_cmd_sg_list[c->cmdindex];
1818         chain_size = le32_to_cpu(cp->data_len);
1819         temp64 = pci_map_single(h->pdev, chain_block, chain_size,
1820                                 PCI_DMA_TODEVICE);
1821         if (dma_mapping_error(&h->pdev->dev, temp64)) {
1822                 /* prevent subsequent unmapping */
1823                 cp->sg->address = 0;
1824                 return -1;
1825         }
1826         cp->sg->address = cpu_to_le64(temp64);
1827         return 0;
1828 }
1829
1830 static void hpsa_unmap_ioaccel2_sg_chain_block(struct ctlr_info *h,
1831         struct io_accel2_cmd *cp)
1832 {
1833         struct ioaccel2_sg_element *chain_sg;
1834         u64 temp64;
1835         u32 chain_size;
1836
1837         chain_sg = cp->sg;
1838         temp64 = le64_to_cpu(chain_sg->address);
1839         chain_size = le32_to_cpu(cp->data_len);
1840         pci_unmap_single(h->pdev, temp64, chain_size, PCI_DMA_TODEVICE);
1841 }
1842
1843 static int hpsa_map_sg_chain_block(struct ctlr_info *h,
1844         struct CommandList *c)
1845 {
1846         struct SGDescriptor *chain_sg, *chain_block;
1847         u64 temp64;
1848         u32 chain_len;
1849
1850         chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
1851         chain_block = h->cmd_sg_list[c->cmdindex];
1852         chain_sg->Ext = cpu_to_le32(HPSA_SG_CHAIN);
1853         chain_len = sizeof(*chain_sg) *
1854                 (le16_to_cpu(c->Header.SGTotal) - h->max_cmd_sg_entries);
1855         chain_sg->Len = cpu_to_le32(chain_len);
1856         temp64 = pci_map_single(h->pdev, chain_block, chain_len,
1857                                 PCI_DMA_TODEVICE);
1858         if (dma_mapping_error(&h->pdev->dev, temp64)) {
1859                 /* prevent subsequent unmapping */
1860                 chain_sg->Addr = cpu_to_le64(0);
1861                 return -1;
1862         }
1863         chain_sg->Addr = cpu_to_le64(temp64);
1864         return 0;
1865 }
1866
1867 static void hpsa_unmap_sg_chain_block(struct ctlr_info *h,
1868         struct CommandList *c)
1869 {
1870         struct SGDescriptor *chain_sg;
1871
1872         if (le16_to_cpu(c->Header.SGTotal) <= h->max_cmd_sg_entries)
1873                 return;
1874
1875         chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
1876         pci_unmap_single(h->pdev, le64_to_cpu(chain_sg->Addr),
1877                         le32_to_cpu(chain_sg->Len), PCI_DMA_TODEVICE);
1878 }
1879
1880
1881 /* Decode the various types of errors on ioaccel2 path.
1882  * Return 1 for any error that should generate a RAID path retry.
1883  * Return 0 for errors that don't require a RAID path retry.
1884  */
1885 static int handle_ioaccel_mode2_error(struct ctlr_info *h,
1886                                         struct CommandList *c,
1887                                         struct scsi_cmnd *cmd,
1888                                         struct io_accel2_cmd *c2)
1889 {
1890         int data_len;
1891         int retry = 0;
1892         u32 ioaccel2_resid = 0;
1893
1894         switch (c2->error_data.serv_response) {
1895         case IOACCEL2_SERV_RESPONSE_COMPLETE:
1896                 switch (c2->error_data.status) {
1897                 case IOACCEL2_STATUS_SR_TASK_COMP_GOOD:
1898                         break;
1899                 case IOACCEL2_STATUS_SR_TASK_COMP_CHK_COND:
1900                         cmd->result |= SAM_STAT_CHECK_CONDITION;
1901                         if (c2->error_data.data_present !=
1902                                         IOACCEL2_SENSE_DATA_PRESENT) {
1903                                 memset(cmd->sense_buffer, 0,
1904                                         SCSI_SENSE_BUFFERSIZE);
1905                                 break;
1906                         }
1907                         /* copy the sense data */
1908                         data_len = c2->error_data.sense_data_len;
1909                         if (data_len > SCSI_SENSE_BUFFERSIZE)
1910                                 data_len = SCSI_SENSE_BUFFERSIZE;
1911                         if (data_len > sizeof(c2->error_data.sense_data_buff))
1912                                 data_len =
1913                                         sizeof(c2->error_data.sense_data_buff);
1914                         memcpy(cmd->sense_buffer,
1915                                 c2->error_data.sense_data_buff, data_len);
1916                         retry = 1;
1917                         break;
1918                 case IOACCEL2_STATUS_SR_TASK_COMP_BUSY:
1919                         retry = 1;
1920                         break;
1921                 case IOACCEL2_STATUS_SR_TASK_COMP_RES_CON:
1922                         retry = 1;
1923                         break;
1924                 case IOACCEL2_STATUS_SR_TASK_COMP_SET_FULL:
1925                         retry = 1;
1926                         break;
1927                 case IOACCEL2_STATUS_SR_TASK_COMP_ABORTED:
1928                         retry = 1;
1929                         break;
1930                 default:
1931                         retry = 1;
1932                         break;
1933                 }
1934                 break;
1935         case IOACCEL2_SERV_RESPONSE_FAILURE:
1936                 switch (c2->error_data.status) {
1937                 case IOACCEL2_STATUS_SR_IO_ERROR:
1938                 case IOACCEL2_STATUS_SR_IO_ABORTED:
1939                 case IOACCEL2_STATUS_SR_OVERRUN:
1940                         retry = 1;
1941                         break;
1942                 case IOACCEL2_STATUS_SR_UNDERRUN:
1943                         cmd->result = (DID_OK << 16);           /* host byte */
1944                         cmd->result |= (COMMAND_COMPLETE << 8); /* msg byte */
1945                         ioaccel2_resid = get_unaligned_le32(
1946                                                 &c2->error_data.resid_cnt[0]);
1947                         scsi_set_resid(cmd, ioaccel2_resid);
1948                         break;
1949                 case IOACCEL2_STATUS_SR_NO_PATH_TO_DEVICE:
1950                 case IOACCEL2_STATUS_SR_INVALID_DEVICE:
1951                 case IOACCEL2_STATUS_SR_IOACCEL_DISABLED:
1952                         /* We will get an event from ctlr to trigger rescan */
1953                         retry = 1;
1954                         break;
1955                 default:
1956                         retry = 1;
1957                 }
1958                 break;
1959         case IOACCEL2_SERV_RESPONSE_TMF_COMPLETE:
1960                 break;
1961         case IOACCEL2_SERV_RESPONSE_TMF_SUCCESS:
1962                 break;
1963         case IOACCEL2_SERV_RESPONSE_TMF_REJECTED:
1964                 retry = 1;
1965                 break;
1966         case IOACCEL2_SERV_RESPONSE_TMF_WRONG_LUN:
1967                 break;
1968         default:
1969                 retry = 1;
1970                 break;
1971         }
1972
1973         return retry;   /* retry on raid path? */
1974 }
1975
1976 static void hpsa_cmd_free_and_done(struct ctlr_info *h,
1977                 struct CommandList *c, struct scsi_cmnd *cmd)
1978 {
1979         cmd_free(h, c);
1980         cmd->scsi_done(cmd);
1981 }
1982
1983 static void hpsa_retry_cmd(struct ctlr_info *h, struct CommandList *c)
1984 {
1985         INIT_WORK(&c->work, hpsa_command_resubmit_worker);
1986         queue_work_on(raw_smp_processor_id(), h->resubmit_wq, &c->work);
1987 }
1988
1989 static void process_ioaccel2_completion(struct ctlr_info *h,
1990                 struct CommandList *c, struct scsi_cmnd *cmd,
1991                 struct hpsa_scsi_dev_t *dev)
1992 {
1993         struct io_accel2_cmd *c2 = &h->ioaccel2_cmd_pool[c->cmdindex];
1994
1995         /* check for good status */
1996         if (likely(c2->error_data.serv_response == 0 &&
1997                         c2->error_data.status == 0))
1998                 return hpsa_cmd_free_and_done(h, c, cmd);
1999
2000         /*
2001          * Any RAID offload error results in retry which will use
2002          * the normal I/O path so the controller can handle whatever's
2003          * wrong.
2004          */
2005         if (is_logical_dev_addr_mode(dev->scsi3addr) &&
2006                 c2->error_data.serv_response ==
2007                         IOACCEL2_SERV_RESPONSE_FAILURE) {
2008                 if (c2->error_data.status ==
2009                         IOACCEL2_STATUS_SR_IOACCEL_DISABLED)
2010                         dev->offload_enabled = 0;
2011
2012                 return hpsa_retry_cmd(h, c);
2013         }
2014
2015         if (handle_ioaccel_mode2_error(h, c, cmd, c2))
2016                 return hpsa_retry_cmd(h, c);
2017
2018         return hpsa_cmd_free_and_done(h, c, cmd);
2019 }
2020
2021 /* Returns 0 on success, < 0 otherwise. */
2022 static int hpsa_evaluate_tmf_status(struct ctlr_info *h,
2023                                         struct CommandList *cp)
2024 {
2025         u8 tmf_status = cp->err_info->ScsiStatus;
2026
2027         switch (tmf_status) {
2028         case CISS_TMF_COMPLETE:
2029                 /*
2030                  * CISS_TMF_COMPLETE never happens, instead,
2031                  * ei->CommandStatus == 0 for this case.
2032                  */
2033         case CISS_TMF_SUCCESS:
2034                 return 0;
2035         case CISS_TMF_INVALID_FRAME:
2036         case CISS_TMF_NOT_SUPPORTED:
2037         case CISS_TMF_FAILED:
2038         case CISS_TMF_WRONG_LUN:
2039         case CISS_TMF_OVERLAPPED_TAG:
2040                 break;
2041         default:
2042                 dev_warn(&h->pdev->dev, "Unknown TMF status: 0x%02x\n",
2043                                 tmf_status);
2044                 break;
2045         }
2046         return -tmf_status;
2047 }
2048
2049 static void complete_scsi_command(struct CommandList *cp)
2050 {
2051         struct scsi_cmnd *cmd;
2052         struct ctlr_info *h;
2053         struct ErrorInfo *ei;
2054         struct hpsa_scsi_dev_t *dev;
2055         struct io_accel2_cmd *c2;
2056
2057         u8 sense_key;
2058         u8 asc;      /* additional sense code */
2059         u8 ascq;     /* additional sense code qualifier */
2060         unsigned long sense_data_size;
2061
2062         ei = cp->err_info;
2063         cmd = cp->scsi_cmd;
2064         h = cp->h;
2065         dev = cmd->device->hostdata;
2066         c2 = &h->ioaccel2_cmd_pool[cp->cmdindex];
2067
2068         scsi_dma_unmap(cmd); /* undo the DMA mappings */
2069         if ((cp->cmd_type == CMD_SCSI) &&
2070                 (le16_to_cpu(cp->Header.SGTotal) > h->max_cmd_sg_entries))
2071                 hpsa_unmap_sg_chain_block(h, cp);
2072
2073         if ((cp->cmd_type == CMD_IOACCEL2) &&
2074                 (c2->sg[0].chain_indicator == IOACCEL2_CHAIN))
2075                 hpsa_unmap_ioaccel2_sg_chain_block(h, c2);
2076
2077         cmd->result = (DID_OK << 16);           /* host byte */
2078         cmd->result |= (COMMAND_COMPLETE << 8); /* msg byte */
2079
2080         if (cp->cmd_type == CMD_IOACCEL2 || cp->cmd_type == CMD_IOACCEL1)
2081                 atomic_dec(&cp->phys_disk->ioaccel_cmds_out);
2082
2083         /*
2084          * We check for lockup status here as it may be set for
2085          * CMD_SCSI, CMD_IOACCEL1 and CMD_IOACCEL2 commands by
2086          * fail_all_oustanding_cmds()
2087          */
2088         if (unlikely(ei->CommandStatus == CMD_CTLR_LOCKUP)) {
2089                 /* DID_NO_CONNECT will prevent a retry */
2090                 cmd->result = DID_NO_CONNECT << 16;
2091                 return hpsa_cmd_free_and_done(h, cp, cmd);
2092         }
2093
2094         if (cp->cmd_type == CMD_IOACCEL2)
2095                 return process_ioaccel2_completion(h, cp, cmd, dev);
2096
2097         scsi_set_resid(cmd, ei->ResidualCnt);
2098         if (ei->CommandStatus == 0)
2099                 return hpsa_cmd_free_and_done(h, cp, cmd);
2100
2101         /* For I/O accelerator commands, copy over some fields to the normal
2102          * CISS header used below for error handling.
2103          */
2104         if (cp->cmd_type == CMD_IOACCEL1) {
2105                 struct io_accel1_cmd *c = &h->ioaccel_cmd_pool[cp->cmdindex];
2106                 cp->Header.SGList = scsi_sg_count(cmd);
2107                 cp->Header.SGTotal = cpu_to_le16(cp->Header.SGList);
2108                 cp->Request.CDBLen = le16_to_cpu(c->io_flags) &
2109                         IOACCEL1_IOFLAGS_CDBLEN_MASK;
2110                 cp->Header.tag = c->tag;
2111                 memcpy(cp->Header.LUN.LunAddrBytes, c->CISS_LUN, 8);
2112                 memcpy(cp->Request.CDB, c->CDB, cp->Request.CDBLen);
2113
2114                 /* Any RAID offload error results in retry which will use
2115                  * the normal I/O path so the controller can handle whatever's
2116                  * wrong.
2117                  */
2118                 if (is_logical_dev_addr_mode(dev->scsi3addr)) {
2119                         if (ei->CommandStatus == CMD_IOACCEL_DISABLED)
2120                                 dev->offload_enabled = 0;
2121                         return hpsa_retry_cmd(h, cp);
2122                 }
2123         }
2124
2125         /* an error has occurred */
2126         switch (ei->CommandStatus) {
2127
2128         case CMD_TARGET_STATUS:
2129                 cmd->result |= ei->ScsiStatus;
2130                 /* copy the sense data */
2131                 if (SCSI_SENSE_BUFFERSIZE < sizeof(ei->SenseInfo))
2132                         sense_data_size = SCSI_SENSE_BUFFERSIZE;
2133                 else
2134                         sense_data_size = sizeof(ei->SenseInfo);
2135                 if (ei->SenseLen < sense_data_size)
2136                         sense_data_size = ei->SenseLen;
2137                 memcpy(cmd->sense_buffer, ei->SenseInfo, sense_data_size);
2138                 if (ei->ScsiStatus)
2139                         decode_sense_data(ei->SenseInfo, sense_data_size,
2140                                 &sense_key, &asc, &ascq);
2141                 if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION) {
2142                         if (sense_key == ABORTED_COMMAND) {
2143                                 cmd->result |= DID_SOFT_ERROR << 16;
2144                                 break;
2145                         }
2146                         break;
2147                 }
2148                 /* Problem was not a check condition
2149                  * Pass it up to the upper layers...
2150                  */
2151                 if (ei->ScsiStatus) {
2152                         dev_warn(&h->pdev->dev, "cp %p has status 0x%x "
2153                                 "Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
2154                                 "Returning result: 0x%x\n",
2155                                 cp, ei->ScsiStatus,
2156                                 sense_key, asc, ascq,
2157                                 cmd->result);
2158                 } else {  /* scsi status is zero??? How??? */
2159                         dev_warn(&h->pdev->dev, "cp %p SCSI status was 0. "
2160                                 "Returning no connection.\n", cp),
2161
2162                         /* Ordinarily, this case should never happen,
2163                          * but there is a bug in some released firmware
2164                          * revisions that allows it to happen if, for
2165                          * example, a 4100 backplane loses power and
2166                          * the tape drive is in it.  We assume that
2167                          * it's a fatal error of some kind because we
2168                          * can't show that it wasn't. We will make it
2169                          * look like selection timeout since that is
2170                          * the most common reason for this to occur,
2171                          * and it's severe enough.
2172                          */
2173
2174                         cmd->result = DID_NO_CONNECT << 16;
2175                 }
2176                 break;
2177
2178         case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
2179                 break;
2180         case CMD_DATA_OVERRUN:
2181                 dev_warn(&h->pdev->dev,
2182                         "CDB %16phN data overrun\n", cp->Request.CDB);
2183                 break;
2184         case CMD_INVALID: {
2185                 /* print_bytes(cp, sizeof(*cp), 1, 0);
2186                 print_cmd(cp); */
2187                 /* We get CMD_INVALID if you address a non-existent device
2188                  * instead of a selection timeout (no response).  You will
2189                  * see this if you yank out a drive, then try to access it.
2190                  * This is kind of a shame because it means that any other
2191                  * CMD_INVALID (e.g. driver bug) will get interpreted as a
2192                  * missing target. */
2193                 cmd->result = DID_NO_CONNECT << 16;
2194         }
2195                 break;
2196         case CMD_PROTOCOL_ERR:
2197                 cmd->result = DID_ERROR << 16;
2198                 dev_warn(&h->pdev->dev, "CDB %16phN : protocol error\n",
2199                                 cp->Request.CDB);
2200                 break;
2201         case CMD_HARDWARE_ERR:
2202                 cmd->result = DID_ERROR << 16;
2203                 dev_warn(&h->pdev->dev, "CDB %16phN : hardware error\n",
2204                         cp->Request.CDB);
2205                 break;
2206         case CMD_CONNECTION_LOST:
2207                 cmd->result = DID_ERROR << 16;
2208                 dev_warn(&h->pdev->dev, "CDB %16phN : connection lost\n",
2209                         cp->Request.CDB);
2210                 break;
2211         case CMD_ABORTED:
2212                 cmd->result = DID_ABORT << 16;
2213                 dev_warn(&h->pdev->dev, "CDB %16phN was aborted with status 0x%x\n",
2214                                 cp->Request.CDB, ei->ScsiStatus);
2215                 break;
2216         case CMD_ABORT_FAILED:
2217                 cmd->result = DID_ERROR << 16;
2218                 dev_warn(&h->pdev->dev, "CDB %16phN : abort failed\n",
2219                         cp->Request.CDB);
2220                 break;
2221         case CMD_UNSOLICITED_ABORT:
2222                 cmd->result = DID_SOFT_ERROR << 16; /* retry the command */
2223                 dev_warn(&h->pdev->dev, "CDB %16phN : unsolicited abort\n",
2224                         cp->Request.CDB);
2225                 break;
2226         case CMD_TIMEOUT:
2227                 cmd->result = DID_TIME_OUT << 16;
2228                 dev_warn(&h->pdev->dev, "CDB %16phN timed out\n",
2229                         cp->Request.CDB);
2230                 break;
2231         case CMD_UNABORTABLE:
2232                 cmd->result = DID_ERROR << 16;
2233                 dev_warn(&h->pdev->dev, "Command unabortable\n");
2234                 break;
2235         case CMD_TMF_STATUS:
2236                 if (hpsa_evaluate_tmf_status(h, cp)) /* TMF failed? */
2237                         cmd->result = DID_ERROR << 16;
2238                 break;
2239         case CMD_IOACCEL_DISABLED:
2240                 /* This only handles the direct pass-through case since RAID
2241                  * offload is handled above.  Just attempt a retry.
2242                  */
2243                 cmd->result = DID_SOFT_ERROR << 16;
2244                 dev_warn(&h->pdev->dev,
2245                                 "cp %p had HP SSD Smart Path error\n", cp);
2246                 break;
2247         default:
2248                 cmd->result = DID_ERROR << 16;
2249                 dev_warn(&h->pdev->dev, "cp %p returned unknown status %x\n",
2250                                 cp, ei->CommandStatus);
2251         }
2252
2253         return hpsa_cmd_free_and_done(h, cp, cmd);
2254 }
2255
2256 static void hpsa_pci_unmap(struct pci_dev *pdev,
2257         struct CommandList *c, int sg_used, int data_direction)
2258 {
2259         int i;
2260
2261         for (i = 0; i < sg_used; i++)
2262                 pci_unmap_single(pdev, (dma_addr_t) le64_to_cpu(c->SG[i].Addr),
2263                                 le32_to_cpu(c->SG[i].Len),
2264                                 data_direction);
2265 }
2266
2267 static int hpsa_map_one(struct pci_dev *pdev,
2268                 struct CommandList *cp,
2269                 unsigned char *buf,
2270                 size_t buflen,
2271                 int data_direction)
2272 {
2273         u64 addr64;
2274
2275         if (buflen == 0 || data_direction == PCI_DMA_NONE) {
2276                 cp->Header.SGList = 0;
2277                 cp->Header.SGTotal = cpu_to_le16(0);
2278                 return 0;
2279         }
2280
2281         addr64 = pci_map_single(pdev, buf, buflen, data_direction);
2282         if (dma_mapping_error(&pdev->dev, addr64)) {
2283                 /* Prevent subsequent unmap of something never mapped */
2284                 cp->Header.SGList = 0;
2285                 cp->Header.SGTotal = cpu_to_le16(0);
2286                 return -1;
2287         }
2288         cp->SG[0].Addr = cpu_to_le64(addr64);
2289         cp->SG[0].Len = cpu_to_le32(buflen);
2290         cp->SG[0].Ext = cpu_to_le32(HPSA_SG_LAST); /* we are not chaining */
2291         cp->Header.SGList = 1;   /* no. SGs contig in this cmd */
2292         cp->Header.SGTotal = cpu_to_le16(1); /* total sgs in cmd list */
2293         return 0;
2294 }
2295
2296 #define NO_TIMEOUT ((unsigned long) -1)
2297 #define DEFAULT_TIMEOUT 30000 /* milliseconds */
2298 static int hpsa_scsi_do_simple_cmd_core(struct ctlr_info *h,
2299         struct CommandList *c, int reply_queue, unsigned long timeout_msecs)
2300 {
2301         DECLARE_COMPLETION_ONSTACK(wait);
2302
2303         c->waiting = &wait;
2304         __enqueue_cmd_and_start_io(h, c, reply_queue);
2305         if (timeout_msecs == NO_TIMEOUT) {
2306                 /* TODO: get rid of this no-timeout thing */
2307                 wait_for_completion_io(&wait);
2308                 return IO_OK;
2309         }
2310         if (!wait_for_completion_io_timeout(&wait,
2311                                         msecs_to_jiffies(timeout_msecs))) {
2312                 dev_warn(&h->pdev->dev, "Command timed out.\n");
2313                 return -ETIMEDOUT;
2314         }
2315         return IO_OK;
2316 }
2317
2318 static int hpsa_scsi_do_simple_cmd(struct ctlr_info *h, struct CommandList *c,
2319                                    int reply_queue, unsigned long timeout_msecs)
2320 {
2321         if (unlikely(lockup_detected(h))) {
2322                 c->err_info->CommandStatus = CMD_CTLR_LOCKUP;
2323                 return IO_OK;
2324         }
2325         return hpsa_scsi_do_simple_cmd_core(h, c, reply_queue, timeout_msecs);
2326 }
2327
2328 static u32 lockup_detected(struct ctlr_info *h)
2329 {
2330         int cpu;
2331         u32 rc, *lockup_detected;
2332
2333         cpu = get_cpu();
2334         lockup_detected = per_cpu_ptr(h->lockup_detected, cpu);
2335         rc = *lockup_detected;
2336         put_cpu();
2337         return rc;
2338 }
2339
2340 #define MAX_DRIVER_CMD_RETRIES 25
2341 static int hpsa_scsi_do_simple_cmd_with_retry(struct ctlr_info *h,
2342         struct CommandList *c, int data_direction, unsigned long timeout_msecs)
2343 {
2344         int backoff_time = 10, retry_count = 0;
2345         int rc;
2346
2347         do {
2348                 memset(c->err_info, 0, sizeof(*c->err_info));
2349                 rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE,
2350                                                   timeout_msecs);
2351                 if (rc)
2352                         break;
2353                 retry_count++;
2354                 if (retry_count > 3) {
2355                         msleep(backoff_time);
2356                         if (backoff_time < 1000)
2357                                 backoff_time *= 2;
2358                 }
2359         } while ((check_for_unit_attention(h, c) ||
2360                         check_for_busy(h, c)) &&
2361                         retry_count <= MAX_DRIVER_CMD_RETRIES);
2362         hpsa_pci_unmap(h->pdev, c, 1, data_direction);
2363         if (retry_count > MAX_DRIVER_CMD_RETRIES)
2364                 rc = -EIO;
2365         return rc;
2366 }
2367
2368 static void hpsa_print_cmd(struct ctlr_info *h, char *txt,
2369                                 struct CommandList *c)
2370 {
2371         const u8 *cdb = c->Request.CDB;
2372         const u8 *lun = c->Header.LUN.LunAddrBytes;
2373
2374         dev_warn(&h->pdev->dev, "%s: LUN:%02x%02x%02x%02x%02x%02x%02x%02x"
2375         " CDB:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
2376                 txt, lun[0], lun[1], lun[2], lun[3],
2377                 lun[4], lun[5], lun[6], lun[7],
2378                 cdb[0], cdb[1], cdb[2], cdb[3],
2379                 cdb[4], cdb[5], cdb[6], cdb[7],
2380                 cdb[8], cdb[9], cdb[10], cdb[11],
2381                 cdb[12], cdb[13], cdb[14], cdb[15]);
2382 }
2383
2384 static void hpsa_scsi_interpret_error(struct ctlr_info *h,
2385                         struct CommandList *cp)
2386 {
2387         const struct ErrorInfo *ei = cp->err_info;
2388         struct device *d = &cp->h->pdev->dev;
2389         u8 sense_key, asc, ascq;
2390         int sense_len;
2391
2392         switch (ei->CommandStatus) {
2393         case CMD_TARGET_STATUS:
2394                 if (ei->SenseLen > sizeof(ei->SenseInfo))
2395                         sense_len = sizeof(ei->SenseInfo);
2396                 else
2397                         sense_len = ei->SenseLen;
2398                 decode_sense_data(ei->SenseInfo, sense_len,
2399                                         &sense_key, &asc, &ascq);
2400                 hpsa_print_cmd(h, "SCSI status", cp);
2401                 if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION)
2402                         dev_warn(d, "SCSI Status = 02, Sense key = 0x%02x, ASC = 0x%02x, ASCQ = 0x%02x\n",
2403                                 sense_key, asc, ascq);
2404                 else
2405                         dev_warn(d, "SCSI Status = 0x%02x\n", ei->ScsiStatus);
2406                 if (ei->ScsiStatus == 0)
2407                         dev_warn(d, "SCSI status is abnormally zero.  "
2408                         "(probably indicates selection timeout "
2409                         "reported incorrectly due to a known "
2410                         "firmware bug, circa July, 2001.)\n");
2411                 break;
2412         case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
2413                 break;
2414         case CMD_DATA_OVERRUN:
2415                 hpsa_print_cmd(h, "overrun condition", cp);
2416                 break;
2417         case CMD_INVALID: {
2418                 /* controller unfortunately reports SCSI passthru's
2419                  * to non-existent targets as invalid commands.
2420                  */
2421                 hpsa_print_cmd(h, "invalid command", cp);
2422                 dev_warn(d, "probably means device no longer present\n");
2423                 }
2424                 break;
2425         case CMD_PROTOCOL_ERR:
2426                 hpsa_print_cmd(h, "protocol error", cp);
2427                 break;
2428         case CMD_HARDWARE_ERR:
2429                 hpsa_print_cmd(h, "hardware error", cp);
2430                 break;
2431         case CMD_CONNECTION_LOST:
2432                 hpsa_print_cmd(h, "connection lost", cp);
2433                 break;
2434         case CMD_ABORTED:
2435                 hpsa_print_cmd(h, "aborted", cp);
2436                 break;
2437         case CMD_ABORT_FAILED:
2438                 hpsa_print_cmd(h, "abort failed", cp);
2439                 break;
2440         case CMD_UNSOLICITED_ABORT:
2441                 hpsa_print_cmd(h, "unsolicited abort", cp);
2442                 break;
2443         case CMD_TIMEOUT:
2444                 hpsa_print_cmd(h, "timed out", cp);
2445                 break;
2446         case CMD_UNABORTABLE:
2447                 hpsa_print_cmd(h, "unabortable", cp);
2448                 break;
2449         case CMD_CTLR_LOCKUP:
2450                 hpsa_print_cmd(h, "controller lockup detected", cp);
2451                 break;
2452         default:
2453                 hpsa_print_cmd(h, "unknown status", cp);
2454                 dev_warn(d, "Unknown command status %x\n",
2455                                 ei->CommandStatus);
2456         }
2457 }
2458
2459 static int hpsa_scsi_do_inquiry(struct ctlr_info *h, unsigned char *scsi3addr,
2460                         u16 page, unsigned char *buf,
2461                         unsigned char bufsize)
2462 {
2463         int rc = IO_OK;
2464         struct CommandList *c;
2465         struct ErrorInfo *ei;
2466
2467         c = cmd_alloc(h);
2468
2469         if (fill_cmd(c, HPSA_INQUIRY, h, buf, bufsize,
2470                         page, scsi3addr, TYPE_CMD)) {
2471                 rc = -1;
2472                 goto out;
2473         }
2474         rc = hpsa_scsi_do_simple_cmd_with_retry(h, c,
2475                                         PCI_DMA_FROMDEVICE, NO_TIMEOUT);
2476         if (rc)
2477                 goto out;
2478         ei = c->err_info;
2479         if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
2480                 hpsa_scsi_interpret_error(h, c);
2481                 rc = -1;
2482         }
2483 out:
2484         cmd_free(h, c);
2485         return rc;
2486 }
2487
2488 static int hpsa_bmic_ctrl_mode_sense(struct ctlr_info *h,
2489                 unsigned char *scsi3addr, unsigned char page,
2490                 struct bmic_controller_parameters *buf, size_t bufsize)
2491 {
2492         int rc = IO_OK;
2493         struct CommandList *c;
2494         struct ErrorInfo *ei;
2495
2496         c = cmd_alloc(h);
2497         if (fill_cmd(c, BMIC_SENSE_CONTROLLER_PARAMETERS, h, buf, bufsize,
2498                         page, scsi3addr, TYPE_CMD)) {
2499                 rc = -1;
2500                 goto out;
2501         }
2502         rc = hpsa_scsi_do_simple_cmd_with_retry(h, c,
2503                         PCI_DMA_FROMDEVICE, NO_TIMEOUT);
2504         if (rc)
2505                 goto out;
2506         ei = c->err_info;
2507         if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
2508                 hpsa_scsi_interpret_error(h, c);
2509                 rc = -1;
2510         }
2511 out:
2512         cmd_free(h, c);
2513         return rc;
2514 }
2515
2516 static int hpsa_send_reset(struct ctlr_info *h, unsigned char *scsi3addr,
2517         u8 reset_type, int reply_queue)
2518 {
2519         int rc = IO_OK;
2520         struct CommandList *c;
2521         struct ErrorInfo *ei;
2522
2523         c = cmd_alloc(h);
2524
2525
2526         /* fill_cmd can't fail here, no data buffer to map. */
2527         (void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0,
2528                         scsi3addr, TYPE_MSG);
2529         c->Request.CDB[1] = reset_type; /* fill_cmd defaults to LUN reset */
2530         rc = hpsa_scsi_do_simple_cmd(h, c, reply_queue, NO_TIMEOUT);
2531         if (rc) {
2532                 dev_warn(&h->pdev->dev, "Failed to send reset command\n");
2533                 goto out;
2534         }
2535         /* no unmap needed here because no data xfer. */
2536
2537         ei = c->err_info;
2538         if (ei->CommandStatus != 0) {
2539                 hpsa_scsi_interpret_error(h, c);
2540                 rc = -1;
2541         }
2542 out:
2543         cmd_free(h, c);
2544         return rc;
2545 }
2546
2547 static void hpsa_get_raid_level(struct ctlr_info *h,
2548         unsigned char *scsi3addr, unsigned char *raid_level)
2549 {
2550         int rc;
2551         unsigned char *buf;
2552
2553         *raid_level = RAID_UNKNOWN;
2554         buf = kzalloc(64, GFP_KERNEL);
2555         if (!buf)
2556                 return;
2557         rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE | 0xC1, buf, 64);
2558         if (rc == 0)
2559                 *raid_level = buf[8];
2560         if (*raid_level > RAID_UNKNOWN)
2561                 *raid_level = RAID_UNKNOWN;
2562         kfree(buf);
2563         return;
2564 }
2565
2566 #define HPSA_MAP_DEBUG
2567 #ifdef HPSA_MAP_DEBUG
2568 static void hpsa_debug_map_buff(struct ctlr_info *h, int rc,
2569                                 struct raid_map_data *map_buff)
2570 {
2571         struct raid_map_disk_data *dd = &map_buff->data[0];
2572         int map, row, col;
2573         u16 map_cnt, row_cnt, disks_per_row;
2574
2575         if (rc != 0)
2576                 return;
2577
2578         /* Show details only if debugging has been activated. */
2579         if (h->raid_offload_debug < 2)
2580                 return;
2581
2582         dev_info(&h->pdev->dev, "structure_size = %u\n",
2583                                 le32_to_cpu(map_buff->structure_size));
2584         dev_info(&h->pdev->dev, "volume_blk_size = %u\n",
2585                         le32_to_cpu(map_buff->volume_blk_size));
2586         dev_info(&h->pdev->dev, "volume_blk_cnt = 0x%llx\n",
2587                         le64_to_cpu(map_buff->volume_blk_cnt));
2588         dev_info(&h->pdev->dev, "physicalBlockShift = %u\n",
2589                         map_buff->phys_blk_shift);
2590         dev_info(&h->pdev->dev, "parity_rotation_shift = %u\n",
2591                         map_buff->parity_rotation_shift);
2592         dev_info(&h->pdev->dev, "strip_size = %u\n",
2593                         le16_to_cpu(map_buff->strip_size));
2594         dev_info(&h->pdev->dev, "disk_starting_blk = 0x%llx\n",
2595                         le64_to_cpu(map_buff->disk_starting_blk));
2596         dev_info(&h->pdev->dev, "disk_blk_cnt = 0x%llx\n",
2597                         le64_to_cpu(map_buff->disk_blk_cnt));
2598         dev_info(&h->pdev->dev, "data_disks_per_row = %u\n",
2599                         le16_to_cpu(map_buff->data_disks_per_row));
2600         dev_info(&h->pdev->dev, "metadata_disks_per_row = %u\n",
2601                         le16_to_cpu(map_buff->metadata_disks_per_row));
2602         dev_info(&h->pdev->dev, "row_cnt = %u\n",
2603                         le16_to_cpu(map_buff->row_cnt));
2604         dev_info(&h->pdev->dev, "layout_map_count = %u\n",
2605                         le16_to_cpu(map_buff->layout_map_count));
2606         dev_info(&h->pdev->dev, "flags = 0x%x\n",
2607                         le16_to_cpu(map_buff->flags));
2608         dev_info(&h->pdev->dev, "encrypytion = %s\n",
2609                         le16_to_cpu(map_buff->flags) &
2610                         RAID_MAP_FLAG_ENCRYPT_ON ?  "ON" : "OFF");
2611         dev_info(&h->pdev->dev, "dekindex = %u\n",
2612                         le16_to_cpu(map_buff->dekindex));
2613         map_cnt = le16_to_cpu(map_buff->layout_map_count);
2614         for (map = 0; map < map_cnt; map++) {
2615                 dev_info(&h->pdev->dev, "Map%u:\n", map);
2616                 row_cnt = le16_to_cpu(map_buff->row_cnt);
2617                 for (row = 0; row < row_cnt; row++) {
2618                         dev_info(&h->pdev->dev, "  Row%u:\n", row);
2619                         disks_per_row =
2620                                 le16_to_cpu(map_buff->data_disks_per_row);
2621                         for (col = 0; col < disks_per_row; col++, dd++)
2622                                 dev_info(&h->pdev->dev,
2623                                         "    D%02u: h=0x%04x xor=%u,%u\n",
2624                                         col, dd->ioaccel_handle,
2625                                         dd->xor_mult[0], dd->xor_mult[1]);
2626                         disks_per_row =
2627                                 le16_to_cpu(map_buff->metadata_disks_per_row);
2628                         for (col = 0; col < disks_per_row; col++, dd++)
2629                                 dev_info(&h->pdev->dev,
2630                                         "    M%02u: h=0x%04x xor=%u,%u\n",
2631                                         col, dd->ioaccel_handle,
2632                                         dd->xor_mult[0], dd->xor_mult[1]);
2633                 }
2634         }
2635 }
2636 #else
2637 static void hpsa_debug_map_buff(__attribute__((unused)) struct ctlr_info *h,
2638                         __attribute__((unused)) int rc,
2639                         __attribute__((unused)) struct raid_map_data *map_buff)
2640 {
2641 }
2642 #endif
2643
2644 static int hpsa_get_raid_map(struct ctlr_info *h,
2645         unsigned char *scsi3addr, struct hpsa_scsi_dev_t *this_device)
2646 {
2647         int rc = 0;
2648         struct CommandList *c;
2649         struct ErrorInfo *ei;
2650
2651         c = cmd_alloc(h);
2652
2653         if (fill_cmd(c, HPSA_GET_RAID_MAP, h, &this_device->raid_map,
2654                         sizeof(this_device->raid_map), 0,
2655                         scsi3addr, TYPE_CMD)) {
2656                 dev_warn(&h->pdev->dev, "hpsa_get_raid_map fill_cmd failed\n");
2657                 cmd_free(h, c);
2658                 return -1;
2659         }
2660         rc = hpsa_scsi_do_simple_cmd_with_retry(h, c,
2661                                         PCI_DMA_FROMDEVICE, NO_TIMEOUT);
2662         if (rc)
2663                 goto out;
2664         ei = c->err_info;
2665         if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
2666                 hpsa_scsi_interpret_error(h, c);
2667                 rc = -1;
2668                 goto out;
2669         }
2670         cmd_free(h, c);
2671
2672         /* @todo in the future, dynamically allocate RAID map memory */
2673         if (le32_to_cpu(this_device->raid_map.structure_size) >
2674                                 sizeof(this_device->raid_map)) {
2675                 dev_warn(&h->pdev->dev, "RAID map size is too large!\n");
2676                 rc = -1;
2677         }
2678         hpsa_debug_map_buff(h, rc, &this_device->raid_map);
2679         return rc;
2680 out:
2681         cmd_free(h, c);
2682         return rc;
2683 }
2684
2685 static int hpsa_bmic_id_physical_device(struct ctlr_info *h,
2686                 unsigned char scsi3addr[], u16 bmic_device_index,
2687                 struct bmic_identify_physical_device *buf, size_t bufsize)
2688 {
2689         int rc = IO_OK;
2690         struct CommandList *c;
2691         struct ErrorInfo *ei;
2692
2693         c = cmd_alloc(h);
2694         rc = fill_cmd(c, BMIC_IDENTIFY_PHYSICAL_DEVICE, h, buf, bufsize,
2695                 0, RAID_CTLR_LUNID, TYPE_CMD);
2696         if (rc)
2697                 goto out;
2698
2699         c->Request.CDB[2] = bmic_device_index & 0xff;
2700         c->Request.CDB[9] = (bmic_device_index >> 8) & 0xff;
2701
2702         hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE,
2703                                                 NO_TIMEOUT);
2704         ei = c->err_info;
2705         if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
2706                 hpsa_scsi_interpret_error(h, c);
2707                 rc = -1;
2708         }
2709 out:
2710         cmd_free(h, c);
2711         return rc;
2712 }
2713
2714 static int hpsa_vpd_page_supported(struct ctlr_info *h,
2715         unsigned char scsi3addr[], u8 page)
2716 {
2717         int rc;
2718         int i;
2719         int pages;
2720         unsigned char *buf, bufsize;
2721
2722         buf = kzalloc(256, GFP_KERNEL);
2723         if (!buf)
2724                 return 0;
2725
2726         /* Get the size of the page list first */
2727         rc = hpsa_scsi_do_inquiry(h, scsi3addr,
2728                                 VPD_PAGE | HPSA_VPD_SUPPORTED_PAGES,
2729                                 buf, HPSA_VPD_HEADER_SZ);
2730         if (rc != 0)
2731                 goto exit_unsupported;
2732         pages = buf[3];
2733         if ((pages + HPSA_VPD_HEADER_SZ) <= 255)
2734                 bufsize = pages + HPSA_VPD_HEADER_SZ;
2735         else
2736                 bufsize = 255;
2737
2738         /* Get the whole VPD page list */
2739         rc = hpsa_scsi_do_inquiry(h, scsi3addr,
2740                                 VPD_PAGE | HPSA_VPD_SUPPORTED_PAGES,
2741                                 buf, bufsize);
2742         if (rc != 0)
2743                 goto exit_unsupported;
2744
2745         pages = buf[3];
2746         for (i = 1; i <= pages; i++)
2747                 if (buf[3 + i] == page)
2748                         goto exit_supported;
2749 exit_unsupported:
2750         kfree(buf);
2751         return 0;
2752 exit_supported:
2753         kfree(buf);
2754         return 1;
2755 }
2756
2757 static void hpsa_get_ioaccel_status(struct ctlr_info *h,
2758         unsigned char *scsi3addr, struct hpsa_scsi_dev_t *this_device)
2759 {
2760         int rc;
2761         unsigned char *buf;
2762         u8 ioaccel_status;
2763
2764         this_device->offload_config = 0;
2765         this_device->offload_enabled = 0;
2766         this_device->offload_to_be_enabled = 0;
2767
2768         buf = kzalloc(64, GFP_KERNEL);
2769         if (!buf)
2770                 return;
2771         if (!hpsa_vpd_page_supported(h, scsi3addr, HPSA_VPD_LV_IOACCEL_STATUS))
2772                 goto out;
2773         rc = hpsa_scsi_do_inquiry(h, scsi3addr,
2774                         VPD_PAGE | HPSA_VPD_LV_IOACCEL_STATUS, buf, 64);
2775         if (rc != 0)
2776                 goto out;
2777
2778 #define IOACCEL_STATUS_BYTE 4
2779 #define OFFLOAD_CONFIGURED_BIT 0x01
2780 #define OFFLOAD_ENABLED_BIT 0x02
2781         ioaccel_status = buf[IOACCEL_STATUS_BYTE];
2782         this_device->offload_config =
2783                 !!(ioaccel_status & OFFLOAD_CONFIGURED_BIT);
2784         if (this_device->offload_config) {
2785                 this_device->offload_enabled =
2786                         !!(ioaccel_status & OFFLOAD_ENABLED_BIT);
2787                 if (hpsa_get_raid_map(h, scsi3addr, this_device))
2788                         this_device->offload_enabled = 0;
2789         }
2790         this_device->offload_to_be_enabled = this_device->offload_enabled;
2791 out:
2792         kfree(buf);
2793         return;
2794 }
2795
2796 /* Get the device id from inquiry page 0x83 */
2797 static int hpsa_get_device_id(struct ctlr_info *h, unsigned char *scsi3addr,
2798         unsigned char *device_id, int buflen)
2799 {
2800         int rc;
2801         unsigned char *buf;
2802
2803         if (buflen > 16)
2804                 buflen = 16;
2805         buf = kzalloc(64, GFP_KERNEL);
2806         if (!buf)
2807                 return -ENOMEM;
2808         rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE | 0x83, buf, 64);
2809         if (rc == 0)
2810                 memcpy(device_id, &buf[8], buflen);
2811         kfree(buf);
2812         return rc != 0;
2813 }
2814
2815 static int hpsa_scsi_do_report_luns(struct ctlr_info *h, int logical,
2816                 void *buf, int bufsize,
2817                 int extended_response)
2818 {
2819         int rc = IO_OK;
2820         struct CommandList *c;
2821         unsigned char scsi3addr[8];
2822         struct ErrorInfo *ei;
2823
2824         c = cmd_alloc(h);
2825
2826         /* address the controller */
2827         memset(scsi3addr, 0, sizeof(scsi3addr));
2828         if (fill_cmd(c, logical ? HPSA_REPORT_LOG : HPSA_REPORT_PHYS, h,
2829                 buf, bufsize, 0, scsi3addr, TYPE_CMD)) {
2830                 rc = -1;
2831                 goto out;
2832         }
2833         if (extended_response)
2834                 c->Request.CDB[1] = extended_response;
2835         rc = hpsa_scsi_do_simple_cmd_with_retry(h, c,
2836                                         PCI_DMA_FROMDEVICE, NO_TIMEOUT);
2837         if (rc)
2838                 goto out;
2839         ei = c->err_info;
2840         if (ei->CommandStatus != 0 &&
2841             ei->CommandStatus != CMD_DATA_UNDERRUN) {
2842                 hpsa_scsi_interpret_error(h, c);
2843                 rc = -1;
2844         } else {
2845                 struct ReportLUNdata *rld = buf;
2846
2847                 if (rld->extended_response_flag != extended_response) {
2848                         dev_err(&h->pdev->dev,
2849                                 "report luns requested format %u, got %u\n",
2850                                 extended_response,
2851                                 rld->extended_response_flag);
2852                         rc = -1;
2853                 }
2854         }
2855 out:
2856         cmd_free(h, c);
2857         return rc;
2858 }
2859
2860 static inline int hpsa_scsi_do_report_phys_luns(struct ctlr_info *h,
2861                 struct ReportExtendedLUNdata *buf, int bufsize)
2862 {
2863         return hpsa_scsi_do_report_luns(h, 0, buf, bufsize,
2864                                                 HPSA_REPORT_PHYS_EXTENDED);
2865 }
2866
2867 static inline int hpsa_scsi_do_report_log_luns(struct ctlr_info *h,
2868                 struct ReportLUNdata *buf, int bufsize)
2869 {
2870         return hpsa_scsi_do_report_luns(h, 1, buf, bufsize, 0);
2871 }
2872
2873 static inline void hpsa_set_bus_target_lun(struct hpsa_scsi_dev_t *device,
2874         int bus, int target, int lun)
2875 {
2876         device->bus = bus;
2877         device->target = target;
2878         device->lun = lun;
2879 }
2880
2881 /* Use VPD inquiry to get details of volume status */
2882 static int hpsa_get_volume_status(struct ctlr_info *h,
2883                                         unsigned char scsi3addr[])
2884 {
2885         int rc;
2886         int status;
2887         int size;
2888         unsigned char *buf;
2889
2890         buf = kzalloc(64, GFP_KERNEL);
2891         if (!buf)
2892                 return HPSA_VPD_LV_STATUS_UNSUPPORTED;
2893
2894         /* Does controller have VPD for logical volume status? */
2895         if (!hpsa_vpd_page_supported(h, scsi3addr, HPSA_VPD_LV_STATUS))
2896                 goto exit_failed;
2897
2898         /* Get the size of the VPD return buffer */
2899         rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE | HPSA_VPD_LV_STATUS,
2900                                         buf, HPSA_VPD_HEADER_SZ);
2901         if (rc != 0)
2902                 goto exit_failed;
2903         size = buf[3];
2904
2905         /* Now get the whole VPD buffer */
2906         rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE | HPSA_VPD_LV_STATUS,
2907                                         buf, size + HPSA_VPD_HEADER_SZ);
2908         if (rc != 0)
2909                 goto exit_failed;
2910         status = buf[4]; /* status byte */
2911
2912         kfree(buf);
2913         return status;
2914 exit_failed:
2915         kfree(buf);
2916         return HPSA_VPD_LV_STATUS_UNSUPPORTED;
2917 }
2918
2919 /* Determine offline status of a volume.
2920  * Return either:
2921  *  0 (not offline)
2922  *  0xff (offline for unknown reasons)
2923  *  # (integer code indicating one of several NOT READY states
2924  *     describing why a volume is to be kept offline)
2925  */
2926 static int hpsa_volume_offline(struct ctlr_info *h,
2927                                         unsigned char scsi3addr[])
2928 {
2929         struct CommandList *c;
2930         unsigned char *sense;
2931         u8 sense_key, asc, ascq;
2932         int sense_len;
2933         int rc, ldstat = 0;
2934         u16 cmd_status;
2935         u8 scsi_status;
2936 #define ASC_LUN_NOT_READY 0x04
2937 #define ASCQ_LUN_NOT_READY_FORMAT_IN_PROGRESS 0x04
2938 #define ASCQ_LUN_NOT_READY_INITIALIZING_CMD_REQ 0x02
2939
2940         c = cmd_alloc(h);
2941
2942         (void) fill_cmd(c, TEST_UNIT_READY, h, NULL, 0, 0, scsi3addr, TYPE_CMD);
2943         rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE, NO_TIMEOUT);
2944         if (rc) {
2945                 cmd_free(h, c);
2946                 return 0;
2947         }
2948         sense = c->err_info->SenseInfo;
2949         if (c->err_info->SenseLen > sizeof(c->err_info->SenseInfo))
2950                 sense_len = sizeof(c->err_info->SenseInfo);
2951         else
2952                 sense_len = c->err_info->SenseLen;
2953         decode_sense_data(sense, sense_len, &sense_key, &asc, &ascq);
2954         cmd_status = c->err_info->CommandStatus;
2955         scsi_status = c->err_info->ScsiStatus;
2956         cmd_free(h, c);
2957         /* Is the volume 'not ready'? */
2958         if (cmd_status != CMD_TARGET_STATUS ||
2959                 scsi_status != SAM_STAT_CHECK_CONDITION ||
2960                 sense_key != NOT_READY ||
2961                 asc != ASC_LUN_NOT_READY)  {
2962                 return 0;
2963         }
2964
2965         /* Determine the reason for not ready state */
2966         ldstat = hpsa_get_volume_status(h, scsi3addr);
2967
2968         /* Keep volume offline in certain cases: */
2969         switch (ldstat) {
2970         case HPSA_LV_UNDERGOING_ERASE:
2971         case HPSA_LV_UNDERGOING_RPI:
2972         case HPSA_LV_PENDING_RPI:
2973         case HPSA_LV_ENCRYPTED_NO_KEY:
2974         case HPSA_LV_PLAINTEXT_IN_ENCRYPT_ONLY_CONTROLLER:
2975         case HPSA_LV_UNDERGOING_ENCRYPTION:
2976         case HPSA_LV_UNDERGOING_ENCRYPTION_REKEYING:
2977         case HPSA_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
2978                 return ldstat;
2979         case HPSA_VPD_LV_STATUS_UNSUPPORTED:
2980                 /* If VPD status page isn't available,
2981                  * use ASC/ASCQ to determine state
2982                  */
2983                 if ((ascq == ASCQ_LUN_NOT_READY_FORMAT_IN_PROGRESS) ||
2984                         (ascq == ASCQ_LUN_NOT_READY_INITIALIZING_CMD_REQ))
2985                         return ldstat;
2986                 break;
2987         default:
2988                 break;
2989         }
2990         return 0;
2991 }
2992
2993 /*
2994  * Find out if a logical device supports aborts by simply trying one.
2995  * Smart Array may claim not to support aborts on logical drives, but
2996  * if a MSA2000 * is connected, the drives on that will be presented
2997  * by the Smart Array as logical drives, and aborts may be sent to
2998  * those devices successfully.  So the simplest way to find out is
2999  * to simply try an abort and see how the device responds.
3000  */
3001 static int hpsa_device_supports_aborts(struct ctlr_info *h,
3002                                         unsigned char *scsi3addr)
3003 {
3004         struct CommandList *c;
3005         struct ErrorInfo *ei;
3006         int rc = 0;
3007
3008         u64 tag = (u64) -1; /* bogus tag */
3009
3010         /* Assume that physical devices support aborts */
3011         if (!is_logical_dev_addr_mode(scsi3addr))
3012                 return 1;
3013
3014         c = cmd_alloc(h);
3015
3016         (void) fill_cmd(c, HPSA_ABORT_MSG, h, &tag, 0, 0, scsi3addr, TYPE_MSG);
3017         (void) hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE, NO_TIMEOUT);
3018         /* no unmap needed here because no data xfer. */
3019         ei = c->err_info;
3020         switch (ei->CommandStatus) {
3021         case CMD_INVALID:
3022                 rc = 0;
3023                 break;
3024         case CMD_UNABORTABLE:
3025         case CMD_ABORT_FAILED:
3026                 rc = 1;
3027                 break;
3028         case CMD_TMF_STATUS:
3029                 rc = hpsa_evaluate_tmf_status(h, c);
3030                 break;
3031         default:
3032                 rc = 0;
3033                 break;
3034         }
3035         cmd_free(h, c);
3036         return rc;
3037 }
3038
3039 static int hpsa_update_device_info(struct ctlr_info *h,
3040         unsigned char scsi3addr[], struct hpsa_scsi_dev_t *this_device,
3041         unsigned char *is_OBDR_device)
3042 {
3043
3044 #define OBDR_SIG_OFFSET 43
3045 #define OBDR_TAPE_SIG "$DR-10"
3046 #define OBDR_SIG_LEN (sizeof(OBDR_TAPE_SIG) - 1)
3047 #define OBDR_TAPE_INQ_SIZE (OBDR_SIG_OFFSET + OBDR_SIG_LEN)
3048
3049         unsigned char *inq_buff;
3050         unsigned char *obdr_sig;
3051
3052         inq_buff = kzalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
3053         if (!inq_buff)
3054                 goto bail_out;
3055
3056         /* Do an inquiry to the device to see what it is. */
3057         if (hpsa_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
3058                 (unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
3059                 /* Inquiry failed (msg printed already) */
3060                 dev_err(&h->pdev->dev,
3061                         "hpsa_update_device_info: inquiry failed\n");
3062                 goto bail_out;
3063         }
3064
3065         this_device->devtype = (inq_buff[0] & 0x1f);
3066         memcpy(this_device->scsi3addr, scsi3addr, 8);
3067         memcpy(this_device->vendor, &inq_buff[8],
3068                 sizeof(this_device->vendor));
3069         memcpy(this_device->model, &inq_buff[16],
3070                 sizeof(this_device->model));
3071         memset(this_device->device_id, 0,
3072                 sizeof(this_device->device_id));
3073         hpsa_get_device_id(h, scsi3addr, this_device->device_id,
3074                 sizeof(this_device->device_id));
3075
3076         if (this_device->devtype == TYPE_DISK &&
3077                 is_logical_dev_addr_mode(scsi3addr)) {
3078                 int volume_offline;
3079
3080                 hpsa_get_raid_level(h, scsi3addr, &this_device->raid_level);
3081                 if (h->fw_support & MISC_FW_RAID_OFFLOAD_BASIC)
3082                         hpsa_get_ioaccel_status(h, scsi3addr, this_device);
3083                 volume_offline = hpsa_volume_offline(h, scsi3addr);
3084                 if (volume_offline < 0 || volume_offline > 0xff)
3085                         volume_offline = HPSA_VPD_LV_STATUS_UNSUPPORTED;
3086                 this_device->volume_offline = volume_offline & 0xff;
3087         } else {
3088                 this_device->raid_level = RAID_UNKNOWN;
3089                 this_device->offload_config = 0;
3090                 this_device->offload_enabled = 0;
3091                 this_device->offload_to_be_enabled = 0;
3092                 this_device->hba_ioaccel_enabled = 0;
3093                 this_device->volume_offline = 0;
3094                 this_device->queue_depth = h->nr_cmds;
3095         }
3096
3097         if (is_OBDR_device) {
3098                 /* See if this is a One-Button-Disaster-Recovery device
3099                  * by looking for "$DR-10" at offset 43 in inquiry data.
3100                  */
3101                 obdr_sig = &inq_buff[OBDR_SIG_OFFSET];
3102                 *is_OBDR_device = (this_device->devtype == TYPE_ROM &&
3103                                         strncmp(obdr_sig, OBDR_TAPE_SIG,
3104                                                 OBDR_SIG_LEN) == 0);
3105         }
3106         kfree(inq_buff);
3107         return 0;
3108
3109 bail_out:
3110         kfree(inq_buff);
3111         return 1;
3112 }
3113
3114 static void hpsa_update_device_supports_aborts(struct ctlr_info *h,
3115                         struct hpsa_scsi_dev_t *dev, u8 *scsi3addr)
3116 {
3117         unsigned long flags;
3118         int rc, entry;
3119         /*
3120          * See if this device supports aborts.  If we already know
3121          * the device, we already know if it supports aborts, otherwise
3122          * we have to find out if it supports aborts by trying one.
3123          */
3124         spin_lock_irqsave(&h->devlock, flags);
3125         rc = hpsa_scsi_find_entry(dev, h->dev, h->ndevices, &entry);
3126         if ((rc == DEVICE_SAME || rc == DEVICE_UPDATED) &&
3127                 entry >= 0 && entry < h->ndevices) {
3128                 dev->supports_aborts = h->dev[entry]->supports_aborts;
3129                 spin_unlock_irqrestore(&h->devlock, flags);
3130         } else {
3131                 spin_unlock_irqrestore(&h->devlock, flags);
3132                 dev->supports_aborts =
3133                                 hpsa_device_supports_aborts(h, scsi3addr);
3134                 if (dev->supports_aborts < 0)
3135                         dev->supports_aborts = 0;
3136         }
3137 }
3138
3139 static unsigned char *ext_target_model[] = {
3140         "MSA2012",
3141         "MSA2024",
3142         "MSA2312",
3143         "MSA2324",
3144         "P2000 G3 SAS",
3145         "MSA 2040 SAS",
3146         NULL,
3147 };
3148
3149 static int is_ext_target(struct ctlr_info *h, struct hpsa_scsi_dev_t *device)
3150 {
3151         int i;
3152
3153         for (i = 0; ext_target_model[i]; i++)
3154                 if (strncmp(device->model, ext_target_model[i],
3155                         strlen(ext_target_model[i])) == 0)
3156                         return 1;
3157         return 0;
3158 }
3159
3160 /* Helper function to assign bus, target, lun mapping of devices.
3161  * Puts non-external target logical volumes on bus 0, external target logical
3162  * volumes on bus 1, physical devices on bus 2. and the hba on bus 3.
3163  * Logical drive target and lun are assigned at this time, but
3164  * physical device lun and target assignment are deferred (assigned
3165  * in hpsa_find_target_lun, called by hpsa_scsi_add_entry.)
3166  */
3167 static void figure_bus_target_lun(struct ctlr_info *h,
3168         u8 *lunaddrbytes, struct hpsa_scsi_dev_t *device)
3169 {
3170         u32 lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
3171
3172         if (!is_logical_dev_addr_mode(lunaddrbytes)) {
3173                 /* physical device, target and lun filled in later */
3174                 if (is_hba_lunid(lunaddrbytes))
3175                         hpsa_set_bus_target_lun(device, 3, 0, lunid & 0x3fff);
3176                 else
3177                         /* defer target, lun assignment for physical devices */
3178                         hpsa_set_bus_target_lun(device, 2, -1, -1);
3179                 return;
3180         }
3181         /* It's a logical device */
3182         if (is_ext_target(h, device)) {
3183                 /* external target way, put logicals on bus 1
3184                  * and match target/lun numbers box
3185                  * reports, other smart array, bus 0, target 0, match lunid
3186                  */
3187                 hpsa_set_bus_target_lun(device,
3188                         1, (lunid >> 16) & 0x3fff, lunid & 0x00ff);
3189                 return;
3190         }
3191         hpsa_set_bus_target_lun(device, 0, 0, lunid & 0x3fff);
3192 }
3193
3194 /*
3195  * If there is no lun 0 on a target, linux won't find any devices.
3196  * For the external targets (arrays), we have to manually detect the enclosure
3197  * which is at lun zero, as CCISS_REPORT_PHYSICAL_LUNS doesn't report
3198  * it for some reason.  *tmpdevice is the target we're adding,
3199  * this_device is a pointer into the current element of currentsd[]
3200  * that we're building up in update_scsi_devices(), below.
3201  * lunzerobits is a bitmap that tracks which targets already have a
3202  * lun 0 assigned.
3203  * Returns 1 if an enclosure was added, 0 if not.
3204  */
3205 static int add_ext_target_dev(struct ctlr_info *h,
3206         struct hpsa_scsi_dev_t *tmpdevice,
3207         struct hpsa_scsi_dev_t *this_device, u8 *lunaddrbytes,
3208         unsigned long lunzerobits[], int *n_ext_target_devs)
3209 {
3210         unsigned char scsi3addr[8];
3211
3212         if (test_bit(tmpdevice->target, lunzerobits))
3213                 return 0; /* There is already a lun 0 on this target. */
3214
3215         if (!is_logical_dev_addr_mode(lunaddrbytes))
3216                 return 0; /* It's the logical targets that may lack lun 0. */
3217
3218         if (!is_ext_target(h, tmpdevice))
3219                 return 0; /* Only external target devices have this problem. */
3220
3221         if (tmpdevice->lun == 0) /* if lun is 0, then we have a lun 0. */
3222                 return 0;
3223
3224         memset(scsi3addr, 0, 8);
3225         scsi3addr[3] = tmpdevice->target;
3226         if (is_hba_lunid(scsi3addr))
3227                 return 0; /* Don't add the RAID controller here. */
3228
3229         if (is_scsi_rev_5(h))
3230                 return 0; /* p1210m doesn't need to do this. */
3231
3232         if (*n_ext_target_devs >= MAX_EXT_TARGETS) {
3233                 dev_warn(&h->pdev->dev, "Maximum number of external "
3234                         "target devices exceeded.  Check your hardware "
3235                         "configuration.");
3236                 return 0;
3237         }
3238
3239         if (hpsa_update_device_info(h, scsi3addr, this_device, NULL))
3240                 return 0;
3241         (*n_ext_target_devs)++;
3242         hpsa_set_bus_target_lun(this_device,
3243                                 tmpdevice->bus, tmpdevice->target, 0);
3244         hpsa_update_device_supports_aborts(h, this_device, scsi3addr);
3245         set_bit(tmpdevice->target, lunzerobits);
3246         return 1;
3247 }
3248
3249 /*
3250  * Get address of physical disk used for an ioaccel2 mode command:
3251  *      1. Extract ioaccel2 handle from the command.
3252  *      2. Find a matching ioaccel2 handle from list of physical disks.
3253  *      3. Return:
3254  *              1 and set scsi3addr to address of matching physical
3255  *              0 if no matching physical disk was found.
3256  */
3257 static int hpsa_get_pdisk_of_ioaccel2(struct ctlr_info *h,
3258         struct CommandList *ioaccel2_cmd_to_abort, unsigned char *scsi3addr)
3259 {
3260         struct io_accel2_cmd *c2 =
3261                         &h->ioaccel2_cmd_pool[ioaccel2_cmd_to_abort->cmdindex];
3262         unsigned long flags;
3263         int i;
3264
3265         spin_lock_irqsave(&h->devlock, flags);
3266         for (i = 0; i < h->ndevices; i++)
3267                 if (h->dev[i]->ioaccel_handle == le32_to_cpu(c2->scsi_nexus)) {
3268                         memcpy(scsi3addr, h->dev[i]->scsi3addr,
3269                                 sizeof(h->dev[i]->scsi3addr));
3270                         spin_unlock_irqrestore(&h->devlock, flags);
3271                         return 1;
3272                 }
3273         spin_unlock_irqrestore(&h->devlock, flags);
3274         return 0;
3275 }
3276
3277 /*
3278  * Do CISS_REPORT_PHYS and CISS_REPORT_LOG.  Data is returned in physdev,
3279  * logdev.  The number of luns in physdev and logdev are returned in
3280  * *nphysicals and *nlogicals, respectively.
3281  * Returns 0 on success, -1 otherwise.
3282  */
3283 static int hpsa_gather_lun_info(struct ctlr_info *h,
3284         struct ReportExtendedLUNdata *physdev, u32 *nphysicals,
3285         struct ReportLUNdata *logdev, u32 *nlogicals)
3286 {
3287         if (hpsa_scsi_do_report_phys_luns(h, physdev, sizeof(*physdev))) {
3288                 dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
3289                 return -1;
3290         }
3291         *nphysicals = be32_to_cpu(*((__be32 *)physdev->LUNListLength)) / 24;
3292         if (*nphysicals > HPSA_MAX_PHYS_LUN) {
3293                 dev_warn(&h->pdev->dev, "maximum physical LUNs (%d) exceeded. %d LUNs ignored.\n",
3294                         HPSA_MAX_PHYS_LUN, *nphysicals - HPSA_MAX_PHYS_LUN);
3295                 *nphysicals = HPSA_MAX_PHYS_LUN;
3296         }
3297         if (hpsa_scsi_do_report_log_luns(h, logdev, sizeof(*logdev))) {
3298                 dev_err(&h->pdev->dev, "report logical LUNs failed.\n");
3299                 return -1;
3300         }
3301         *nlogicals = be32_to_cpu(*((__be32 *) logdev->LUNListLength)) / 8;
3302         /* Reject Logicals in excess of our max capability. */
3303         if (*nlogicals > HPSA_MAX_LUN) {
3304                 dev_warn(&h->pdev->dev,
3305                         "maximum logical LUNs (%d) exceeded.  "
3306                         "%d LUNs ignored.\n", HPSA_MAX_LUN,
3307                         *nlogicals - HPSA_MAX_LUN);
3308                         *nlogicals = HPSA_MAX_LUN;
3309         }
3310         if (*nlogicals + *nphysicals > HPSA_MAX_PHYS_LUN) {
3311                 dev_warn(&h->pdev->dev,
3312                         "maximum logical + physical LUNs (%d) exceeded. "
3313                         "%d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
3314                         *nphysicals + *nlogicals - HPSA_MAX_PHYS_LUN);
3315                 *nlogicals = HPSA_MAX_PHYS_LUN - *nphysicals;
3316         }
3317         return 0;
3318 }
3319
3320 static u8 *figure_lunaddrbytes(struct ctlr_info *h, int raid_ctlr_position,
3321         int i, int nphysicals, int nlogicals,
3322         struct ReportExtendedLUNdata *physdev_list,
3323         struct ReportLUNdata *logdev_list)
3324 {
3325         /* Helper function, figure out where the LUN ID info is coming from
3326          * given index i, lists of physical and logical devices, where in
3327          * the list the raid controller is supposed to appear (first or last)
3328          */
3329
3330         int logicals_start = nphysicals + (raid_ctlr_position == 0);
3331         int last_device = nphysicals + nlogicals + (raid_ctlr_position == 0);
3332
3333         if (i == raid_ctlr_position)
3334                 return RAID_CTLR_LUNID;
3335
3336         if (i < logicals_start)
3337                 return &physdev_list->LUN[i -
3338                                 (raid_ctlr_position == 0)].lunid[0];
3339
3340         if (i < last_device)
3341                 return &logdev_list->LUN[i - nphysicals -
3342                         (raid_ctlr_position == 0)][0];
3343         BUG();
3344         return NULL;
3345 }
3346
3347 static int hpsa_hba_mode_enabled(struct ctlr_info *h)
3348 {
3349         int rc;
3350         int hba_mode_enabled;
3351         struct bmic_controller_parameters *ctlr_params;
3352         ctlr_params = kzalloc(sizeof(struct bmic_controller_parameters),
3353                 GFP_KERNEL);
3354
3355         if (!ctlr_params)
3356                 return -ENOMEM;
3357         rc = hpsa_bmic_ctrl_mode_sense(h, RAID_CTLR_LUNID, 0, ctlr_params,
3358                 sizeof(struct bmic_controller_parameters));
3359         if (rc) {
3360                 kfree(ctlr_params);
3361                 return rc;
3362         }
3363
3364         hba_mode_enabled =
3365                 ((ctlr_params->nvram_flags & HBA_MODE_ENABLED_FLAG) != 0);
3366         kfree(ctlr_params);
3367         return hba_mode_enabled;
3368 }
3369
3370 /* get physical drive ioaccel handle and queue depth */
3371 static void hpsa_get_ioaccel_drive_info(struct ctlr_info *h,
3372                 struct hpsa_scsi_dev_t *dev,
3373                 u8 *lunaddrbytes,
3374                 struct bmic_identify_physical_device *id_phys)
3375 {
3376         int rc;
3377         struct ext_report_lun_entry *rle =
3378                 (struct ext_report_lun_entry *) lunaddrbytes;
3379
3380         dev->ioaccel_handle = rle->ioaccel_handle;
3381         if (PHYS_IOACCEL(lunaddrbytes) && dev->ioaccel_handle)
3382                 dev->hba_ioaccel_enabled = 1;
3383         memset(id_phys, 0, sizeof(*id_phys));
3384         rc = hpsa_bmic_id_physical_device(h, lunaddrbytes,
3385                         GET_BMIC_DRIVE_NUMBER(lunaddrbytes), id_phys,
3386                         sizeof(*id_phys));
3387         if (!rc)
3388                 /* Reserve space for FW operations */
3389 #define DRIVE_CMDS_RESERVED_FOR_FW 2
3390 #define DRIVE_QUEUE_DEPTH 7
3391                 dev->queue_depth =
3392                         le16_to_cpu(id_phys->current_queue_depth_limit) -
3393                                 DRIVE_CMDS_RESERVED_FOR_FW;
3394         else
3395                 dev->queue_depth = DRIVE_QUEUE_DEPTH; /* conservative */
3396         atomic_set(&dev->ioaccel_cmds_out, 0);
3397 }
3398
3399 static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno)
3400 {
3401         /* the idea here is we could get notified
3402          * that some devices have changed, so we do a report
3403          * physical luns and report logical luns cmd, and adjust
3404          * our list of devices accordingly.
3405          *
3406          * The scsi3addr's of devices won't change so long as the
3407          * adapter is not reset.  That means we can rescan and
3408          * tell which devices we already know about, vs. new
3409          * devices, vs.  disappearing devices.
3410          */
3411         struct ReportExtendedLUNdata *physdev_list = NULL;
3412         struct ReportLUNdata *logdev_list = NULL;
3413         struct bmic_identify_physical_device *id_phys = NULL;
3414         u32 nphysicals = 0;
3415         u32 nlogicals = 0;
3416         u32 ndev_allocated = 0;
3417         struct hpsa_scsi_dev_t **currentsd, *this_device, *tmpdevice;
3418         int ncurrent = 0;
3419         int i, n_ext_target_devs, ndevs_to_allocate;
3420         int raid_ctlr_position;
3421         int rescan_hba_mode;
3422         DECLARE_BITMAP(lunzerobits, MAX_EXT_TARGETS);
3423
3424         currentsd = kzalloc(sizeof(*currentsd) * HPSA_MAX_DEVICES, GFP_KERNEL);
3425         physdev_list = kzalloc(sizeof(*physdev_list), GFP_KERNEL);
3426         logdev_list = kzalloc(sizeof(*logdev_list), GFP_KERNEL);
3427         tmpdevice = kzalloc(sizeof(*tmpdevice), GFP_KERNEL);
3428         id_phys = kzalloc(sizeof(*id_phys), GFP_KERNEL);
3429
3430         if (!currentsd || !physdev_list || !logdev_list ||
3431                 !tmpdevice || !id_phys) {
3432                 dev_err(&h->pdev->dev, "out of memory\n");
3433                 goto out;
3434         }
3435         memset(lunzerobits, 0, sizeof(lunzerobits));
3436
3437         rescan_hba_mode = hpsa_hba_mode_enabled(h);
3438         if (rescan_hba_mode < 0)
3439                 goto out;
3440
3441         if (!h->hba_mode_enabled && rescan_hba_mode)
3442                 dev_warn(&h->pdev->dev, "HBA mode enabled\n");
3443         else if (h->hba_mode_enabled && !rescan_hba_mode)
3444                 dev_warn(&h->pdev->dev, "HBA mode disabled\n");
3445
3446         h->hba_mode_enabled = rescan_hba_mode;
3447
3448         if (hpsa_gather_lun_info(h, physdev_list, &nphysicals,
3449                         logdev_list, &nlogicals))
3450                 goto out;
3451
3452         /* We might see up to the maximum number of logical and physical disks
3453          * plus external target devices, and a device for the local RAID
3454          * controller.
3455          */
3456         ndevs_to_allocate = nphysicals + nlogicals + MAX_EXT_TARGETS + 1;
3457
3458         /* Allocate the per device structures */
3459         for (i = 0; i < ndevs_to_allocate; i++) {
3460                 if (i >= HPSA_MAX_DEVICES) {
3461                         dev_warn(&h->pdev->dev, "maximum devices (%d) exceeded."
3462                                 "  %d devices ignored.\n", HPSA_MAX_DEVICES,
3463                                 ndevs_to_allocate - HPSA_MAX_DEVICES);
3464                         break;
3465                 }
3466
3467                 currentsd[i] = kzalloc(sizeof(*currentsd[i]), GFP_KERNEL);
3468                 if (!currentsd[i]) {
3469                         dev_warn(&h->pdev->dev, "out of memory at %s:%d\n",
3470                                 __FILE__, __LINE__);
3471                         goto out;
3472                 }
3473                 ndev_allocated++;
3474         }
3475
3476         if (is_scsi_rev_5(h))
3477                 raid_ctlr_position = 0;
3478         else
3479                 raid_ctlr_position = nphysicals + nlogicals;
3480
3481         /* adjust our table of devices */
3482         n_ext_target_devs = 0;
3483         for (i = 0; i < nphysicals + nlogicals + 1; i++) {
3484                 u8 *lunaddrbytes, is_OBDR = 0;
3485
3486                 /* Figure out where the LUN ID info is coming from */
3487                 lunaddrbytes = figure_lunaddrbytes(h, raid_ctlr_position,
3488                         i, nphysicals, nlogicals, physdev_list, logdev_list);
3489
3490                 /* skip masked non-disk devices */
3491                 if (MASKED_DEVICE(lunaddrbytes))
3492                         if (i < nphysicals + (raid_ctlr_position == 0) &&
3493                                 NON_DISK_PHYS_DEV(lunaddrbytes))
3494                                 continue;
3495
3496                 /* Get device type, vendor, model, device id */
3497                 if (hpsa_update_device_info(h, lunaddrbytes, tmpdevice,
3498                                                         &is_OBDR))
3499                         continue; /* skip it if we can't talk to it. */
3500                 figure_bus_target_lun(h, lunaddrbytes, tmpdevice);
3501                 hpsa_update_device_supports_aborts(h, tmpdevice, lunaddrbytes);
3502                 this_device = currentsd[ncurrent];
3503
3504                 /*
3505                  * For external target devices, we have to insert a LUN 0 which
3506                  * doesn't show up in CCISS_REPORT_PHYSICAL data, but there
3507                  * is nonetheless an enclosure device there.  We have to
3508                  * present that otherwise linux won't find anything if
3509                  * there is no lun 0.
3510                  */
3511                 if (add_ext_target_dev(h, tmpdevice, this_device,
3512                                 lunaddrbytes, lunzerobits,
3513                                 &n_ext_target_devs)) {
3514                         ncurrent++;
3515                         this_device = currentsd[ncurrent];
3516                 }
3517
3518                 *this_device = *tmpdevice;
3519
3520                 /* do not expose masked devices */
3521                 if (MASKED_DEVICE(lunaddrbytes) &&
3522                         i < nphysicals + (raid_ctlr_position == 0)) {
3523                         if (h->hba_mode_enabled)
3524                                 dev_warn(&h->pdev->dev,
3525                                         "Masked physical device detected\n");
3526                         this_device->expose_state = HPSA_DO_NOT_EXPOSE;
3527                 } else {
3528                         this_device->expose_state =
3529                                         HPSA_SG_ATTACH | HPSA_ULD_ATTACH;
3530                 }
3531
3532                 switch (this_device->devtype) {
3533                 case TYPE_ROM:
3534                         /* We don't *really* support actual CD-ROM devices,
3535                          * just "One Button Disaster Recovery" tape drive
3536                          * which temporarily pretends to be a CD-ROM drive.
3537                          * So we check that the device is really an OBDR tape
3538                          * device by checking for "$DR-10" in bytes 43-48 of
3539                          * the inquiry data.
3540                          */
3541                         if (is_OBDR)
3542                                 ncurrent++;
3543                         break;
3544                 case TYPE_DISK:
3545                         if (i >= nphysicals) {
3546                                 ncurrent++;
3547                                 break;
3548                         }
3549
3550                         if (h->hba_mode_enabled)
3551                                 /* never use raid mapper in HBA mode */
3552                                 this_device->offload_enabled = 0;
3553                         else if (!(h->transMethod & CFGTBL_Trans_io_accel1 ||
3554                                 h->transMethod & CFGTBL_Trans_io_accel2))
3555                                 break;
3556
3557                         hpsa_get_ioaccel_drive_info(h, this_device,
3558                                                 lunaddrbytes, id_phys);
3559                         atomic_set(&this_device->ioaccel_cmds_out, 0);
3560                         ncurrent++;
3561                         break;
3562                 case TYPE_TAPE:
3563                 case TYPE_MEDIUM_CHANGER:
3564                         ncurrent++;
3565                         break;
3566                 case TYPE_ENCLOSURE:
3567                         if (h->hba_mode_enabled)
3568                                 ncurrent++;
3569                         break;
3570                 case TYPE_RAID:
3571                         /* Only present the Smartarray HBA as a RAID controller.
3572                          * If it's a RAID controller other than the HBA itself
3573                          * (an external RAID controller, MSA500 or similar)
3574                          * don't present it.
3575                          */
3576                         if (!is_hba_lunid(lunaddrbytes))
3577                                 break;
3578                         ncurrent++;
3579                         break;
3580                 default:
3581                         break;
3582                 }
3583                 if (ncurrent >= HPSA_MAX_DEVICES)
3584                         break;
3585         }
3586         adjust_hpsa_scsi_table(h, hostno, currentsd, ncurrent);
3587 out:
3588         kfree(tmpdevice);
3589         for (i = 0; i < ndev_allocated; i++)
3590                 kfree(currentsd[i]);
3591         kfree(currentsd);
3592         kfree(physdev_list);
3593         kfree(logdev_list);
3594         kfree(id_phys);
3595 }
3596
3597 static void hpsa_set_sg_descriptor(struct SGDescriptor *desc,
3598                                    struct scatterlist *sg)
3599 {
3600         u64 addr64 = (u64) sg_dma_address(sg);
3601         unsigned int len = sg_dma_len(sg);
3602
3603         desc->Addr = cpu_to_le64(addr64);
3604         desc->Len = cpu_to_le32(len);
3605         desc->Ext = 0;
3606 }
3607
3608 /*
3609  * hpsa_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
3610  * dma mapping  and fills in the scatter gather entries of the
3611  * hpsa command, cp.
3612  */
3613 static int hpsa_scatter_gather(struct ctlr_info *h,
3614                 struct CommandList *cp,
3615                 struct scsi_cmnd *cmd)
3616 {
3617         struct scatterlist *sg;
3618         int use_sg, i, sg_index, chained;
3619         struct SGDescriptor *curr_sg;
3620
3621         BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
3622
3623         use_sg = scsi_dma_map(cmd);
3624         if (use_sg < 0)
3625                 return use_sg;
3626
3627         if (!use_sg)
3628                 goto sglist_finished;
3629
3630         curr_sg = cp->SG;
3631         chained = 0;
3632         sg_index = 0;
3633         scsi_for_each_sg(cmd, sg, use_sg, i) {
3634                 if (i == h->max_cmd_sg_entries - 1 &&
3635                         use_sg > h->max_cmd_sg_entries) {
3636                         chained = 1;
3637                         curr_sg = h->cmd_sg_list[cp->cmdindex];
3638                         sg_index = 0;
3639                 }
3640                 hpsa_set_sg_descriptor(curr_sg, sg);
3641                 curr_sg++;
3642         }
3643
3644         /* Back the pointer up to the last entry and mark it as "last". */
3645         (--curr_sg)->Ext = cpu_to_le32(HPSA_SG_LAST);
3646
3647         if (use_sg + chained > h->maxSG)
3648                 h->maxSG = use_sg + chained;
3649
3650         if (chained) {
3651                 cp->Header.SGList = h->max_cmd_sg_entries;
3652                 cp->Header.SGTotal = cpu_to_le16(use_sg + 1);
3653                 if (hpsa_map_sg_chain_block(h, cp)) {
3654                         scsi_dma_unmap(cmd);
3655                         return -1;
3656                 }
3657                 return 0;
3658         }
3659
3660 sglist_finished:
3661
3662         cp->Header.SGList = (u8) use_sg;   /* no. SGs contig in this cmd */
3663         cp->Header.SGTotal = cpu_to_le16(use_sg); /* total sgs in cmd list */
3664         return 0;
3665 }
3666
3667 #define IO_ACCEL_INELIGIBLE (1)
3668 static int fixup_ioaccel_cdb(u8 *cdb, int *cdb_len)
3669 {
3670         int is_write = 0;
3671         u32 block;
3672         u32 block_cnt;
3673
3674         /* Perform some CDB fixups if needed using 10 byte reads/writes only */
3675         switch (cdb[0]) {
3676         case WRITE_6:
3677         case WRITE_12:
3678                 is_write = 1;
3679         case READ_6:
3680         case READ_12:
3681                 if (*cdb_len == 6) {
3682                         block = (((u32) cdb[2]) << 8) | cdb[3];
3683                         block_cnt = cdb[4];
3684                 } else {
3685                         BUG_ON(*cdb_len != 12);
3686                         block = (((u32) cdb[2]) << 24) |
3687                                 (((u32) cdb[3]) << 16) |
3688                                 (((u32) cdb[4]) << 8) |
3689                                 cdb[5];
3690                         block_cnt =
3691                                 (((u32) cdb[6]) << 24) |
3692                                 (((u32) cdb[7]) << 16) |
3693                                 (((u32) cdb[8]) << 8) |
3694                                 cdb[9];
3695                 }
3696                 if (block_cnt > 0xffff)
3697                         return IO_ACCEL_INELIGIBLE;
3698
3699                 cdb[0] = is_write ? WRITE_10 : READ_10;
3700                 cdb[1] = 0;
3701                 cdb[2] = (u8) (block >> 24);
3702                 cdb[3] = (u8) (block >> 16);
3703                 cdb[4] = (u8) (block >> 8);
3704                 cdb[5] = (u8) (block);
3705                 cdb[6] = 0;
3706                 cdb[7] = (u8) (block_cnt >> 8);
3707                 cdb[8] = (u8) (block_cnt);
3708                 cdb[9] = 0;
3709                 *cdb_len = 10;
3710                 break;
3711         }
3712         return 0;
3713 }
3714
3715 static int hpsa_scsi_ioaccel1_queue_command(struct ctlr_info *h,
3716         struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
3717         u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk)
3718 {
3719         struct scsi_cmnd *cmd = c->scsi_cmd;
3720         struct io_accel1_cmd *cp = &h->ioaccel_cmd_pool[c->cmdindex];
3721         unsigned int len;
3722         unsigned int total_len = 0;
3723         struct scatterlist *sg;
3724         u64 addr64;
3725         int use_sg, i;
3726         struct SGDescriptor *curr_sg;
3727         u32 control = IOACCEL1_CONTROL_SIMPLEQUEUE;
3728
3729         /* TODO: implement chaining support */
3730         if (scsi_sg_count(cmd) > h->ioaccel_maxsg) {
3731                 atomic_dec(&phys_disk->ioaccel_cmds_out);
3732                 return IO_ACCEL_INELIGIBLE;
3733         }
3734
3735         BUG_ON(cmd->cmd_len > IOACCEL1_IOFLAGS_CDBLEN_MAX);
3736
3737         if (fixup_ioaccel_cdb(cdb, &cdb_len)) {
3738                 atomic_dec(&phys_disk->ioaccel_cmds_out);
3739                 return IO_ACCEL_INELIGIBLE;
3740         }
3741
3742         c->cmd_type = CMD_IOACCEL1;
3743
3744         /* Adjust the DMA address to point to the accelerated command buffer */
3745         c->busaddr = (u32) h->ioaccel_cmd_pool_dhandle +
3746                                 (c->cmdindex * sizeof(*cp));
3747         BUG_ON(c->busaddr & 0x0000007F);
3748
3749         use_sg = scsi_dma_map(cmd);
3750         if (use_sg < 0) {
3751                 atomic_dec(&phys_disk->ioaccel_cmds_out);
3752                 return use_sg;
3753         }
3754
3755         if (use_sg) {
3756                 curr_sg = cp->SG;
3757                 scsi_for_each_sg(cmd, sg, use_sg, i) {
3758                         addr64 = (u64) sg_dma_address(sg);
3759                         len  = sg_dma_len(sg);
3760                         total_len += len;
3761                         curr_sg->Addr = cpu_to_le64(addr64);
3762                         curr_sg->Len = cpu_to_le32(len);
3763                         curr_sg->Ext = cpu_to_le32(0);
3764                         curr_sg++;
3765                 }
3766                 (--curr_sg)->Ext = cpu_to_le32(HPSA_SG_LAST);
3767
3768                 switch (cmd->sc_data_direction) {
3769                 case DMA_TO_DEVICE:
3770                         control |= IOACCEL1_CONTROL_DATA_OUT;
3771                         break;
3772                 case DMA_FROM_DEVICE:
3773                         control |= IOACCEL1_CONTROL_DATA_IN;
3774                         break;
3775                 case DMA_NONE:
3776                         control |= IOACCEL1_CONTROL_NODATAXFER;
3777                         break;
3778                 default:
3779                         dev_err(&h->pdev->dev, "unknown data direction: %d\n",
3780                         cmd->sc_data_direction);
3781                         BUG();
3782                         break;
3783                 }
3784         } else {
3785                 control |= IOACCEL1_CONTROL_NODATAXFER;
3786         }
3787
3788         c->Header.SGList = use_sg;
3789         /* Fill out the command structure to submit */
3790         cp->dev_handle = cpu_to_le16(ioaccel_handle & 0xFFFF);
3791         cp->transfer_len = cpu_to_le32(total_len);
3792         cp->io_flags = cpu_to_le16(IOACCEL1_IOFLAGS_IO_REQ |
3793                         (cdb_len & IOACCEL1_IOFLAGS_CDBLEN_MASK));
3794         cp->control = cpu_to_le32(control);
3795         memcpy(cp->CDB, cdb, cdb_len);
3796         memcpy(cp->CISS_LUN, scsi3addr, 8);
3797         /* Tag was already set at init time. */
3798         enqueue_cmd_and_start_io(h, c);
3799         return 0;
3800 }
3801
3802 /*
3803  * Queue a command directly to a device behind the controller using the
3804  * I/O accelerator path.
3805  */
3806 static int hpsa_scsi_ioaccel_direct_map(struct ctlr_info *h,
3807         struct CommandList *c)
3808 {
3809         struct scsi_cmnd *cmd = c->scsi_cmd;
3810         struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
3811
3812         c->phys_disk = dev;
3813
3814         return hpsa_scsi_ioaccel_queue_command(h, c, dev->ioaccel_handle,
3815                 cmd->cmnd, cmd->cmd_len, dev->scsi3addr, dev);
3816 }
3817
3818 /*
3819  * Set encryption parameters for the ioaccel2 request
3820  */
3821 static void set_encrypt_ioaccel2(struct ctlr_info *h,
3822         struct CommandList *c, struct io_accel2_cmd *cp)
3823 {
3824         struct scsi_cmnd *cmd = c->scsi_cmd;
3825         struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
3826         struct raid_map_data *map = &dev->raid_map;
3827         u64 first_block;
3828
3829         /* Are we doing encryption on this device */
3830         if (!(le16_to_cpu(map->flags) & RAID_MAP_FLAG_ENCRYPT_ON))
3831                 return;
3832         /* Set the data encryption key index. */
3833         cp->dekindex = map->dekindex;
3834
3835         /* Set the encryption enable flag, encoded into direction field. */
3836         cp->direction |= IOACCEL2_DIRECTION_ENCRYPT_MASK;
3837
3838         /* Set encryption tweak values based on logical block address
3839          * If block size is 512, tweak value is LBA.
3840          * For other block sizes, tweak is (LBA * block size)/ 512)
3841          */
3842         switch (cmd->cmnd[0]) {
3843         /* Required? 6-byte cdbs eliminated by fixup_ioaccel_cdb */
3844         case WRITE_6:
3845         case READ_6:
3846                 first_block = get_unaligned_be16(&cmd->cmnd[2]);
3847                 break;
3848         case WRITE_10:
3849         case READ_10:
3850         /* Required? 12-byte cdbs eliminated by fixup_ioaccel_cdb */
3851         case WRITE_12:
3852         case READ_12:
3853                 first_block = get_unaligned_be32(&cmd->cmnd[2]);
3854                 break;
3855         case WRITE_16:
3856         case READ_16:
3857                 first_block = get_unaligned_be64(&cmd->cmnd[2]);
3858                 break;
3859         default:
3860                 dev_err(&h->pdev->dev,
3861                         "ERROR: %s: size (0x%x) not supported for encryption\n",
3862                         __func__, cmd->cmnd[0]);
3863                 BUG();
3864                 break;
3865         }
3866
3867         if (le32_to_cpu(map->volume_blk_size) != 512)
3868                 first_block = first_block *
3869                                 le32_to_cpu(map->volume_blk_size)/512;
3870
3871         cp->tweak_lower = cpu_to_le32(first_block);
3872         cp->tweak_upper = cpu_to_le32(first_block >> 32);
3873 }
3874
3875 static int hpsa_scsi_ioaccel2_queue_command(struct ctlr_info *h,
3876         struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
3877         u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk)
3878 {
3879         struct scsi_cmnd *cmd = c->scsi_cmd;
3880         struct io_accel2_cmd *cp = &h->ioaccel2_cmd_pool[c->cmdindex];
3881         struct ioaccel2_sg_element *curr_sg;
3882         int use_sg, i;
3883         struct scatterlist *sg;
3884         u64 addr64;
3885         u32 len;
3886         u32 total_len = 0;
3887
3888         BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
3889
3890         if (fixup_ioaccel_cdb(cdb, &cdb_len)) {
3891                 atomic_dec(&phys_disk->ioaccel_cmds_out);
3892                 return IO_ACCEL_INELIGIBLE;
3893         }
3894
3895         c->cmd_type = CMD_IOACCEL2;
3896         /* Adjust the DMA address to point to the accelerated command buffer */
3897         c->busaddr = (u32) h->ioaccel2_cmd_pool_dhandle +
3898                                 (c->cmdindex * sizeof(*cp));
3899         BUG_ON(c->busaddr & 0x0000007F);
3900
3901         memset(cp, 0, sizeof(*cp));
3902         cp->IU_type = IOACCEL2_IU_TYPE;
3903
3904         use_sg = scsi_dma_map(cmd);
3905         if (use_sg < 0) {
3906                 atomic_dec(&phys_disk->ioaccel_cmds_out);
3907                 return use_sg;
3908         }
3909
3910         if (use_sg) {
3911                 curr_sg = cp->sg;
3912                 if (use_sg > h->ioaccel_maxsg) {
3913                         addr64 = le64_to_cpu(
3914                                 h->ioaccel2_cmd_sg_list[c->cmdindex]->address);
3915                         curr_sg->address = cpu_to_le64(addr64);
3916                         curr_sg->length = 0;
3917                         curr_sg->reserved[0] = 0;
3918                         curr_sg->reserved[1] = 0;
3919                         curr_sg->reserved[2] = 0;
3920                         curr_sg->chain_indicator = 0x80;
3921
3922                         curr_sg = h->ioaccel2_cmd_sg_list[c->cmdindex];
3923                 }
3924                 scsi_for_each_sg(cmd, sg, use_sg, i) {
3925                         addr64 = (u64) sg_dma_address(sg);
3926                         len  = sg_dma_len(sg);
3927                         total_len += len;
3928                         curr_sg->address = cpu_to_le64(addr64);
3929                         curr_sg->length = cpu_to_le32(len);
3930                         curr_sg->reserved[0] = 0;
3931                         curr_sg->reserved[1] = 0;
3932                         curr_sg->reserved[2] = 0;
3933                         curr_sg->chain_indicator = 0;
3934                         curr_sg++;
3935                 }
3936
3937                 switch (cmd->sc_data_direction) {
3938                 case DMA_TO_DEVICE:
3939                         cp->direction &= ~IOACCEL2_DIRECTION_MASK;
3940                         cp->direction |= IOACCEL2_DIR_DATA_OUT;
3941                         break;
3942                 case DMA_FROM_DEVICE:
3943                         cp->direction &= ~IOACCEL2_DIRECTION_MASK;
3944                         cp->direction |= IOACCEL2_DIR_DATA_IN;
3945                         break;
3946                 case DMA_NONE:
3947                         cp->direction &= ~IOACCEL2_DIRECTION_MASK;
3948                         cp->direction |= IOACCEL2_DIR_NO_DATA;
3949                         break;
3950                 default:
3951                         dev_err(&h->pdev->dev, "unknown data direction: %d\n",
3952                                 cmd->sc_data_direction);
3953                         BUG();
3954                         break;
3955                 }
3956         } else {
3957                 cp->direction &= ~IOACCEL2_DIRECTION_MASK;
3958                 cp->direction |= IOACCEL2_DIR_NO_DATA;
3959         }
3960
3961         /* Set encryption parameters, if necessary */
3962         set_encrypt_ioaccel2(h, c, cp);
3963
3964         cp->scsi_nexus = cpu_to_le32(ioaccel_handle);
3965         cp->Tag = cpu_to_le32(c->cmdindex << DIRECT_LOOKUP_SHIFT);
3966         memcpy(cp->cdb, cdb, sizeof(cp->cdb));
3967
3968         cp->data_len = cpu_to_le32(total_len);
3969         cp->err_ptr = cpu_to_le64(c->busaddr +
3970                         offsetof(struct io_accel2_cmd, error_data));
3971         cp->err_len = cpu_to_le32(sizeof(cp->error_data));
3972
3973         /* fill in sg elements */
3974         if (use_sg > h->ioaccel_maxsg) {
3975                 cp->sg_count = 1;
3976                 if (hpsa_map_ioaccel2_sg_chain_block(h, cp, c)) {
3977                         atomic_dec(&phys_disk->ioaccel_cmds_out);
3978                         scsi_dma_unmap(cmd);
3979                         return -1;
3980                 }
3981         } else
3982                 cp->sg_count = (u8) use_sg;
3983
3984         enqueue_cmd_and_start_io(h, c);
3985         return 0;
3986 }
3987
3988 /*
3989  * Queue a command to the correct I/O accelerator path.
3990  */
3991 static int hpsa_scsi_ioaccel_queue_command(struct ctlr_info *h,
3992         struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
3993         u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk)
3994 {
3995         /* Try to honor the device's queue depth */
3996         if (atomic_inc_return(&phys_disk->ioaccel_cmds_out) >
3997                                         phys_disk->queue_depth) {
3998                 atomic_dec(&phys_disk->ioaccel_cmds_out);
3999                 return IO_ACCEL_INELIGIBLE;
4000         }
4001         if (h->transMethod & CFGTBL_Trans_io_accel1)
4002                 return hpsa_scsi_ioaccel1_queue_command(h, c, ioaccel_handle,
4003                                                 cdb, cdb_len, scsi3addr,
4004                                                 phys_disk);
4005         else
4006                 return hpsa_scsi_ioaccel2_queue_command(h, c, ioaccel_handle,
4007                                                 cdb, cdb_len, scsi3addr,
4008                                                 phys_disk);
4009 }
4010
4011 static void raid_map_helper(struct raid_map_data *map,
4012                 int offload_to_mirror, u32 *map_index, u32 *current_group)
4013 {
4014         if (offload_to_mirror == 0)  {
4015                 /* use physical disk in the first mirrored group. */
4016                 *map_index %= le16_to_cpu(map->data_disks_per_row);
4017                 return;
4018         }
4019         do {
4020                 /* determine mirror group that *map_index indicates */
4021                 *current_group = *map_index /
4022                         le16_to_cpu(map->data_disks_per_row);
4023                 if (offload_to_mirror == *current_group)
4024                         continue;
4025                 if (*current_group < le16_to_cpu(map->layout_map_count) - 1) {
4026                         /* select map index from next group */
4027                         *map_index += le16_to_cpu(map->data_disks_per_row);
4028                         (*current_group)++;
4029                 } else {
4030                         /* select map index from first group */
4031                         *map_index %= le16_to_cpu(map->data_disks_per_row);
4032                         *current_group = 0;
4033                 }
4034         } while (offload_to_mirror != *current_group);
4035 }
4036
4037 /*
4038  * Attempt to perform offload RAID mapping for a logical volume I/O.
4039  */
4040 static int hpsa_scsi_ioaccel_raid_map(struct ctlr_info *h,
4041         struct CommandList *c)
4042 {
4043         struct scsi_cmnd *cmd = c->scsi_cmd;
4044         struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
4045         struct raid_map_data *map = &dev->raid_map;
4046         struct raid_map_disk_data *dd = &map->data[0];
4047         int is_write = 0;
4048         u32 map_index;
4049         u64 first_block, last_block;
4050         u32 block_cnt;
4051         u32 blocks_per_row;
4052         u64 first_row, last_row;
4053         u32 first_row_offset, last_row_offset;
4054         u32 first_column, last_column;
4055         u64 r0_first_row, r0_last_row;
4056         u32 r5or6_blocks_per_row;
4057         u64 r5or6_first_row, r5or6_last_row;
4058         u32 r5or6_first_row_offset, r5or6_last_row_offset;
4059         u32 r5or6_first_column, r5or6_last_column;
4060         u32 total_disks_per_row;
4061         u32 stripesize;
4062         u32 first_group, last_group, current_group;
4063         u32 map_row;
4064         u32 disk_handle;
4065         u64 disk_block;
4066         u32 disk_block_cnt;
4067         u8 cdb[16];
4068         u8 cdb_len;
4069         u16 strip_size;
4070 #if BITS_PER_LONG == 32
4071         u64 tmpdiv;
4072 #endif
4073         int offload_to_mirror;
4074
4075         /* check for valid opcode, get LBA and block count */
4076         switch (cmd->cmnd[0]) {
4077         case WRITE_6:
4078                 is_write = 1;
4079         case READ_6:
4080                 first_block =
4081                         (((u64) cmd->cmnd[2]) << 8) |
4082                         cmd->cmnd[3];
4083                 block_cnt = cmd->cmnd[4];
4084                 if (block_cnt == 0)
4085                         block_cnt = 256;
4086                 break;
4087         case WRITE_10:
4088                 is_write = 1;
4089         case READ_10:
4090                 first_block =
4091                         (((u64) cmd->cmnd[2]) << 24) |
4092                         (((u64) cmd->cmnd[3]) << 16) |
4093                         (((u64) cmd->cmnd[4]) << 8) |
4094                         cmd->cmnd[5];
4095                 block_cnt =
4096                         (((u32) cmd->cmnd[7]) << 8) |
4097                         cmd->cmnd[8];
4098                 break;
4099         case WRITE_12:
4100                 is_write = 1;
4101         case READ_12:
4102                 first_block =
4103                         (((u64) cmd->cmnd[2]) << 24) |
4104                         (((u64) cmd->cmnd[3]) << 16) |
4105                         (((u64) cmd->cmnd[4]) << 8) |
4106                         cmd->cmnd[5];
4107                 block_cnt =
4108                         (((u32) cmd->cmnd[6]) << 24) |
4109                         (((u32) cmd->cmnd[7]) << 16) |
4110                         (((u32) cmd->cmnd[8]) << 8) |
4111                 cmd->cmnd[9];
4112                 break;
4113         case WRITE_16:
4114                 is_write = 1;
4115         case READ_16:
4116                 first_block =
4117                         (((u64) cmd->cmnd[2]) << 56) |
4118                         (((u64) cmd->cmnd[3]) << 48) |
4119                         (((u64) cmd->cmnd[4]) << 40) |
4120                         (((u64) cmd->cmnd[5]) << 32) |
4121                         (((u64) cmd->cmnd[6]) << 24) |
4122                         (((u64) cmd->cmnd[7]) << 16) |
4123                         (((u64) cmd->cmnd[8]) << 8) |
4124                         cmd->cmnd[9];
4125                 block_cnt =
4126                         (((u32) cmd->cmnd[10]) << 24) |
4127                         (((u32) cmd->cmnd[11]) << 16) |
4128                         (((u32) cmd->cmnd[12]) << 8) |
4129                         cmd->cmnd[13];
4130                 break;
4131         default:
4132                 return IO_ACCEL_INELIGIBLE; /* process via normal I/O path */
4133         }
4134         last_block = first_block + block_cnt - 1;
4135
4136         /* check for write to non-RAID-0 */
4137         if (is_write && dev->raid_level != 0)
4138                 return IO_ACCEL_INELIGIBLE;
4139
4140         /* check for invalid block or wraparound */
4141         if (last_block >= le64_to_cpu(map->volume_blk_cnt) ||
4142                 last_block < first_block)
4143                 return IO_ACCEL_INELIGIBLE;
4144
4145         /* calculate stripe information for the request */
4146         blocks_per_row = le16_to_cpu(map->data_disks_per_row) *
4147                                 le16_to_cpu(map->strip_size);
4148         strip_size = le16_to_cpu(map->strip_size);
4149 #if BITS_PER_LONG == 32
4150         tmpdiv = first_block;
4151         (void) do_div(tmpdiv, blocks_per_row);
4152         first_row = tmpdiv;
4153         tmpdiv = last_block;
4154         (void) do_div(tmpdiv, blocks_per_row);
4155         last_row = tmpdiv;
4156         first_row_offset = (u32) (first_block - (first_row * blocks_per_row));
4157         last_row_offset = (u32) (last_block - (last_row * blocks_per_row));
4158         tmpdiv = first_row_offset;
4159         (void) do_div(tmpdiv, strip_size);
4160         first_column = tmpdiv;
4161         tmpdiv = last_row_offset;
4162         (void) do_div(tmpdiv, strip_size);
4163         last_column = tmpdiv;
4164 #else
4165         first_row = first_block / blocks_per_row;
4166         last_row = last_block / blocks_per_row;
4167         first_row_offset = (u32) (first_block - (first_row * blocks_per_row));
4168         last_row_offset = (u32) (last_block - (last_row * blocks_per_row));
4169         first_column = first_row_offset / strip_size;
4170         last_column = last_row_offset / strip_size;
4171 #endif
4172
4173         /* if this isn't a single row/column then give to the controller */
4174         if ((first_row != last_row) || (first_column != last_column))
4175                 return IO_ACCEL_INELIGIBLE;
4176
4177         /* proceeding with driver mapping */
4178         total_disks_per_row = le16_to_cpu(map->data_disks_per_row) +
4179                                 le16_to_cpu(map->metadata_disks_per_row);
4180         map_row = ((u32)(first_row >> map->parity_rotation_shift)) %
4181                                 le16_to_cpu(map->row_cnt);
4182         map_index = (map_row * total_disks_per_row) + first_column;
4183
4184         switch (dev->raid_level) {
4185         case HPSA_RAID_0:
4186                 break; /* nothing special to do */
4187         case HPSA_RAID_1:
4188                 /* Handles load balance across RAID 1 members.
4189                  * (2-drive R1 and R10 with even # of drives.)
4190                  * Appropriate for SSDs, not optimal for HDDs
4191                  */
4192                 BUG_ON(le16_to_cpu(map->layout_map_count) != 2);
4193                 if (dev->offload_to_mirror)
4194                         map_index += le16_to_cpu(map->data_disks_per_row);
4195                 dev->offload_to_mirror = !dev->offload_to_mirror;
4196                 break;
4197         case HPSA_RAID_ADM:
4198                 /* Handles N-way mirrors  (R1-ADM)
4199                  * and R10 with # of drives divisible by 3.)
4200                  */
4201                 BUG_ON(le16_to_cpu(map->layout_map_count) != 3);
4202
4203                 offload_to_mirror = dev->offload_to_mirror;
4204                 raid_map_helper(map, offload_to_mirror,
4205                                 &map_index, &current_group);
4206                 /* set mirror group to use next time */
4207                 offload_to_mirror =
4208                         (offload_to_mirror >=
4209                         le16_to_cpu(map->layout_map_count) - 1)
4210                         ? 0 : offload_to_mirror + 1;
4211                 dev->offload_to_mirror = offload_to_mirror;
4212                 /* Avoid direct use of dev->offload_to_mirror within this
4213                  * function since multiple threads might simultaneously
4214                  * increment it beyond the range of dev->layout_map_count -1.
4215                  */
4216                 break;
4217         case HPSA_RAID_5:
4218         case HPSA_RAID_6:
4219                 if (le16_to_cpu(map->layout_map_count) <= 1)
4220                         break;
4221
4222                 /* Verify first and last block are in same RAID group */
4223                 r5or6_blocks_per_row =
4224                         le16_to_cpu(map->strip_size) *
4225                         le16_to_cpu(map->data_disks_per_row);
4226                 BUG_ON(r5or6_blocks_per_row == 0);
4227                 stripesize = r5or6_blocks_per_row *
4228                         le16_to_cpu(map->layout_map_count);
4229 #if BITS_PER_LONG == 32
4230                 tmpdiv = first_block;
4231                 first_group = do_div(tmpdiv, stripesize);
4232                 tmpdiv = first_group;
4233                 (void) do_div(tmpdiv, r5or6_blocks_per_row);
4234                 first_group = tmpdiv;
4235                 tmpdiv = last_block;
4236                 last_group = do_div(tmpdiv, stripesize);
4237                 tmpdiv = last_group;
4238                 (void) do_div(tmpdiv, r5or6_blocks_per_row);
4239                 last_group = tmpdiv;
4240 #else
4241                 first_group = (first_block % stripesize) / r5or6_blocks_per_row;
4242                 last_group = (last_block % stripesize) / r5or6_blocks_per_row;
4243 #endif
4244                 if (first_group != last_group)
4245                         return IO_ACCEL_INELIGIBLE;
4246
4247                 /* Verify request is in a single row of RAID 5/6 */
4248 #if BITS_PER_LONG == 32
4249                 tmpdiv = first_block;
4250                 (void) do_div(tmpdiv, stripesize);
4251                 first_row = r5or6_first_row = r0_first_row = tmpdiv;
4252                 tmpdiv = last_block;
4253                 (void) do_div(tmpdiv, stripesize);
4254                 r5or6_last_row = r0_last_row = tmpdiv;
4255 #else
4256                 first_row = r5or6_first_row = r0_first_row =
4257                                                 first_block / stripesize;
4258                 r5or6_last_row = r0_last_row = last_block / stripesize;
4259 #endif
4260                 if (r5or6_first_row != r5or6_last_row)
4261                         return IO_ACCEL_INELIGIBLE;
4262
4263
4264                 /* Verify request is in a single column */
4265 #if BITS_PER_LONG == 32
4266                 tmpdiv = first_block;
4267                 first_row_offset = do_div(tmpdiv, stripesize);
4268                 tmpdiv = first_row_offset;
4269                 first_row_offset = (u32) do_div(tmpdiv, r5or6_blocks_per_row);
4270                 r5or6_first_row_offset = first_row_offset;
4271                 tmpdiv = last_block;
4272                 r5or6_last_row_offset = do_div(tmpdiv, stripesize);
4273                 tmpdiv = r5or6_last_row_offset;
4274                 r5or6_last_row_offset = do_div(tmpdiv, r5or6_blocks_per_row);
4275                 tmpdiv = r5or6_first_row_offset;
4276                 (void) do_div(tmpdiv, map->strip_size);
4277                 first_column = r5or6_first_column = tmpdiv;
4278                 tmpdiv = r5or6_last_row_offset;
4279                 (void) do_div(tmpdiv, map->strip_size);
4280                 r5or6_last_column = tmpdiv;
4281 #else
4282                 first_row_offset = r5or6_first_row_offset =
4283                         (u32)((first_block % stripesize) %
4284                                                 r5or6_blocks_per_row);
4285
4286                 r5or6_last_row_offset =
4287                         (u32)((last_block % stripesize) %
4288                                                 r5or6_blocks_per_row);
4289
4290                 first_column = r5or6_first_column =
4291                         r5or6_first_row_offset / le16_to_cpu(map->strip_size);
4292                 r5or6_last_column =
4293                         r5or6_last_row_offset / le16_to_cpu(map->strip_size);
4294 #endif
4295                 if (r5or6_first_column != r5or6_last_column)
4296                         return IO_ACCEL_INELIGIBLE;
4297
4298                 /* Request is eligible */
4299                 map_row = ((u32)(first_row >> map->parity_rotation_shift)) %
4300                         le16_to_cpu(map->row_cnt);
4301
4302                 map_index = (first_group *
4303                         (le16_to_cpu(map->row_cnt) * total_disks_per_row)) +
4304                         (map_row * total_disks_per_row) + first_column;
4305                 break;
4306         default:
4307                 return IO_ACCEL_INELIGIBLE;
4308         }
4309
4310         if (unlikely(map_index >= RAID_MAP_MAX_ENTRIES))
4311                 return IO_ACCEL_INELIGIBLE;
4312
4313         c->phys_disk = dev->phys_disk[map_index];
4314
4315         disk_handle = dd[map_index].ioaccel_handle;
4316         disk_block = le64_to_cpu(map->disk_starting_blk) +
4317                         first_row * le16_to_cpu(map->strip_size) +
4318                         (first_row_offset - first_column *
4319                         le16_to_cpu(map->strip_size));
4320         disk_block_cnt = block_cnt;
4321
4322         /* handle differing logical/physical block sizes */
4323         if (map->phys_blk_shift) {
4324                 disk_block <<= map->phys_blk_shift;
4325                 disk_block_cnt <<= map->phys_blk_shift;
4326         }
4327         BUG_ON(disk_block_cnt > 0xffff);
4328
4329         /* build the new CDB for the physical disk I/O */
4330         if (disk_block > 0xffffffff) {
4331                 cdb[0] = is_write ? WRITE_16 : READ_16;
4332                 cdb[1] = 0;
4333                 cdb[2] = (u8) (disk_block >> 56);
4334                 cdb[3] = (u8) (disk_block >> 48);
4335                 cdb[4] = (u8) (disk_block >> 40);
4336                 cdb[5] = (u8) (disk_block >> 32);
4337                 cdb[6] = (u8) (disk_block >> 24);
4338                 cdb[7] = (u8) (disk_block >> 16);
4339                 cdb[8] = (u8) (disk_block >> 8);
4340                 cdb[9] = (u8) (disk_block);
4341                 cdb[10] = (u8) (disk_block_cnt >> 24);
4342                 cdb[11] = (u8) (disk_block_cnt >> 16);
4343                 cdb[12] = (u8) (disk_block_cnt >> 8);
4344                 cdb[13] = (u8) (disk_block_cnt);
4345                 cdb[14] = 0;
4346                 cdb[15] = 0;
4347                 cdb_len = 16;
4348         } else {
4349                 cdb[0] = is_write ? WRITE_10 : READ_10;
4350                 cdb[1] = 0;
4351                 cdb[2] = (u8) (disk_block >> 24);
4352                 cdb[3] = (u8) (disk_block >> 16);
4353                 cdb[4] = (u8) (disk_block >> 8);
4354                 cdb[5] = (u8) (disk_block);
4355                 cdb[6] = 0;
4356                 cdb[7] = (u8) (disk_block_cnt >> 8);
4357                 cdb[8] = (u8) (disk_block_cnt);
4358                 cdb[9] = 0;
4359                 cdb_len = 10;
4360         }
4361         return hpsa_scsi_ioaccel_queue_command(h, c, disk_handle, cdb, cdb_len,
4362                                                 dev->scsi3addr,
4363                                                 dev->phys_disk[map_index]);
4364 }
4365
4366 /*
4367  * Submit commands down the "normal" RAID stack path
4368  * All callers to hpsa_ciss_submit must check lockup_detected
4369  * beforehand, before (opt.) and after calling cmd_alloc
4370  */
4371 static int hpsa_ciss_submit(struct ctlr_info *h,
4372         struct CommandList *c, struct scsi_cmnd *cmd,
4373         unsigned char scsi3addr[])
4374 {
4375         cmd->host_scribble = (unsigned char *) c;
4376         c->cmd_type = CMD_SCSI;
4377         c->scsi_cmd = cmd;
4378         c->Header.ReplyQueue = 0;  /* unused in simple mode */
4379         memcpy(&c->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
4380         c->Header.tag = cpu_to_le64((c->cmdindex << DIRECT_LOOKUP_SHIFT));
4381
4382         /* Fill in the request block... */
4383
4384         c->Request.Timeout = 0;
4385         BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
4386         c->Request.CDBLen = cmd->cmd_len;
4387         memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
4388         switch (cmd->sc_data_direction) {
4389         case DMA_TO_DEVICE:
4390                 c->Request.type_attr_dir =
4391                         TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_WRITE);
4392                 break;
4393         case DMA_FROM_DEVICE:
4394                 c->Request.type_attr_dir =
4395                         TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_READ);
4396                 break;
4397         case DMA_NONE:
4398                 c->Request.type_attr_dir =
4399                         TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_NONE);
4400                 break;
4401         case DMA_BIDIRECTIONAL:
4402                 /* This can happen if a buggy application does a scsi passthru
4403                  * and sets both inlen and outlen to non-zero. ( see
4404                  * ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
4405                  */
4406
4407                 c->Request.type_attr_dir =
4408                         TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_RSVD);
4409                 /* This is technically wrong, and hpsa controllers should
4410                  * reject it with CMD_INVALID, which is the most correct
4411                  * response, but non-fibre backends appear to let it
4412                  * slide by, and give the same results as if this field
4413                  * were set correctly.  Either way is acceptable for
4414                  * our purposes here.
4415                  */
4416
4417                 break;
4418
4419         default:
4420                 dev_err(&h->pdev->dev, "unknown data direction: %d\n",
4421                         cmd->sc_data_direction);
4422                 BUG();
4423                 break;
4424         }
4425
4426         if (hpsa_scatter_gather(h, c, cmd) < 0) { /* Fill SG list */
4427                 cmd_free(h, c);
4428                 return SCSI_MLQUEUE_HOST_BUSY;
4429         }
4430         enqueue_cmd_and_start_io(h, c);
4431         /* the cmd'll come back via intr handler in complete_scsi_command()  */
4432         return 0;
4433 }
4434
4435 static void hpsa_cmd_init(struct ctlr_info *h, int index,
4436                                 struct CommandList *c)
4437 {
4438         dma_addr_t cmd_dma_handle, err_dma_handle;
4439
4440         /* Zero out all of commandlist except the last field, refcount */
4441         memset(c, 0, offsetof(struct CommandList, refcount));
4442         c->Header.tag = cpu_to_le64((u64) (index << DIRECT_LOOKUP_SHIFT));
4443         cmd_dma_handle = h->cmd_pool_dhandle + index * sizeof(*c);
4444         c->err_info = h->errinfo_pool + index;
4445         memset(c->err_info, 0, sizeof(*c->err_info));
4446         err_dma_handle = h->errinfo_pool_dhandle
4447             + index * sizeof(*c->err_info);
4448         c->cmdindex = index;
4449         c->busaddr = (u32) cmd_dma_handle;
4450         c->ErrDesc.Addr = cpu_to_le64((u64) err_dma_handle);
4451         c->ErrDesc.Len = cpu_to_le32((u32) sizeof(*c->err_info));
4452         c->h = h;
4453 }
4454
4455 static void hpsa_preinitialize_commands(struct ctlr_info *h)
4456 {
4457         int i;
4458
4459         for (i = 0; i < h->nr_cmds; i++) {
4460                 struct CommandList *c = h->cmd_pool + i;
4461
4462                 hpsa_cmd_init(h, i, c);
4463                 atomic_set(&c->refcount, 0);
4464         }
4465 }
4466
4467 static inline void hpsa_cmd_partial_init(struct ctlr_info *h, int index,
4468                                 struct CommandList *c)
4469 {
4470         dma_addr_t cmd_dma_handle = h->cmd_pool_dhandle + index * sizeof(*c);
4471
4472         memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
4473         memset(c->err_info, 0, sizeof(*c->err_info));
4474         c->busaddr = (u32) cmd_dma_handle;
4475 }
4476
4477 static int hpsa_ioaccel_submit(struct ctlr_info *h,
4478                 struct CommandList *c, struct scsi_cmnd *cmd,
4479                 unsigned char *scsi3addr)
4480 {
4481         struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
4482         int rc = IO_ACCEL_INELIGIBLE;
4483
4484         cmd->host_scribble = (unsigned char *) c;
4485
4486         if (dev->offload_enabled) {
4487                 hpsa_cmd_init(h, c->cmdindex, c);
4488                 c->cmd_type = CMD_SCSI;
4489                 c->scsi_cmd = cmd;
4490                 rc = hpsa_scsi_ioaccel_raid_map(h, c);
4491                 if (rc < 0)     /* scsi_dma_map failed. */
4492                         rc = SCSI_MLQUEUE_HOST_BUSY;
4493         } else if (dev->hba_ioaccel_enabled) {
4494                 hpsa_cmd_init(h, c->cmdindex, c);
4495                 c->cmd_type = CMD_SCSI;
4496                 c->scsi_cmd = cmd;
4497                 rc = hpsa_scsi_ioaccel_direct_map(h, c);
4498                 if (rc < 0)     /* scsi_dma_map failed. */
4499                         rc = SCSI_MLQUEUE_HOST_BUSY;
4500         }
4501         return rc;
4502 }
4503
4504 static void hpsa_command_resubmit_worker(struct work_struct *work)
4505 {
4506         struct scsi_cmnd *cmd;
4507         struct hpsa_scsi_dev_t *dev;
4508         struct CommandList *c = container_of(work, struct CommandList, work);
4509
4510         cmd = c->scsi_cmd;
4511         dev = cmd->device->hostdata;
4512         if (!dev) {
4513                 cmd->result = DID_NO_CONNECT << 16;
4514                 return hpsa_cmd_free_and_done(c->h, c, cmd);
4515         }
4516         if (c->cmd_type == CMD_IOACCEL2) {
4517                 struct ctlr_info *h = c->h;
4518                 struct io_accel2_cmd *c2 = &h->ioaccel2_cmd_pool[c->cmdindex];
4519                 int rc;
4520
4521                 if (c2->error_data.serv_response ==
4522                                 IOACCEL2_STATUS_SR_TASK_COMP_SET_FULL) {
4523                         rc = hpsa_ioaccel_submit(h, c, cmd, dev->scsi3addr);
4524                         if (rc == 0)
4525                                 return;
4526                         if (rc == SCSI_MLQUEUE_HOST_BUSY) {
4527                                 /*
4528                                  * If we get here, it means dma mapping failed.
4529                                  * Try again via scsi mid layer, which will
4530                                  * then get SCSI_MLQUEUE_HOST_BUSY.
4531                                  */
4532                                 cmd->result = DID_IMM_RETRY << 16;
4533                                 return hpsa_cmd_free_and_done(h, c, cmd);
4534                         }
4535                         /* else, fall thru and resubmit down CISS path */
4536                 }
4537         }
4538         hpsa_cmd_partial_init(c->h, c->cmdindex, c);
4539         if (hpsa_ciss_submit(c->h, c, cmd, dev->scsi3addr)) {
4540                 /*
4541                  * If we get here, it means dma mapping failed. Try
4542                  * again via scsi mid layer, which will then get
4543                  * SCSI_MLQUEUE_HOST_BUSY.
4544                  *
4545                  * hpsa_ciss_submit will have already freed c
4546                  * if it encountered a dma mapping failure.
4547                  */
4548                 cmd->result = DID_IMM_RETRY << 16;
4549                 cmd->scsi_done(cmd);
4550         }
4551 }
4552
4553 /* Running in struct Scsi_Host->host_lock less mode */
4554 static int hpsa_scsi_queue_command(struct Scsi_Host *sh, struct scsi_cmnd *cmd)
4555 {
4556         struct ctlr_info *h;
4557         struct hpsa_scsi_dev_t *dev;
4558         unsigned char scsi3addr[8];
4559         struct CommandList *c;
4560         int rc = 0;
4561
4562         /* Get the ptr to our adapter structure out of cmd->host. */
4563         h = sdev_to_hba(cmd->device);
4564         dev = cmd->device->hostdata;
4565         if (!dev) {
4566                 cmd->result = DID_NO_CONNECT << 16;
4567                 cmd->scsi_done(cmd);
4568                 return 0;
4569         }
4570         memcpy(scsi3addr, dev->scsi3addr, sizeof(scsi3addr));
4571
4572         if (unlikely(lockup_detected(h))) {
4573                 cmd->result = DID_NO_CONNECT << 16;
4574                 cmd->scsi_done(cmd);
4575                 return 0;
4576         }
4577         c = cmd_alloc(h);
4578
4579         if (unlikely(lockup_detected(h))) {
4580                 cmd->result = DID_NO_CONNECT << 16;
4581                 cmd_free(h, c);
4582                 cmd->scsi_done(cmd);
4583                 return 0;
4584         }
4585
4586         /*
4587          * Call alternate submit routine for I/O accelerated commands.
4588          * Retries always go down the normal I/O path.
4589          */
4590         if (likely(cmd->retries == 0 &&
4591                 cmd->request->cmd_type == REQ_TYPE_FS &&
4592                 h->acciopath_status)) {
4593                 rc = hpsa_ioaccel_submit(h, c, cmd, scsi3addr);
4594                 if (rc == 0)
4595                         return 0;
4596                 if (rc == SCSI_MLQUEUE_HOST_BUSY) {
4597                         cmd_free(h, c);
4598                         return SCSI_MLQUEUE_HOST_BUSY;
4599                 }
4600         }
4601         return hpsa_ciss_submit(h, c, cmd, scsi3addr);
4602 }
4603
4604 static void hpsa_scan_complete(struct ctlr_info *h)
4605 {
4606         unsigned long flags;
4607
4608         spin_lock_irqsave(&h->scan_lock, flags);
4609         h->scan_finished = 1;
4610         wake_up_all(&h->scan_wait_queue);
4611         spin_unlock_irqrestore(&h->scan_lock, flags);
4612 }
4613
4614 static void hpsa_scan_start(struct Scsi_Host *sh)
4615 {
4616         struct ctlr_info *h = shost_to_hba(sh);
4617         unsigned long flags;
4618
4619         /*
4620          * Don't let rescans be initiated on a controller known to be locked
4621          * up.  If the controller locks up *during* a rescan, that thread is
4622          * probably hosed, but at least we can prevent new rescan threads from
4623          * piling up on a locked up controller.
4624          */
4625         if (unlikely(lockup_detected(h)))
4626                 return hpsa_scan_complete(h);
4627
4628         /* wait until any scan already in progress is finished. */
4629         while (1) {
4630                 spin_lock_irqsave(&h->scan_lock, flags);
4631                 if (h->scan_finished)
4632                         break;
4633                 spin_unlock_irqrestore(&h->scan_lock, flags);
4634                 wait_event(h->scan_wait_queue, h->scan_finished);
4635                 /* Note: We don't need to worry about a race between this
4636                  * thread and driver unload because the midlayer will
4637                  * have incremented the reference count, so unload won't
4638                  * happen if we're in here.
4639                  */
4640         }
4641         h->scan_finished = 0; /* mark scan as in progress */
4642         spin_unlock_irqrestore(&h->scan_lock, flags);
4643
4644         if (unlikely(lockup_detected(h)))
4645                 return hpsa_scan_complete(h);
4646
4647         hpsa_update_scsi_devices(h, h->scsi_host->host_no);
4648
4649         hpsa_scan_complete(h);
4650 }
4651
4652 static int hpsa_change_queue_depth(struct scsi_device *sdev, int qdepth)
4653 {
4654         struct hpsa_scsi_dev_t *logical_drive = sdev->hostdata;
4655
4656         if (!logical_drive)
4657                 return -ENODEV;
4658
4659         if (qdepth < 1)
4660                 qdepth = 1;
4661         else if (qdepth > logical_drive->queue_depth)
4662                 qdepth = logical_drive->queue_depth;
4663
4664         return scsi_change_queue_depth(sdev, qdepth);
4665 }
4666
4667 static int hpsa_scan_finished(struct Scsi_Host *sh,
4668         unsigned long elapsed_time)
4669 {
4670         struct ctlr_info *h = shost_to_hba(sh);
4671         unsigned long flags;
4672         int finished;
4673
4674         spin_lock_irqsave(&h->scan_lock, flags);
4675         finished = h->scan_finished;
4676         spin_unlock_irqrestore(&h->scan_lock, flags);
4677         return finished;
4678 }
4679
4680 static void hpsa_unregister_scsi(struct ctlr_info *h)
4681 {
4682         /* we are being forcibly unloaded, and may not refuse. */
4683         scsi_remove_host(h->scsi_host);
4684         scsi_host_put(h->scsi_host);
4685         h->scsi_host = NULL;
4686 }
4687
4688 static int hpsa_register_scsi(struct ctlr_info *h)
4689 {
4690         struct Scsi_Host *sh;
4691         int error;
4692
4693         sh = scsi_host_alloc(&hpsa_driver_template, sizeof(h));
4694         if (sh == NULL)
4695                 goto fail;
4696
4697         sh->io_port = 0;
4698         sh->n_io_port = 0;
4699         sh->this_id = -1;
4700         sh->max_channel = 3;
4701         sh->max_cmd_len = MAX_COMMAND_SIZE;
4702         sh->max_lun = HPSA_MAX_LUN;
4703         sh->max_id = HPSA_MAX_LUN;
4704         sh->can_queue = h->nr_cmds - HPSA_NRESERVED_CMDS;
4705         sh->cmd_per_lun = sh->can_queue;
4706         sh->sg_tablesize = h->maxsgentries;
4707         h->scsi_host = sh;
4708         sh->hostdata[0] = (unsigned long) h;
4709         sh->irq = h->intr[h->intr_mode];
4710         sh->unique_id = sh->irq;
4711         error = scsi_add_host(sh, &h->pdev->dev);
4712         if (error)
4713                 goto fail_host_put;
4714         scsi_scan_host(sh);
4715         return 0;
4716
4717  fail_host_put:
4718         dev_err(&h->pdev->dev, "%s: scsi_add_host"
4719                 " failed for controller %d\n", __func__, h->ctlr);
4720         scsi_host_put(sh);
4721         return error;
4722  fail:
4723         dev_err(&h->pdev->dev, "%s: scsi_host_alloc"
4724                 " failed for controller %d\n", __func__, h->ctlr);
4725         return -ENOMEM;
4726 }
4727
4728 static int wait_for_device_to_become_ready(struct ctlr_info *h,
4729         unsigned char lunaddr[])
4730 {
4731         int rc;
4732         int count = 0;
4733         int waittime = 1; /* seconds */
4734         struct CommandList *c;
4735
4736         c = cmd_alloc(h);
4737
4738         /* Send test unit ready until device ready, or give up. */
4739         while (count < HPSA_TUR_RETRY_LIMIT) {
4740
4741                 /* Wait for a bit.  do this first, because if we send
4742                  * the TUR right away, the reset will just abort it.
4743                  */
4744                 msleep(1000 * waittime);
4745                 count++;
4746                 rc = 0; /* Device ready. */
4747
4748                 /* Increase wait time with each try, up to a point. */
4749                 if (waittime < HPSA_MAX_WAIT_INTERVAL_SECS)
4750                         waittime = waittime * 2;
4751
4752                 /* Send the Test Unit Ready, fill_cmd can't fail, no mapping */
4753                 (void) fill_cmd(c, TEST_UNIT_READY, h,
4754                                 NULL, 0, 0, lunaddr, TYPE_CMD);
4755                 rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE,
4756                                                 NO_TIMEOUT);
4757                 if (rc)
4758                         goto do_it_again;
4759                 /* no unmap needed here because no data xfer. */
4760
4761                 if (c->err_info->CommandStatus == CMD_SUCCESS)
4762                         break;
4763
4764                 if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
4765                         c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION &&
4766                         (c->err_info->SenseInfo[2] == NO_SENSE ||
4767                         c->err_info->SenseInfo[2] == UNIT_ATTENTION))
4768                         break;
4769 do_it_again:
4770                 dev_warn(&h->pdev->dev, "waiting %d secs "
4771                         "for device to become ready.\n", waittime);
4772                 rc = 1; /* device not ready. */
4773         }
4774
4775         if (rc)
4776                 dev_warn(&h->pdev->dev, "giving up on device.\n");
4777         else
4778                 dev_warn(&h->pdev->dev, "device is ready.\n");
4779
4780         cmd_free(h, c);
4781         return rc;
4782 }
4783
4784 /* Need at least one of these error handlers to keep ../scsi/hosts.c from
4785  * complaining.  Doing a host- or bus-reset can't do anything good here.
4786  */
4787 static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
4788 {
4789         int rc;
4790         struct ctlr_info *h;
4791         struct hpsa_scsi_dev_t *dev;
4792
4793         /* find the controller to which the command to be aborted was sent */
4794         h = sdev_to_hba(scsicmd->device);
4795         if (h == NULL) /* paranoia */
4796                 return FAILED;
4797
4798         if (lockup_detected(h))
4799                 return FAILED;
4800
4801         dev = scsicmd->device->hostdata;
4802         if (!dev) {
4803                 dev_err(&h->pdev->dev, "hpsa_eh_device_reset_handler: "
4804                         "device lookup failed.\n");
4805                 return FAILED;
4806         }
4807
4808         /* if controller locked up, we can guarantee command won't complete */
4809         if (lockup_detected(h)) {
4810                 dev_warn(&h->pdev->dev,
4811                         "scsi %d:%d:%d:%d RESET FAILED, lockup detected\n",
4812                         h->scsi_host->host_no, dev->bus, dev->target,
4813                         dev->lun);
4814                 return FAILED;
4815         }
4816
4817         /* this reset request might be the result of a lockup; check */
4818         if (detect_controller_lockup(h)) {
4819                 dev_warn(&h->pdev->dev,
4820                          "scsi %d:%d:%d:%d RESET FAILED, new lockup detected\n",
4821                          h->scsi_host->host_no, dev->bus, dev->target,
4822                          dev->lun);
4823                 return FAILED;
4824         }
4825
4826         hpsa_show_dev_msg(KERN_WARNING, h, dev, "resetting");
4827
4828         /* send a reset to the SCSI LUN which the command was sent to */
4829         rc = hpsa_send_reset(h, dev->scsi3addr, HPSA_RESET_TYPE_LUN,
4830                              DEFAULT_REPLY_QUEUE);
4831         if (rc == 0 && wait_for_device_to_become_ready(h, dev->scsi3addr) == 0)
4832                 return SUCCESS;
4833
4834         dev_warn(&h->pdev->dev,
4835                 "scsi %d:%d:%d:%d reset failed\n",
4836                 h->scsi_host->host_no, dev->bus, dev->target, dev->lun);
4837         return FAILED;
4838 }
4839
4840 static void swizzle_abort_tag(u8 *tag)
4841 {
4842         u8 original_tag[8];
4843
4844         memcpy(original_tag, tag, 8);
4845         tag[0] = original_tag[3];
4846         tag[1] = original_tag[2];
4847         tag[2] = original_tag[1];
4848         tag[3] = original_tag[0];
4849         tag[4] = original_tag[7];
4850         tag[5] = original_tag[6];
4851         tag[6] = original_tag[5];
4852         tag[7] = original_tag[4];
4853 }
4854
4855 static void hpsa_get_tag(struct ctlr_info *h,
4856         struct CommandList *c, __le32 *taglower, __le32 *tagupper)
4857 {
4858         u64 tag;
4859         if (c->cmd_type == CMD_IOACCEL1) {
4860                 struct io_accel1_cmd *cm1 = (struct io_accel1_cmd *)
4861                         &h->ioaccel_cmd_pool[c->cmdindex];
4862                 tag = le64_to_cpu(cm1->tag);
4863                 *tagupper = cpu_to_le32(tag >> 32);
4864                 *taglower = cpu_to_le32(tag);
4865                 return;
4866         }
4867         if (c->cmd_type == CMD_IOACCEL2) {
4868                 struct io_accel2_cmd *cm2 = (struct io_accel2_cmd *)
4869                         &h->ioaccel2_cmd_pool[c->cmdindex];
4870                 /* upper tag not used in ioaccel2 mode */
4871                 memset(tagupper, 0, sizeof(*tagupper));
4872                 *taglower = cm2->Tag;
4873                 return;
4874         }
4875         tag = le64_to_cpu(c->Header.tag);
4876         *tagupper = cpu_to_le32(tag >> 32);
4877         *taglower = cpu_to_le32(tag);
4878 }
4879
4880 static int hpsa_send_abort(struct ctlr_info *h, unsigned char *scsi3addr,
4881         struct CommandList *abort, int reply_queue)
4882 {
4883         int rc = IO_OK;
4884         struct CommandList *c;
4885         struct ErrorInfo *ei;
4886         __le32 tagupper, taglower;
4887
4888         c = cmd_alloc(h);
4889
4890         /* fill_cmd can't fail here, no buffer to map */
4891         (void) fill_cmd(c, HPSA_ABORT_MSG, h, &abort->Header.tag,
4892                 0, 0, scsi3addr, TYPE_MSG);
4893         if (h->needs_abort_tags_swizzled)
4894                 swizzle_abort_tag(&c->Request.CDB[4]);
4895         (void) hpsa_scsi_do_simple_cmd(h, c, reply_queue, NO_TIMEOUT);
4896         hpsa_get_tag(h, abort, &taglower, &tagupper);
4897         dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: do_simple_cmd(abort) completed.\n",
4898                 __func__, tagupper, taglower);
4899         /* no unmap needed here because no data xfer. */
4900
4901         ei = c->err_info;
4902         switch (ei->CommandStatus) {
4903         case CMD_SUCCESS:
4904                 break;
4905         case CMD_TMF_STATUS:
4906                 rc = hpsa_evaluate_tmf_status(h, c);
4907                 break;
4908         case CMD_UNABORTABLE: /* Very common, don't make noise. */
4909                 rc = -1;
4910                 break;
4911         default:
4912                 dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: interpreting error.\n",
4913                         __func__, tagupper, taglower);
4914                 hpsa_scsi_interpret_error(h, c);
4915                 rc = -1;
4916                 break;
4917         }
4918         cmd_free(h, c);
4919         dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: Finished.\n",
4920                 __func__, tagupper, taglower);
4921         return rc;
4922 }
4923
4924 static void setup_ioaccel2_abort_cmd(struct CommandList *c, struct ctlr_info *h,
4925         struct CommandList *command_to_abort, int reply_queue)
4926 {
4927         struct io_accel2_cmd *c2 = &h->ioaccel2_cmd_pool[c->cmdindex];
4928         struct hpsa_tmf_struct *ac = (struct hpsa_tmf_struct *) c2;
4929         struct io_accel2_cmd *c2a =
4930                 &h->ioaccel2_cmd_pool[command_to_abort->cmdindex];
4931         struct scsi_cmnd *scmd =
4932                 (struct scsi_cmnd *) command_to_abort->scsi_cmd;
4933         struct hpsa_scsi_dev_t *dev = scmd->device->hostdata;
4934
4935         /*
4936          * We're overlaying struct hpsa_tmf_struct on top of something which
4937          * was allocated as a struct io_accel2_cmd, so we better be sure it
4938          * actually fits, and doesn't overrun the error info space.
4939          */
4940         BUILD_BUG_ON(sizeof(struct hpsa_tmf_struct) >
4941                         sizeof(struct io_accel2_cmd));
4942         BUG_ON(offsetof(struct io_accel2_cmd, error_data) <
4943                         offsetof(struct hpsa_tmf_struct, error_len) +
4944                                 sizeof(ac->error_len));
4945
4946         c->cmd_type = IOACCEL2_TMF;
4947         /* Adjust the DMA address to point to the accelerated command buffer */
4948         c->busaddr = (u32) h->ioaccel2_cmd_pool_dhandle +
4949                                 (c->cmdindex * sizeof(struct io_accel2_cmd));
4950         BUG_ON(c->busaddr & 0x0000007F);
4951
4952         memset(ac, 0, sizeof(*c2)); /* yes this is correct */
4953         ac->iu_type = IOACCEL2_IU_TMF_TYPE;
4954         ac->reply_queue = reply_queue;
4955         ac->tmf = IOACCEL2_TMF_ABORT;
4956         ac->it_nexus = cpu_to_le32(dev->ioaccel_handle);
4957         memset(ac->lun_id, 0, sizeof(ac->lun_id));
4958         ac->tag = cpu_to_le64(c->cmdindex << DIRECT_LOOKUP_SHIFT);
4959         ac->abort_tag = cpu_to_le64(le32_to_cpu(c2a->Tag));
4960         ac->error_ptr = cpu_to_le64(c->busaddr +
4961                         offsetof(struct io_accel2_cmd, error_data));
4962         ac->error_len = cpu_to_le32(sizeof(c2->error_data));
4963 }
4964
4965 /* ioaccel2 path firmware cannot handle abort task requests.
4966  * Change abort requests to physical target reset, and send to the
4967  * address of the physical disk used for the ioaccel 2 command.
4968  * Return 0 on success (IO_OK)
4969  *       -1 on failure
4970  */
4971
4972 static int hpsa_send_reset_as_abort_ioaccel2(struct ctlr_info *h,
4973         unsigned char *scsi3addr, struct CommandList *abort, int reply_queue)
4974 {
4975         int rc = IO_OK;
4976         struct scsi_cmnd *scmd; /* scsi command within request being aborted */
4977         struct hpsa_scsi_dev_t *dev; /* device to which scsi cmd was sent */
4978         unsigned char phys_scsi3addr[8]; /* addr of phys disk with volume */
4979         unsigned char *psa = &phys_scsi3addr[0];
4980
4981         /* Get a pointer to the hpsa logical device. */
4982         scmd = abort->scsi_cmd;
4983         dev = (struct hpsa_scsi_dev_t *)(scmd->device->hostdata);
4984         if (dev == NULL) {
4985                 dev_warn(&h->pdev->dev,
4986                         "Cannot abort: no device pointer for command.\n");
4987                         return -1; /* not abortable */
4988         }
4989
4990         if (h->raid_offload_debug > 0)
4991                 dev_info(&h->pdev->dev,
4992                         "scsi %d:%d:%d:%d %s scsi3addr 0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
4993                         h->scsi_host->host_no, dev->bus, dev->target, dev->lun,
4994                         "Reset as abort",
4995                         scsi3addr[0], scsi3addr[1], scsi3addr[2], scsi3addr[3],
4996                         scsi3addr[4], scsi3addr[5], scsi3addr[6], scsi3addr[7]);
4997
4998         if (!dev->offload_enabled) {
4999                 dev_warn(&h->pdev->dev,
5000                         "Can't abort: device is not operating in HP SSD Smart Path mode.\n");
5001                 return -1; /* not abortable */
5002         }
5003
5004         /* Incoming scsi3addr is logical addr. We need physical disk addr. */
5005         if (!hpsa_get_pdisk_of_ioaccel2(h, abort, psa)) {
5006                 dev_warn(&h->pdev->dev, "Can't abort: Failed lookup of physical address.\n");
5007                 return -1; /* not abortable */
5008         }
5009
5010         /* send the reset */
5011         if (h->raid_offload_debug > 0)
5012                 dev_info(&h->pdev->dev,
5013                         "Reset as abort: Resetting physical device at scsi3addr 0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
5014                         psa[0], psa[1], psa[2], psa[3],
5015                         psa[4], psa[5], psa[6], psa[7]);
5016         rc = hpsa_send_reset(h, psa, HPSA_RESET_TYPE_TARGET, reply_queue);
5017         if (rc != 0) {
5018                 dev_warn(&h->pdev->dev,
5019                         "Reset as abort: Failed on physical device at scsi3addr 0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
5020                         psa[0], psa[1], psa[2], psa[3],
5021                         psa[4], psa[5], psa[6], psa[7]);
5022                 return rc; /* failed to reset */
5023         }
5024
5025         /* wait for device to recover */
5026         if (wait_for_device_to_become_ready(h, psa) != 0) {
5027                 dev_warn(&h->pdev->dev,
5028                         "Reset as abort: Failed: Device never recovered from reset: 0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
5029                         psa[0], psa[1], psa[2], psa[3],
5030                         psa[4], psa[5], psa[6], psa[7]);
5031                 return -1;  /* failed to recover */
5032         }
5033
5034         /* device recovered */
5035         dev_info(&h->pdev->dev,
5036                 "Reset as abort: Device recovered from reset: scsi3addr 0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
5037                 psa[0], psa[1], psa[2], psa[3],
5038                 psa[4], psa[5], psa[6], psa[7]);
5039
5040         return rc; /* success */
5041 }
5042
5043 static int hpsa_send_abort_ioaccel2(struct ctlr_info *h,
5044         struct CommandList *abort, int reply_queue)
5045 {
5046         int rc = IO_OK;
5047         struct CommandList *c;
5048         __le32 taglower, tagupper;
5049         struct hpsa_scsi_dev_t *dev;
5050         struct io_accel2_cmd *c2;
5051
5052         dev = abort->scsi_cmd->device->hostdata;
5053         if (!dev->offload_enabled && !dev->hba_ioaccel_enabled)
5054                 return -1;
5055
5056         c = cmd_alloc(h);
5057         setup_ioaccel2_abort_cmd(c, h, abort, reply_queue);
5058         c2 = &h->ioaccel2_cmd_pool[c->cmdindex];
5059         (void) hpsa_scsi_do_simple_cmd(h, c, reply_queue, NO_TIMEOUT);
5060         hpsa_get_tag(h, abort, &taglower, &tagupper);
5061         dev_dbg(&h->pdev->dev,
5062                 "%s: Tag:0x%08x:%08x: do_simple_cmd(ioaccel2 abort) completed.\n",
5063                 __func__, tagupper, taglower);
5064         /* no unmap needed here because no data xfer. */
5065
5066         dev_dbg(&h->pdev->dev,
5067                 "%s: Tag:0x%08x:%08x: abort service response = 0x%02x.\n",
5068                 __func__, tagupper, taglower, c2->error_data.serv_response);
5069         switch (c2->error_data.serv_response) {
5070         case IOACCEL2_SERV_RESPONSE_TMF_COMPLETE:
5071         case IOACCEL2_SERV_RESPONSE_TMF_SUCCESS:
5072                 rc = 0;
5073                 break;
5074         case IOACCEL2_SERV_RESPONSE_TMF_REJECTED:
5075         case IOACCEL2_SERV_RESPONSE_FAILURE:
5076         case IOACCEL2_SERV_RESPONSE_TMF_WRONG_LUN:
5077                 rc = -1;
5078                 break;
5079         default:
5080                 dev_warn(&h->pdev->dev,
5081                         "%s: Tag:0x%08x:%08x: unknown abort service response 0x%02x\n",
5082                         __func__, tagupper, taglower,
5083                         c2->error_data.serv_response);
5084                 rc = -1;
5085         }
5086         cmd_free(h, c);
5087         dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: Finished.\n", __func__,
5088                 tagupper, taglower);
5089         return rc;
5090 }
5091
5092 static int hpsa_send_abort_both_ways(struct ctlr_info *h,
5093         unsigned char *scsi3addr, struct CommandList *abort, int reply_queue)
5094 {
5095         /*
5096          * ioccelerator mode 2 commands should be aborted via the
5097          * accelerated path, since RAID path is unaware of these commands,
5098          * but not all underlying firmware can handle abort TMF.
5099          * Change abort to physical device reset when abort TMF is unsupported.
5100          */
5101         if (abort->cmd_type == CMD_IOACCEL2) {
5102                 if (HPSATMF_IOACCEL_ENABLED & h->TMFSupportFlags)
5103                         return hpsa_send_abort_ioaccel2(h, abort,
5104                                                 reply_queue);
5105                 else
5106                         return hpsa_send_reset_as_abort_ioaccel2(h, scsi3addr,
5107                                                         abort, reply_queue);
5108         }
5109         return hpsa_send_abort(h, scsi3addr, abort, reply_queue);
5110 }
5111
5112 /* Find out which reply queue a command was meant to return on */
5113 static int hpsa_extract_reply_queue(struct ctlr_info *h,
5114                                         struct CommandList *c)
5115 {
5116         if (c->cmd_type == CMD_IOACCEL2)
5117                 return h->ioaccel2_cmd_pool[c->cmdindex].reply_queue;
5118         return c->Header.ReplyQueue;
5119 }
5120
5121 /*
5122  * Limit concurrency of abort commands to prevent
5123  * over-subscription of commands
5124  */
5125 static inline int wait_for_available_abort_cmd(struct ctlr_info *h)
5126 {
5127 #define ABORT_CMD_WAIT_MSECS 5000
5128         return !wait_event_timeout(h->abort_cmd_wait_queue,
5129                         atomic_dec_if_positive(&h->abort_cmds_available) >= 0,
5130                         msecs_to_jiffies(ABORT_CMD_WAIT_MSECS));
5131 }
5132
5133 /* Send an abort for the specified command.
5134  *      If the device and controller support it,
5135  *              send a task abort request.
5136  */
5137 static int hpsa_eh_abort_handler(struct scsi_cmnd *sc)
5138 {
5139
5140         int i, rc;
5141         struct ctlr_info *h;
5142         struct hpsa_scsi_dev_t *dev;
5143         struct CommandList *abort; /* pointer to command to be aborted */
5144         struct scsi_cmnd *as;   /* ptr to scsi cmd inside aborted command. */
5145         char msg[256];          /* For debug messaging. */
5146         int ml = 0;
5147         __le32 tagupper, taglower;
5148         int refcount, reply_queue;
5149
5150         if (sc == NULL)
5151                 return FAILED;
5152
5153         if (sc->device == NULL)
5154                 return FAILED;
5155
5156         /* Find the controller of the command to be aborted */
5157         h = sdev_to_hba(sc->device);
5158         if (h == NULL)
5159                 return FAILED;
5160
5161         /* Find the device of the command to be aborted */
5162         dev = sc->device->hostdata;
5163         if (!dev) {
5164                 dev_err(&h->pdev->dev, "%s FAILED, Device lookup failed.\n",
5165                                 msg);
5166                 return FAILED;
5167         }
5168
5169         /* If controller locked up, we can guarantee command won't complete */
5170         if (lockup_detected(h)) {
5171                 hpsa_show_dev_msg(KERN_WARNING, h, dev,
5172                                         "ABORT FAILED, lockup detected");
5173                 return FAILED;
5174         }
5175
5176         /* This is a good time to check if controller lockup has occurred */
5177         if (detect_controller_lockup(h)) {
5178                 hpsa_show_dev_msg(KERN_WARNING, h, dev,
5179                                         "ABORT FAILED, new lockup detected");
5180                 return FAILED;
5181         }
5182
5183         /* Check that controller supports some kind of task abort */
5184         if (!(HPSATMF_PHYS_TASK_ABORT & h->TMFSupportFlags) &&
5185                 !(HPSATMF_LOG_TASK_ABORT & h->TMFSupportFlags))
5186                 return FAILED;
5187
5188         memset(msg, 0, sizeof(msg));
5189         ml += sprintf(msg+ml, "scsi %d:%d:%d:%llu %s %p",
5190                 h->scsi_host->host_no, sc->device->channel,
5191                 sc->device->id, sc->device->lun,
5192                 "Aborting command", sc);
5193
5194         /* Get SCSI command to be aborted */
5195         abort = (struct CommandList *) sc->host_scribble;
5196         if (abort == NULL) {
5197                 /* This can happen if the command already completed. */
5198                 return SUCCESS;
5199         }
5200         refcount = atomic_inc_return(&abort->refcount);
5201         if (refcount == 1) { /* Command is done already. */
5202                 cmd_free(h, abort);
5203                 return SUCCESS;
5204         }
5205
5206         /* Don't bother trying the abort if we know it won't work. */
5207         if (abort->cmd_type != CMD_IOACCEL2 &&
5208                 abort->cmd_type != CMD_IOACCEL1 && !dev->supports_aborts) {
5209                 cmd_free(h, abort);
5210                 return FAILED;
5211         }
5212
5213         hpsa_get_tag(h, abort, &taglower, &tagupper);
5214         reply_queue = hpsa_extract_reply_queue(h, abort);
5215         ml += sprintf(msg+ml, "Tag:0x%08x:%08x ", tagupper, taglower);
5216         as  = abort->scsi_cmd;
5217         if (as != NULL)
5218                 ml += sprintf(msg+ml,
5219                         "CDBLen: %d CDB: 0x%02x%02x... SN: 0x%lx ",
5220                         as->cmd_len, as->cmnd[0], as->cmnd[1],
5221                         as->serial_number);
5222         dev_warn(&h->pdev->dev, "%s BEING SENT\n", msg);
5223         hpsa_show_dev_msg(KERN_WARNING, h, dev, "Aborting command");
5224
5225         /*
5226          * Command is in flight, or possibly already completed
5227          * by the firmware (but not to the scsi mid layer) but we can't
5228          * distinguish which.  Send the abort down.
5229          */
5230         if (wait_for_available_abort_cmd(h)) {
5231                 dev_warn(&h->pdev->dev,
5232                         "%s FAILED, timeout waiting for an abort command to become available.\n",
5233                         msg);
5234                 cmd_free(h, abort);
5235                 return FAILED;
5236         }
5237         rc = hpsa_send_abort_both_ways(h, dev->scsi3addr, abort, reply_queue);
5238         atomic_inc(&h->abort_cmds_available);
5239         wake_up_all(&h->abort_cmd_wait_queue);
5240         if (rc != 0) {
5241                 dev_warn(&h->pdev->dev, "%s SENT, FAILED\n", msg);
5242                 hpsa_show_dev_msg(KERN_WARNING, h, dev,
5243                                 "FAILED to abort command");
5244                 cmd_free(h, abort);
5245                 return FAILED;
5246         }
5247         dev_info(&h->pdev->dev, "%s SENT, SUCCESS\n", msg);
5248
5249         /*
5250          * If the abort(s) above completed and actually aborted the
5251          * command, then the command to be aborted should already be
5252          * completed.  If not, wait around a bit more to see if they
5253          * manage to complete normally.
5254          */
5255 #define ABORT_COMPLETE_WAIT_SECS 30
5256         for (i = 0; i < ABORT_COMPLETE_WAIT_SECS * 10; i++) {
5257                 refcount = atomic_read(&abort->refcount);
5258                 if (refcount < 2) {
5259                         cmd_free(h, abort);
5260                         return SUCCESS;
5261                 } else {
5262                         msleep(100);
5263                 }
5264         }
5265         dev_warn(&h->pdev->dev, "%s FAILED. Aborted command has not completed after %d seconds.\n",
5266                 msg, ABORT_COMPLETE_WAIT_SECS);
5267         cmd_free(h, abort);
5268         return FAILED;
5269 }
5270
5271 /*
5272  * For operations that cannot sleep, a command block is allocated at init,
5273  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
5274  * which ones are free or in use.  Lock must be held when calling this.
5275  * cmd_free() is the complement.
5276  * This function never gives up and returns NULL.  If it hangs,
5277  * another thread must call cmd_free() to free some tags.
5278  */
5279
5280 static struct CommandList *cmd_alloc(struct ctlr_info *h)
5281 {
5282         struct CommandList *c;
5283         int refcount, i;
5284         unsigned long offset;
5285
5286         /*
5287          * There is some *extremely* small but non-zero chance that that
5288          * multiple threads could get in here, and one thread could
5289          * be scanning through the list of bits looking for a free
5290          * one, but the free ones are always behind him, and other
5291          * threads sneak in behind him and eat them before he can
5292          * get to them, so that while there is always a free one, a
5293          * very unlucky thread might be starved anyway, never able to
5294          * beat the other threads.  In reality, this happens so
5295          * infrequently as to be indistinguishable from never.
5296          */
5297
5298         offset = h->last_allocation; /* benignly racy */
5299         for (;;) {
5300                 i = find_next_zero_bit(h->cmd_pool_bits, h->nr_cmds, offset);
5301                 if (unlikely(i == h->nr_cmds)) {
5302                         offset = 0;
5303                         continue;
5304                 }
5305                 c = h->cmd_pool + i;
5306                 refcount = atomic_inc_return(&c->refcount);
5307                 if (unlikely(refcount > 1)) {
5308                         cmd_free(h, c); /* already in use */
5309                         offset = (i + 1) % h->nr_cmds;
5310                         continue;
5311                 }
5312                 set_bit(i & (BITS_PER_LONG - 1),
5313                         h->cmd_pool_bits + (i / BITS_PER_LONG));
5314                 break; /* it's ours now. */
5315         }
5316         h->last_allocation = i; /* benignly racy */
5317         hpsa_cmd_partial_init(h, i, c);
5318         return c;
5319 }
5320
5321 static void cmd_free(struct ctlr_info *h, struct CommandList *c)
5322 {
5323         if (atomic_dec_and_test(&c->refcount)) {
5324                 int i;
5325
5326                 i = c - h->cmd_pool;
5327                 clear_bit(i & (BITS_PER_LONG - 1),
5328                           h->cmd_pool_bits + (i / BITS_PER_LONG));
5329         }
5330 }
5331
5332 #ifdef CONFIG_COMPAT
5333
5334 static int hpsa_ioctl32_passthru(struct scsi_device *dev, int cmd,
5335         void __user *arg)
5336 {
5337         IOCTL32_Command_struct __user *arg32 =
5338             (IOCTL32_Command_struct __user *) arg;
5339         IOCTL_Command_struct arg64;
5340         IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
5341         int err;
5342         u32 cp;
5343
5344         memset(&arg64, 0, sizeof(arg64));
5345         err = 0;
5346         err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
5347                            sizeof(arg64.LUN_info));
5348         err |= copy_from_user(&arg64.Request, &arg32->Request,
5349                            sizeof(arg64.Request));
5350         err |= copy_from_user(&arg64.error_info, &arg32->error_info,
5351                            sizeof(arg64.error_info));
5352         err |= get_user(arg64.buf_size, &arg32->buf_size);
5353         err |= get_user(cp, &arg32->buf);
5354         arg64.buf = compat_ptr(cp);
5355         err |= copy_to_user(p, &arg64, sizeof(arg64));
5356
5357         if (err)
5358                 return -EFAULT;
5359
5360         err = hpsa_ioctl(dev, CCISS_PASSTHRU, p);
5361         if (err)
5362                 return err;
5363         err |= copy_in_user(&arg32->error_info, &p->error_info,
5364                          sizeof(arg32->error_info));
5365         if (err)
5366                 return -EFAULT;
5367         return err;
5368 }
5369
5370 static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
5371         int cmd, void __user *arg)
5372 {
5373         BIG_IOCTL32_Command_struct __user *arg32 =
5374             (BIG_IOCTL32_Command_struct __user *) arg;
5375         BIG_IOCTL_Command_struct arg64;
5376         BIG_IOCTL_Command_struct __user *p =
5377             compat_alloc_user_space(sizeof(arg64));
5378         int err;
5379         u32 cp;
5380
5381         memset(&arg64, 0, sizeof(arg64));
5382         err = 0;
5383         err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
5384                            sizeof(arg64.LUN_info));
5385         err |= copy_from_user(&arg64.Request, &arg32->Request,
5386                            sizeof(arg64.Request));
5387         err |= copy_from_user(&arg64.error_info, &arg32->error_info,
5388                            sizeof(arg64.error_info));
5389         err |= get_user(arg64.buf_size, &arg32->buf_size);
5390         err |= get_user(arg64.malloc_size, &arg32->malloc_size);
5391         err |= get_user(cp, &arg32->buf);
5392         arg64.buf = compat_ptr(cp);
5393         err |= copy_to_user(p, &arg64, sizeof(arg64));
5394
5395         if (err)
5396                 return -EFAULT;
5397
5398         err = hpsa_ioctl(dev, CCISS_BIG_PASSTHRU, p);
5399         if (err)
5400                 return err;
5401         err |= copy_in_user(&arg32->error_info, &p->error_info,
5402                          sizeof(arg32->error_info));
5403         if (err)
5404                 return -EFAULT;
5405         return err;
5406 }
5407
5408 static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void __user *arg)
5409 {
5410         switch (cmd) {
5411         case CCISS_GETPCIINFO:
5412         case CCISS_GETINTINFO:
5413         case CCISS_SETINTINFO:
5414         case CCISS_GETNODENAME:
5415         case CCISS_SETNODENAME:
5416         case CCISS_GETHEARTBEAT:
5417         case CCISS_GETBUSTYPES:
5418         case CCISS_GETFIRMVER:
5419         case CCISS_GETDRIVVER:
5420         case CCISS_REVALIDVOLS:
5421         case CCISS_DEREGDISK:
5422         case CCISS_REGNEWDISK:
5423         case CCISS_REGNEWD:
5424         case CCISS_RESCANDISK:
5425         case CCISS_GETLUNINFO:
5426                 return hpsa_ioctl(dev, cmd, arg);
5427
5428         case CCISS_PASSTHRU32:
5429                 return hpsa_ioctl32_passthru(dev, cmd, arg);
5430         case CCISS_BIG_PASSTHRU32:
5431                 return hpsa_ioctl32_big_passthru(dev, cmd, arg);
5432
5433         default:
5434                 return -ENOIOCTLCMD;
5435         }
5436 }
5437 #endif
5438
5439 static int hpsa_getpciinfo_ioctl(struct ctlr_info *h, void __user *argp)
5440 {
5441         struct hpsa_pci_info pciinfo;
5442
5443         if (!argp)
5444                 return -EINVAL;
5445         pciinfo.domain = pci_domain_nr(h->pdev->bus);
5446         pciinfo.bus = h->pdev->bus->number;
5447         pciinfo.dev_fn = h->pdev->devfn;
5448         pciinfo.board_id = h->board_id;
5449         if (copy_to_user(argp, &pciinfo, sizeof(pciinfo)))
5450                 return -EFAULT;
5451         return 0;
5452 }
5453
5454 static int hpsa_getdrivver_ioctl(struct ctlr_info *h, void __user *argp)
5455 {
5456         DriverVer_type DriverVer;
5457         unsigned char vmaj, vmin, vsubmin;
5458         int rc;
5459
5460         rc = sscanf(HPSA_DRIVER_VERSION, "%hhu.%hhu.%hhu",
5461                 &vmaj, &vmin, &vsubmin);
5462         if (rc != 3) {
5463                 dev_info(&h->pdev->dev, "driver version string '%s' "
5464                         "unrecognized.", HPSA_DRIVER_VERSION);
5465                 vmaj = 0;
5466                 vmin = 0;
5467                 vsubmin = 0;
5468         }
5469         DriverVer = (vmaj << 16) | (vmin << 8) | vsubmin;
5470         if (!argp)
5471                 return -EINVAL;
5472         if (copy_to_user(argp, &DriverVer, sizeof(DriverVer_type)))
5473                 return -EFAULT;
5474         return 0;
5475 }
5476
5477 static int hpsa_passthru_ioctl(struct ctlr_info *h, void __user *argp)
5478 {
5479         IOCTL_Command_struct iocommand;
5480         struct CommandList *c;
5481         char *buff = NULL;
5482         u64 temp64;
5483         int rc = 0;
5484
5485         if (!argp)
5486                 return -EINVAL;
5487         if (!capable(CAP_SYS_RAWIO))
5488                 return -EPERM;
5489         if (copy_from_user(&iocommand, argp, sizeof(iocommand)))
5490                 return -EFAULT;
5491         if ((iocommand.buf_size < 1) &&
5492             (iocommand.Request.Type.Direction != XFER_NONE)) {
5493                 return -EINVAL;
5494         }
5495         if (iocommand.buf_size > 0) {
5496                 buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
5497                 if (buff == NULL)
5498                         return -ENOMEM;
5499                 if (iocommand.Request.Type.Direction & XFER_WRITE) {
5500                         /* Copy the data into the buffer we created */
5501                         if (copy_from_user(buff, iocommand.buf,
5502                                 iocommand.buf_size)) {
5503                                 rc = -EFAULT;
5504                                 goto out_kfree;
5505                         }
5506                 } else {
5507                         memset(buff, 0, iocommand.buf_size);
5508                 }
5509         }
5510         c = cmd_alloc(h);
5511
5512         /* Fill in the command type */
5513         c->cmd_type = CMD_IOCTL_PEND;
5514         /* Fill in Command Header */
5515         c->Header.ReplyQueue = 0; /* unused in simple mode */
5516         if (iocommand.buf_size > 0) {   /* buffer to fill */
5517                 c->Header.SGList = 1;
5518                 c->Header.SGTotal = cpu_to_le16(1);
5519         } else  { /* no buffers to fill */
5520                 c->Header.SGList = 0;
5521                 c->Header.SGTotal = cpu_to_le16(0);
5522         }
5523         memcpy(&c->Header.LUN, &iocommand.LUN_info, sizeof(c->Header.LUN));
5524
5525         /* Fill in Request block */
5526         memcpy(&c->Request, &iocommand.Request,
5527                 sizeof(c->Request));
5528
5529         /* Fill in the scatter gather information */
5530         if (iocommand.buf_size > 0) {
5531                 temp64 = pci_map_single(h->pdev, buff,
5532                         iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
5533                 if (dma_mapping_error(&h->pdev->dev, (dma_addr_t) temp64)) {
5534                         c->SG[0].Addr = cpu_to_le64(0);
5535                         c->SG[0].Len = cpu_to_le32(0);
5536                         rc = -ENOMEM;
5537                         goto out;
5538                 }
5539                 c->SG[0].Addr = cpu_to_le64(temp64);
5540                 c->SG[0].Len = cpu_to_le32(iocommand.buf_size);
5541                 c->SG[0].Ext = cpu_to_le32(HPSA_SG_LAST); /* not chaining */
5542         }
5543         rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE, NO_TIMEOUT);
5544         if (iocommand.buf_size > 0)
5545                 hpsa_pci_unmap(h->pdev, c, 1, PCI_DMA_BIDIRECTIONAL);
5546         check_ioctl_unit_attention(h, c);
5547         if (rc) {
5548                 rc = -EIO;
5549                 goto out;
5550         }
5551
5552         /* Copy the error information out */
5553         memcpy(&iocommand.error_info, c->err_info,
5554                 sizeof(iocommand.error_info));
5555         if (copy_to_user(argp, &iocommand, sizeof(iocommand))) {
5556                 rc = -EFAULT;
5557                 goto out;
5558         }
5559         if ((iocommand.Request.Type.Direction & XFER_READ) &&
5560                 iocommand.buf_size > 0) {
5561                 /* Copy the data out of the buffer we created */
5562                 if (copy_to_user(iocommand.buf, buff, iocommand.buf_size)) {
5563                         rc = -EFAULT;
5564                         goto out;
5565                 }
5566         }
5567 out:
5568         cmd_free(h, c);
5569 out_kfree:
5570         kfree(buff);
5571         return rc;
5572 }
5573
5574 static int hpsa_big_passthru_ioctl(struct ctlr_info *h, void __user *argp)
5575 {
5576         BIG_IOCTL_Command_struct *ioc;
5577         struct CommandList *c;
5578         unsigned char **buff = NULL;
5579         int *buff_size = NULL;
5580         u64 temp64;
5581         BYTE sg_used = 0;
5582         int status = 0;
5583         u32 left;
5584         u32 sz;
5585         BYTE __user *data_ptr;
5586
5587         if (!argp)
5588                 return -EINVAL;
5589         if (!capable(CAP_SYS_RAWIO))
5590                 return -EPERM;
5591         ioc = (BIG_IOCTL_Command_struct *)
5592             kmalloc(sizeof(*ioc), GFP_KERNEL);
5593         if (!ioc) {
5594                 status = -ENOMEM;
5595                 goto cleanup1;
5596         }
5597         if (copy_from_user(ioc, argp, sizeof(*ioc))) {
5598                 status = -EFAULT;
5599                 goto cleanup1;
5600         }
5601         if ((ioc->buf_size < 1) &&
5602             (ioc->Request.Type.Direction != XFER_NONE)) {
5603                 status = -EINVAL;
5604                 goto cleanup1;
5605         }
5606         /* Check kmalloc limits  using all SGs */
5607         if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
5608                 status = -EINVAL;
5609                 goto cleanup1;
5610         }
5611         if (ioc->buf_size > ioc->malloc_size * SG_ENTRIES_IN_CMD) {
5612                 status = -EINVAL;
5613                 goto cleanup1;
5614         }
5615         buff = kzalloc(SG_ENTRIES_IN_CMD * sizeof(char *), GFP_KERNEL);
5616         if (!buff) {
5617                 status = -ENOMEM;
5618                 goto cleanup1;
5619         }
5620         buff_size = kmalloc(SG_ENTRIES_IN_CMD * sizeof(int), GFP_KERNEL);
5621         if (!buff_size) {
5622                 status = -ENOMEM;
5623                 goto cleanup1;
5624         }
5625         left = ioc->buf_size;
5626         data_ptr = ioc->buf;
5627         while (left) {
5628                 sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
5629                 buff_size[sg_used] = sz;
5630                 buff[sg_used] = kmalloc(sz, GFP_KERNEL);
5631                 if (buff[sg_used] == NULL) {
5632                         status = -ENOMEM;
5633                         goto cleanup1;
5634                 }
5635                 if (ioc->Request.Type.Direction & XFER_WRITE) {
5636                         if (copy_from_user(buff[sg_used], data_ptr, sz)) {
5637                                 status = -EFAULT;
5638                                 goto cleanup1;
5639                         }
5640                 } else
5641                         memset(buff[sg_used], 0, sz);
5642                 left -= sz;
5643                 data_ptr += sz;
5644                 sg_used++;
5645         }
5646         c = cmd_alloc(h);
5647
5648         c->cmd_type = CMD_IOCTL_PEND;
5649         c->Header.ReplyQueue = 0;
5650         c->Header.SGList = (u8) sg_used;
5651         c->Header.SGTotal = cpu_to_le16(sg_used);
5652         memcpy(&c->Header.LUN, &ioc->LUN_info, sizeof(c->Header.LUN));
5653         memcpy(&c->Request, &ioc->Request, sizeof(c->Request));
5654         if (ioc->buf_size > 0) {
5655                 int i;
5656                 for (i = 0; i < sg_used; i++) {
5657                         temp64 = pci_map_single(h->pdev, buff[i],
5658                                     buff_size[i], PCI_DMA_BIDIRECTIONAL);
5659                         if (dma_mapping_error(&h->pdev->dev,
5660                                                         (dma_addr_t) temp64)) {
5661                                 c->SG[i].Addr = cpu_to_le64(0);
5662                                 c->SG[i].Len = cpu_to_le32(0);
5663                                 hpsa_pci_unmap(h->pdev, c, i,
5664                                         PCI_DMA_BIDIRECTIONAL);
5665                                 status = -ENOMEM;
5666                                 goto cleanup0;
5667                         }
5668                         c->SG[i].Addr = cpu_to_le64(temp64);
5669                         c->SG[i].Len = cpu_to_le32(buff_size[i]);
5670                         c->SG[i].Ext = cpu_to_le32(0);
5671                 }
5672                 c->SG[--i].Ext = cpu_to_le32(HPSA_SG_LAST);
5673         }
5674         status = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE, NO_TIMEOUT);
5675         if (sg_used)
5676                 hpsa_pci_unmap(h->pdev, c, sg_used, PCI_DMA_BIDIRECTIONAL);
5677         check_ioctl_unit_attention(h, c);
5678         if (status) {
5679                 status = -EIO;
5680                 goto cleanup0;
5681         }
5682
5683         /* Copy the error information out */
5684         memcpy(&ioc->error_info, c->err_info, sizeof(ioc->error_info));
5685         if (copy_to_user(argp, ioc, sizeof(*ioc))) {
5686                 status = -EFAULT;
5687                 goto cleanup0;
5688         }
5689         if ((ioc->Request.Type.Direction & XFER_READ) && ioc->buf_size > 0) {
5690                 int i;
5691
5692                 /* Copy the data out of the buffer we created */
5693                 BYTE __user *ptr = ioc->buf;
5694                 for (i = 0; i < sg_used; i++) {
5695                         if (copy_to_user(ptr, buff[i], buff_size[i])) {
5696                                 status = -EFAULT;
5697                                 goto cleanup0;
5698                         }
5699                         ptr += buff_size[i];
5700                 }
5701         }
5702         status = 0;
5703 cleanup0:
5704         cmd_free(h, c);
5705 cleanup1:
5706         if (buff) {
5707                 int i;
5708
5709                 for (i = 0; i < sg_used; i++)
5710                         kfree(buff[i]);
5711                 kfree(buff);
5712         }
5713         kfree(buff_size);
5714         kfree(ioc);
5715         return status;
5716 }
5717
5718 static void check_ioctl_unit_attention(struct ctlr_info *h,
5719         struct CommandList *c)
5720 {
5721         if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
5722                         c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
5723                 (void) check_for_unit_attention(h, c);
5724 }
5725
5726 /*
5727  * ioctl
5728  */
5729 static int hpsa_ioctl(struct scsi_device *dev, int cmd, void __user *arg)
5730 {
5731         struct ctlr_info *h;
5732         void __user *argp = (void __user *)arg;
5733         int rc;
5734
5735         h = sdev_to_hba(dev);
5736
5737         switch (cmd) {
5738         case CCISS_DEREGDISK:
5739         case CCISS_REGNEWDISK:
5740         case CCISS_REGNEWD:
5741                 hpsa_scan_start(h->scsi_host);
5742                 return 0;
5743         case CCISS_GETPCIINFO:
5744                 return hpsa_getpciinfo_ioctl(h, argp);
5745         case CCISS_GETDRIVVER:
5746                 return hpsa_getdrivver_ioctl(h, argp);
5747         case CCISS_PASSTHRU:
5748                 if (atomic_dec_if_positive(&h->passthru_cmds_avail) < 0)
5749                         return -EAGAIN;
5750                 rc = hpsa_passthru_ioctl(h, argp);
5751                 atomic_inc(&h->passthru_cmds_avail);
5752                 return rc;
5753         case CCISS_BIG_PASSTHRU:
5754                 if (atomic_dec_if_positive(&h->passthru_cmds_avail) < 0)
5755                         return -EAGAIN;
5756                 rc = hpsa_big_passthru_ioctl(h, argp);
5757                 atomic_inc(&h->passthru_cmds_avail);
5758                 return rc;
5759         default:
5760                 return -ENOTTY;
5761         }
5762 }
5763
5764 static void hpsa_send_host_reset(struct ctlr_info *h, unsigned char *scsi3addr,
5765                                 u8 reset_type)
5766 {
5767         struct CommandList *c;
5768
5769         c = cmd_alloc(h);
5770
5771         /* fill_cmd can't fail here, no data buffer to map */
5772         (void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0,
5773                 RAID_CTLR_LUNID, TYPE_MSG);
5774         c->Request.CDB[1] = reset_type; /* fill_cmd defaults to target reset */
5775         c->waiting = NULL;
5776         enqueue_cmd_and_start_io(h, c);
5777         /* Don't wait for completion, the reset won't complete.  Don't free
5778          * the command either.  This is the last command we will send before
5779          * re-initializing everything, so it doesn't matter and won't leak.
5780          */
5781         return;
5782 }
5783
5784 static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
5785         void *buff, size_t size, u16 page_code, unsigned char *scsi3addr,
5786         int cmd_type)
5787 {
5788         int pci_dir = XFER_NONE;
5789         u64 tag; /* for commands to be aborted */
5790
5791         c->cmd_type = CMD_IOCTL_PEND;
5792         c->Header.ReplyQueue = 0;
5793         if (buff != NULL && size > 0) {
5794                 c->Header.SGList = 1;
5795                 c->Header.SGTotal = cpu_to_le16(1);
5796         } else {
5797                 c->Header.SGList = 0;
5798                 c->Header.SGTotal = cpu_to_le16(0);
5799         }
5800         memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
5801
5802         if (cmd_type == TYPE_CMD) {
5803                 switch (cmd) {
5804                 case HPSA_INQUIRY:
5805                         /* are we trying to read a vital product page */
5806                         if (page_code & VPD_PAGE) {
5807                                 c->Request.CDB[1] = 0x01;
5808                                 c->Request.CDB[2] = (page_code & 0xff);
5809                         }
5810                         c->Request.CDBLen = 6;
5811                         c->Request.type_attr_dir =
5812                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
5813                         c->Request.Timeout = 0;
5814                         c->Request.CDB[0] = HPSA_INQUIRY;
5815                         c->Request.CDB[4] = size & 0xFF;
5816                         break;
5817                 case HPSA_REPORT_LOG:
5818                 case HPSA_REPORT_PHYS:
5819                         /* Talking to controller so It's a physical command
5820                            mode = 00 target = 0.  Nothing to write.
5821                          */
5822                         c->Request.CDBLen = 12;
5823                         c->Request.type_attr_dir =
5824                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
5825                         c->Request.Timeout = 0;
5826                         c->Request.CDB[0] = cmd;
5827                         c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
5828                         c->Request.CDB[7] = (size >> 16) & 0xFF;
5829                         c->Request.CDB[8] = (size >> 8) & 0xFF;
5830                         c->Request.CDB[9] = size & 0xFF;
5831                         break;
5832                 case HPSA_CACHE_FLUSH:
5833                         c->Request.CDBLen = 12;
5834                         c->Request.type_attr_dir =
5835                                         TYPE_ATTR_DIR(cmd_type,
5836                                                 ATTR_SIMPLE, XFER_WRITE);
5837                         c->Request.Timeout = 0;
5838                         c->Request.CDB[0] = BMIC_WRITE;
5839                         c->Request.CDB[6] = BMIC_CACHE_FLUSH;
5840                         c->Request.CDB[7] = (size >> 8) & 0xFF;
5841                         c->Request.CDB[8] = size & 0xFF;
5842                         break;
5843                 case TEST_UNIT_READY:
5844                         c->Request.CDBLen = 6;
5845                         c->Request.type_attr_dir =
5846                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_NONE);
5847                         c->Request.Timeout = 0;
5848                         break;
5849                 case HPSA_GET_RAID_MAP:
5850                         c->Request.CDBLen = 12;
5851                         c->Request.type_attr_dir =
5852                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
5853                         c->Request.Timeout = 0;
5854                         c->Request.CDB[0] = HPSA_CISS_READ;
5855                         c->Request.CDB[1] = cmd;
5856                         c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
5857                         c->Request.CDB[7] = (size >> 16) & 0xFF;
5858                         c->Request.CDB[8] = (size >> 8) & 0xFF;
5859                         c->Request.CDB[9] = size & 0xFF;
5860                         break;
5861                 case BMIC_SENSE_CONTROLLER_PARAMETERS:
5862                         c->Request.CDBLen = 10;
5863                         c->Request.type_attr_dir =
5864                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
5865                         c->Request.Timeout = 0;
5866                         c->Request.CDB[0] = BMIC_READ;
5867                         c->Request.CDB[6] = BMIC_SENSE_CONTROLLER_PARAMETERS;
5868                         c->Request.CDB[7] = (size >> 16) & 0xFF;
5869                         c->Request.CDB[8] = (size >> 8) & 0xFF;
5870                         break;
5871                 case BMIC_IDENTIFY_PHYSICAL_DEVICE:
5872                         c->Request.CDBLen = 10;
5873                         c->Request.type_attr_dir =
5874                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
5875                         c->Request.Timeout = 0;
5876                         c->Request.CDB[0] = BMIC_READ;
5877                         c->Request.CDB[6] = BMIC_IDENTIFY_PHYSICAL_DEVICE;
5878                         c->Request.CDB[7] = (size >> 16) & 0xFF;
5879                         c->Request.CDB[8] = (size >> 8) & 0XFF;
5880                         break;
5881                 default:
5882                         dev_warn(&h->pdev->dev, "unknown command 0x%c\n", cmd);
5883                         BUG();
5884                         return -1;
5885                 }
5886         } else if (cmd_type == TYPE_MSG) {
5887                 switch (cmd) {
5888
5889                 case  HPSA_DEVICE_RESET_MSG:
5890                         c->Request.CDBLen = 16;
5891                         c->Request.type_attr_dir =
5892                                 TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_NONE);
5893                         c->Request.Timeout = 0; /* Don't time out */
5894                         memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
5895                         c->Request.CDB[0] =  cmd;
5896                         c->Request.CDB[1] = HPSA_RESET_TYPE_LUN;
5897                         /* If bytes 4-7 are zero, it means reset the */
5898                         /* LunID device */
5899                         c->Request.CDB[4] = 0x00;
5900                         c->Request.CDB[5] = 0x00;
5901                         c->Request.CDB[6] = 0x00;
5902                         c->Request.CDB[7] = 0x00;
5903                         break;
5904                 case  HPSA_ABORT_MSG:
5905                         memcpy(&tag, buff, sizeof(tag));
5906                         dev_dbg(&h->pdev->dev,
5907                                 "Abort Tag:0x%016llx using rqst Tag:0x%016llx",
5908                                 tag, c->Header.tag);
5909                         c->Request.CDBLen = 16;
5910                         c->Request.type_attr_dir =
5911                                         TYPE_ATTR_DIR(cmd_type,
5912                                                 ATTR_SIMPLE, XFER_WRITE);
5913                         c->Request.Timeout = 0; /* Don't time out */
5914                         c->Request.CDB[0] = HPSA_TASK_MANAGEMENT;
5915                         c->Request.CDB[1] = HPSA_TMF_ABORT_TASK;
5916                         c->Request.CDB[2] = 0x00; /* reserved */
5917                         c->Request.CDB[3] = 0x00; /* reserved */
5918                         /* Tag to abort goes in CDB[4]-CDB[11] */
5919                         memcpy(&c->Request.CDB[4], &tag, sizeof(tag));
5920                         c->Request.CDB[12] = 0x00; /* reserved */
5921                         c->Request.CDB[13] = 0x00; /* reserved */
5922                         c->Request.CDB[14] = 0x00; /* reserved */
5923                         c->Request.CDB[15] = 0x00; /* reserved */
5924                 break;
5925                 default:
5926                         dev_warn(&h->pdev->dev, "unknown message type %d\n",
5927                                 cmd);
5928                         BUG();
5929                 }
5930         } else {
5931                 dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
5932                 BUG();
5933         }
5934
5935         switch (GET_DIR(c->Request.type_attr_dir)) {
5936         case XFER_READ:
5937                 pci_dir = PCI_DMA_FROMDEVICE;
5938                 break;
5939         case XFER_WRITE:
5940                 pci_dir = PCI_DMA_TODEVICE;
5941                 break;
5942         case XFER_NONE:
5943                 pci_dir = PCI_DMA_NONE;
5944                 break;
5945         default:
5946                 pci_dir = PCI_DMA_BIDIRECTIONAL;
5947         }
5948         if (hpsa_map_one(h->pdev, c, buff, size, pci_dir))
5949                 return -1;
5950         return 0;
5951 }
5952
5953 /*
5954  * Map (physical) PCI mem into (virtual) kernel space
5955  */
5956 static void __iomem *remap_pci_mem(ulong base, ulong size)
5957 {
5958         ulong page_base = ((ulong) base) & PAGE_MASK;
5959         ulong page_offs = ((ulong) base) - page_base;
5960         void __iomem *page_remapped = ioremap_nocache(page_base,
5961                 page_offs + size);
5962
5963         return page_remapped ? (page_remapped + page_offs) : NULL;
5964 }
5965
5966 static inline unsigned long get_next_completion(struct ctlr_info *h, u8 q)
5967 {
5968         return h->access.command_completed(h, q);
5969 }
5970
5971 static inline bool interrupt_pending(struct ctlr_info *h)
5972 {
5973         return h->access.intr_pending(h);
5974 }
5975
5976 static inline long interrupt_not_for_us(struct ctlr_info *h)
5977 {
5978         return (h->access.intr_pending(h) == 0) ||
5979                 (h->interrupts_enabled == 0);
5980 }
5981
5982 static inline int bad_tag(struct ctlr_info *h, u32 tag_index,
5983         u32 raw_tag)
5984 {
5985         if (unlikely(tag_index >= h->nr_cmds)) {
5986                 dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
5987                 return 1;
5988         }
5989         return 0;
5990 }
5991
5992 static inline void finish_cmd(struct CommandList *c)
5993 {
5994         dial_up_lockup_detection_on_fw_flash_complete(c->h, c);
5995         if (likely(c->cmd_type == CMD_IOACCEL1 || c->cmd_type == CMD_SCSI
5996                         || c->cmd_type == CMD_IOACCEL2))
5997                 complete_scsi_command(c);
5998         else if (c->cmd_type == CMD_IOCTL_PEND || c->cmd_type == IOACCEL2_TMF)
5999                 complete(c->waiting);
6000 }
6001
6002
6003 static inline u32 hpsa_tag_discard_error_bits(struct ctlr_info *h, u32 tag)
6004 {
6005 #define HPSA_PERF_ERROR_BITS ((1 << DIRECT_LOOKUP_SHIFT) - 1)
6006 #define HPSA_SIMPLE_ERROR_BITS 0x03
6007         if (unlikely(!(h->transMethod & CFGTBL_Trans_Performant)))
6008                 return tag & ~HPSA_SIMPLE_ERROR_BITS;
6009         return tag & ~HPSA_PERF_ERROR_BITS;
6010 }
6011
6012 /* process completion of an indexed ("direct lookup") command */
6013 static inline void process_indexed_cmd(struct ctlr_info *h,
6014         u32 raw_tag)
6015 {
6016         u32 tag_index;
6017         struct CommandList *c;
6018
6019         tag_index = raw_tag >> DIRECT_LOOKUP_SHIFT;
6020         if (!bad_tag(h, tag_index, raw_tag)) {
6021                 c = h->cmd_pool + tag_index;
6022                 finish_cmd(c);
6023         }
6024 }
6025
6026 /* Some controllers, like p400, will give us one interrupt
6027  * after a soft reset, even if we turned interrupts off.
6028  * Only need to check for this in the hpsa_xxx_discard_completions
6029  * functions.
6030  */
6031 static int ignore_bogus_interrupt(struct ctlr_info *h)
6032 {
6033         if (likely(!reset_devices))
6034                 return 0;
6035
6036         if (likely(h->interrupts_enabled))
6037                 return 0;
6038
6039         dev_info(&h->pdev->dev, "Received interrupt while interrupts disabled "
6040                 "(known firmware bug.)  Ignoring.\n");
6041
6042         return 1;
6043 }
6044
6045 /*
6046  * Convert &h->q[x] (passed to interrupt handlers) back to h.
6047  * Relies on (h-q[x] == x) being true for x such that
6048  * 0 <= x < MAX_REPLY_QUEUES.
6049  */
6050 static struct ctlr_info *queue_to_hba(u8 *queue)
6051 {
6052         return container_of((queue - *queue), struct ctlr_info, q[0]);
6053 }
6054
6055 static irqreturn_t hpsa_intx_discard_completions(int irq, void *queue)
6056 {
6057         struct ctlr_info *h = queue_to_hba(queue);
6058         u8 q = *(u8 *) queue;
6059         u32 raw_tag;
6060
6061         if (ignore_bogus_interrupt(h))
6062                 return IRQ_NONE;
6063
6064         if (interrupt_not_for_us(h))
6065                 return IRQ_NONE;
6066         h->last_intr_timestamp = get_jiffies_64();
6067         while (interrupt_pending(h)) {
6068                 raw_tag = get_next_completion(h, q);
6069                 while (raw_tag != FIFO_EMPTY)
6070                         raw_tag = next_command(h, q);
6071         }
6072         return IRQ_HANDLED;
6073 }
6074
6075 static irqreturn_t hpsa_msix_discard_completions(int irq, void *queue)
6076 {
6077         struct ctlr_info *h = queue_to_hba(queue);
6078         u32 raw_tag;
6079         u8 q = *(u8 *) queue;
6080
6081         if (ignore_bogus_interrupt(h))
6082                 return IRQ_NONE;
6083
6084         h->last_intr_timestamp = get_jiffies_64();
6085         raw_tag = get_next_completion(h, q);
6086         while (raw_tag != FIFO_EMPTY)
6087                 raw_tag = next_command(h, q);
6088         return IRQ_HANDLED;
6089 }
6090
6091 static irqreturn_t do_hpsa_intr_intx(int irq, void *queue)
6092 {
6093         struct ctlr_info *h = queue_to_hba((u8 *) queue);
6094         u32 raw_tag;
6095         u8 q = *(u8 *) queue;
6096
6097         if (interrupt_not_for_us(h))
6098                 return IRQ_NONE;
6099         h->last_intr_timestamp = get_jiffies_64();
6100         while (interrupt_pending(h)) {
6101                 raw_tag = get_next_completion(h, q);
6102                 while (raw_tag != FIFO_EMPTY) {
6103                         process_indexed_cmd(h, raw_tag);
6104                         raw_tag = next_command(h, q);
6105                 }
6106         }
6107         return IRQ_HANDLED;
6108 }
6109
6110 static irqreturn_t do_hpsa_intr_msi(int irq, void *queue)
6111 {
6112         struct ctlr_info *h = queue_to_hba(queue);
6113         u32 raw_tag;
6114         u8 q = *(u8 *) queue;
6115
6116         h->last_intr_timestamp = get_jiffies_64();
6117         raw_tag = get_next_completion(h, q);
6118         while (raw_tag != FIFO_EMPTY) {
6119                 process_indexed_cmd(h, raw_tag);
6120                 raw_tag = next_command(h, q);
6121         }
6122         return IRQ_HANDLED;
6123 }
6124
6125 /* Send a message CDB to the firmware. Careful, this only works
6126  * in simple mode, not performant mode due to the tag lookup.
6127  * We only ever use this immediately after a controller reset.
6128  */
6129 static int hpsa_message(struct pci_dev *pdev, unsigned char opcode,
6130                         unsigned char type)
6131 {
6132         struct Command {
6133                 struct CommandListHeader CommandHeader;
6134                 struct RequestBlock Request;
6135                 struct ErrDescriptor ErrorDescriptor;
6136         };
6137         struct Command *cmd;
6138         static const size_t cmd_sz = sizeof(*cmd) +
6139                                         sizeof(cmd->ErrorDescriptor);
6140         dma_addr_t paddr64;
6141         __le32 paddr32;
6142         u32 tag;
6143         void __iomem *vaddr;
6144         int i, err;
6145
6146         vaddr = pci_ioremap_bar(pdev, 0);
6147         if (vaddr == NULL)
6148                 return -ENOMEM;
6149
6150         /* The Inbound Post Queue only accepts 32-bit physical addresses for the
6151          * CCISS commands, so they must be allocated from the lower 4GiB of
6152          * memory.
6153          */
6154         err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
6155         if (err) {
6156                 iounmap(vaddr);
6157                 return err;
6158         }
6159
6160         cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
6161         if (cmd == NULL) {
6162                 iounmap(vaddr);
6163                 return -ENOMEM;
6164         }
6165
6166         /* This must fit, because of the 32-bit consistent DMA mask.  Also,
6167          * although there's no guarantee, we assume that the address is at
6168          * least 4-byte aligned (most likely, it's page-aligned).
6169          */
6170         paddr32 = cpu_to_le32(paddr64);
6171
6172         cmd->CommandHeader.ReplyQueue = 0;
6173         cmd->CommandHeader.SGList = 0;
6174         cmd->CommandHeader.SGTotal = cpu_to_le16(0);
6175         cmd->CommandHeader.tag = cpu_to_le64(paddr64);
6176         memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
6177
6178         cmd->Request.CDBLen = 16;
6179         cmd->Request.type_attr_dir =
6180                         TYPE_ATTR_DIR(TYPE_MSG, ATTR_HEADOFQUEUE, XFER_NONE);
6181         cmd->Request.Timeout = 0; /* Don't time out */
6182         cmd->Request.CDB[0] = opcode;
6183         cmd->Request.CDB[1] = type;
6184         memset(&cmd->Request.CDB[2], 0, 14); /* rest of the CDB is reserved */
6185         cmd->ErrorDescriptor.Addr =
6186                         cpu_to_le64((le32_to_cpu(paddr32) + sizeof(*cmd)));
6187         cmd->ErrorDescriptor.Len = cpu_to_le32(sizeof(struct ErrorInfo));
6188
6189         writel(le32_to_cpu(paddr32), vaddr + SA5_REQUEST_PORT_OFFSET);
6190
6191         for (i = 0; i < HPSA_MSG_SEND_RETRY_LIMIT; i++) {
6192                 tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
6193                 if ((tag & ~HPSA_SIMPLE_ERROR_BITS) == paddr64)
6194                         break;
6195                 msleep(HPSA_MSG_SEND_RETRY_INTERVAL_MSECS);
6196         }
6197
6198         iounmap(vaddr);
6199
6200         /* we leak the DMA buffer here ... no choice since the controller could
6201          *  still complete the command.
6202          */
6203         if (i == HPSA_MSG_SEND_RETRY_LIMIT) {
6204                 dev_err(&pdev->dev, "controller message %02x:%02x timed out\n",
6205                         opcode, type);
6206                 return -ETIMEDOUT;
6207         }
6208
6209         pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
6210
6211         if (tag & HPSA_ERROR_BIT) {
6212                 dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
6213                         opcode, type);
6214                 return -EIO;
6215         }
6216
6217         dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
6218                 opcode, type);
6219         return 0;
6220 }
6221
6222 #define hpsa_noop(p) hpsa_message(p, 3, 0)
6223
6224 static int hpsa_controller_hard_reset(struct pci_dev *pdev,
6225         void __iomem *vaddr, u32 use_doorbell)
6226 {
6227
6228         if (use_doorbell) {
6229                 /* For everything after the P600, the PCI power state method
6230                  * of resetting the controller doesn't work, so we have this
6231                  * other way using the doorbell register.
6232                  */
6233                 dev_info(&pdev->dev, "using doorbell to reset controller\n");
6234                 writel(use_doorbell, vaddr + SA5_DOORBELL);
6235
6236                 /* PMC hardware guys tell us we need a 10 second delay after
6237                  * doorbell reset and before any attempt to talk to the board
6238                  * at all to ensure that this actually works and doesn't fall
6239                  * over in some weird corner cases.
6240                  */
6241                 msleep(10000);
6242         } else { /* Try to do it the PCI power state way */
6243
6244                 /* Quoting from the Open CISS Specification: "The Power
6245                  * Management Control/Status Register (CSR) controls the power
6246                  * state of the device.  The normal operating state is D0,
6247                  * CSR=00h.  The software off state is D3, CSR=03h.  To reset
6248                  * the controller, place the interface device in D3 then to D0,
6249                  * this causes a secondary PCI reset which will reset the
6250                  * controller." */
6251
6252                 int rc = 0;
6253
6254                 dev_info(&pdev->dev, "using PCI PM to reset controller\n");
6255
6256                 /* enter the D3hot power management state */
6257                 rc = pci_set_power_state(pdev, PCI_D3hot);
6258                 if (rc)
6259                         return rc;
6260
6261                 msleep(500);
6262
6263                 /* enter the D0 power management state */
6264                 rc = pci_set_power_state(pdev, PCI_D0);
6265                 if (rc)
6266                         return rc;
6267
6268                 /*
6269                  * The P600 requires a small delay when changing states.
6270                  * Otherwise we may think the board did not reset and we bail.
6271                  * This for kdump only and is particular to the P600.
6272                  */
6273                 msleep(500);
6274         }
6275         return 0;
6276 }
6277
6278 static void init_driver_version(char *driver_version, int len)
6279 {
6280         memset(driver_version, 0, len);
6281         strncpy(driver_version, HPSA " " HPSA_DRIVER_VERSION, len - 1);
6282 }
6283
6284 static int write_driver_ver_to_cfgtable(struct CfgTable __iomem *cfgtable)
6285 {
6286         char *driver_version;
6287         int i, size = sizeof(cfgtable->driver_version);
6288
6289         driver_version = kmalloc(size, GFP_KERNEL);
6290         if (!driver_version)
6291                 return -ENOMEM;
6292
6293         init_driver_version(driver_version, size);
6294         for (i = 0; i < size; i++)
6295                 writeb(driver_version[i], &cfgtable->driver_version[i]);
6296         kfree(driver_version);
6297         return 0;
6298 }
6299
6300 static void read_driver_ver_from_cfgtable(struct CfgTable __iomem *cfgtable,
6301                                           unsigned char *driver_ver)
6302 {
6303         int i;
6304
6305         for (i = 0; i < sizeof(cfgtable->driver_version); i++)
6306                 driver_ver[i] = readb(&cfgtable->driver_version[i]);
6307 }
6308
6309 static int controller_reset_failed(struct CfgTable __iomem *cfgtable)
6310 {
6311
6312         char *driver_ver, *old_driver_ver;
6313         int rc, size = sizeof(cfgtable->driver_version);
6314
6315         old_driver_ver = kmalloc(2 * size, GFP_KERNEL);
6316         if (!old_driver_ver)
6317                 return -ENOMEM;
6318         driver_ver = old_driver_ver + size;
6319
6320         /* After a reset, the 32 bytes of "driver version" in the cfgtable
6321          * should have been changed, otherwise we know the reset failed.
6322          */
6323         init_driver_version(old_driver_ver, size);
6324         read_driver_ver_from_cfgtable(cfgtable, driver_ver);
6325         rc = !memcmp(driver_ver, old_driver_ver, size);
6326         kfree(old_driver_ver);
6327         return rc;
6328 }
6329 /* This does a hard reset of the controller using PCI power management
6330  * states or the using the doorbell register.
6331  */
6332 static int hpsa_kdump_hard_reset_controller(struct pci_dev *pdev, u32 board_id)
6333 {
6334         u64 cfg_offset;
6335         u32 cfg_base_addr;
6336         u64 cfg_base_addr_index;
6337         void __iomem *vaddr;
6338         unsigned long paddr;
6339         u32 misc_fw_support;
6340         int rc;
6341         struct CfgTable __iomem *cfgtable;
6342         u32 use_doorbell;
6343         u16 command_register;
6344
6345         /* For controllers as old as the P600, this is very nearly
6346          * the same thing as
6347          *
6348          * pci_save_state(pci_dev);
6349          * pci_set_power_state(pci_dev, PCI_D3hot);
6350          * pci_set_power_state(pci_dev, PCI_D0);
6351          * pci_restore_state(pci_dev);
6352          *
6353          * For controllers newer than the P600, the pci power state
6354          * method of resetting doesn't work so we have another way
6355          * using the doorbell register.
6356          */
6357
6358         if (!ctlr_is_resettable(board_id)) {
6359                 dev_warn(&pdev->dev, "Controller not resettable\n");
6360                 return -ENODEV;
6361         }
6362
6363         /* if controller is soft- but not hard resettable... */
6364         if (!ctlr_is_hard_resettable(board_id))
6365                 return -ENOTSUPP; /* try soft reset later. */
6366
6367         /* Save the PCI command register */
6368         pci_read_config_word(pdev, 4, &command_register);
6369         pci_save_state(pdev);
6370
6371         /* find the first memory BAR, so we can find the cfg table */
6372         rc = hpsa_pci_find_memory_BAR(pdev, &paddr);
6373         if (rc)
6374                 return rc;
6375         vaddr = remap_pci_mem(paddr, 0x250);
6376         if (!vaddr)
6377                 return -ENOMEM;
6378
6379         /* find cfgtable in order to check if reset via doorbell is supported */
6380         rc = hpsa_find_cfg_addrs(pdev, vaddr, &cfg_base_addr,
6381                                         &cfg_base_addr_index, &cfg_offset);
6382         if (rc)
6383                 goto unmap_vaddr;
6384         cfgtable = remap_pci_mem(pci_resource_start(pdev,
6385                        cfg_base_addr_index) + cfg_offset, sizeof(*cfgtable));
6386         if (!cfgtable) {
6387                 rc = -ENOMEM;
6388                 goto unmap_vaddr;
6389         }
6390         rc = write_driver_ver_to_cfgtable(cfgtable);
6391         if (rc)
6392                 goto unmap_cfgtable;
6393
6394         /* If reset via doorbell register is supported, use that.
6395          * There are two such methods.  Favor the newest method.
6396          */
6397         misc_fw_support = readl(&cfgtable->misc_fw_support);
6398         use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET2;
6399         if (use_doorbell) {
6400                 use_doorbell = DOORBELL_CTLR_RESET2;
6401         } else {
6402                 use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET;
6403                 if (use_doorbell) {
6404                         dev_warn(&pdev->dev,
6405                                 "Soft reset not supported. Firmware update is required.\n");
6406                         rc = -ENOTSUPP; /* try soft reset */
6407                         goto unmap_cfgtable;
6408                 }
6409         }
6410
6411         rc = hpsa_controller_hard_reset(pdev, vaddr, use_doorbell);
6412         if (rc)
6413                 goto unmap_cfgtable;
6414
6415         pci_restore_state(pdev);
6416         pci_write_config_word(pdev, 4, command_register);
6417
6418         /* Some devices (notably the HP Smart Array 5i Controller)
6419            need a little pause here */
6420         msleep(HPSA_POST_RESET_PAUSE_MSECS);
6421
6422         rc = hpsa_wait_for_board_state(pdev, vaddr, BOARD_READY);
6423         if (rc) {
6424                 dev_warn(&pdev->dev,
6425                         "Failed waiting for board to become ready after hard reset\n");
6426                 goto unmap_cfgtable;
6427         }
6428
6429         rc = controller_reset_failed(vaddr);
6430         if (rc < 0)
6431                 goto unmap_cfgtable;
6432         if (rc) {
6433                 dev_warn(&pdev->dev, "Unable to successfully reset "
6434                         "controller. Will try soft reset.\n");
6435                 rc = -ENOTSUPP;
6436         } else {
6437                 dev_info(&pdev->dev, "board ready after hard reset.\n");
6438         }
6439
6440 unmap_cfgtable:
6441         iounmap(cfgtable);
6442
6443 unmap_vaddr:
6444         iounmap(vaddr);
6445         return rc;
6446 }
6447
6448 /*
6449  *  We cannot read the structure directly, for portability we must use
6450  *   the io functions.
6451  *   This is for debug only.
6452  */
6453 static void print_cfg_table(struct device *dev, struct CfgTable __iomem *tb)
6454 {
6455 #ifdef HPSA_DEBUG
6456         int i;
6457         char temp_name[17];
6458
6459         dev_info(dev, "Controller Configuration information\n");
6460         dev_info(dev, "------------------------------------\n");
6461         for (i = 0; i < 4; i++)
6462                 temp_name[i] = readb(&(tb->Signature[i]));
6463         temp_name[4] = '\0';
6464         dev_info(dev, "   Signature = %s\n", temp_name);
6465         dev_info(dev, "   Spec Number = %d\n", readl(&(tb->SpecValence)));
6466         dev_info(dev, "   Transport methods supported = 0x%x\n",
6467                readl(&(tb->TransportSupport)));
6468         dev_info(dev, "   Transport methods active = 0x%x\n",
6469                readl(&(tb->TransportActive)));
6470         dev_info(dev, "   Requested transport Method = 0x%x\n",
6471                readl(&(tb->HostWrite.TransportRequest)));
6472         dev_info(dev, "   Coalesce Interrupt Delay = 0x%x\n",
6473                readl(&(tb->HostWrite.CoalIntDelay)));
6474         dev_info(dev, "   Coalesce Interrupt Count = 0x%x\n",
6475                readl(&(tb->HostWrite.CoalIntCount)));
6476         dev_info(dev, "   Max outstanding commands = %d\n",
6477                readl(&(tb->CmdsOutMax)));
6478         dev_info(dev, "   Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
6479         for (i = 0; i < 16; i++)
6480                 temp_name[i] = readb(&(tb->ServerName[i]));
6481         temp_name[16] = '\0';
6482         dev_info(dev, "   Server Name = %s\n", temp_name);
6483         dev_info(dev, "   Heartbeat Counter = 0x%x\n\n\n",
6484                 readl(&(tb->HeartBeat)));
6485 #endif                          /* HPSA_DEBUG */
6486 }
6487
6488 static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
6489 {
6490         int i, offset, mem_type, bar_type;
6491
6492         if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
6493                 return 0;
6494         offset = 0;
6495         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
6496                 bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
6497                 if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
6498                         offset += 4;
6499                 else {
6500                         mem_type = pci_resource_flags(pdev, i) &
6501                             PCI_BASE_ADDRESS_MEM_TYPE_MASK;
6502                         switch (mem_type) {
6503                         case PCI_BASE_ADDRESS_MEM_TYPE_32:
6504                         case PCI_BASE_ADDRESS_MEM_TYPE_1M:
6505                                 offset += 4;    /* 32 bit */
6506                                 break;
6507                         case PCI_BASE_ADDRESS_MEM_TYPE_64:
6508                                 offset += 8;
6509                                 break;
6510                         default:        /* reserved in PCI 2.2 */
6511                                 dev_warn(&pdev->dev,
6512                                        "base address is invalid\n");
6513                                 return -1;
6514                                 break;
6515                         }
6516                 }
6517                 if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
6518                         return i + 1;
6519         }
6520         return -1;
6521 }
6522
6523 static void hpsa_disable_interrupt_mode(struct ctlr_info *h)
6524 {
6525         if (h->msix_vector) {
6526                 if (h->pdev->msix_enabled)
6527                         pci_disable_msix(h->pdev);
6528                 h->msix_vector = 0;
6529         } else if (h->msi_vector) {
6530                 if (h->pdev->msi_enabled)
6531                         pci_disable_msi(h->pdev);
6532                 h->msi_vector = 0;
6533         }
6534 }
6535
6536 /* If MSI/MSI-X is supported by the kernel we will try to enable it on
6537  * controllers that are capable. If not, we use legacy INTx mode.
6538  */
6539 static void hpsa_interrupt_mode(struct ctlr_info *h)
6540 {
6541 #ifdef CONFIG_PCI_MSI
6542         int err, i;
6543         struct msix_entry hpsa_msix_entries[MAX_REPLY_QUEUES];
6544
6545         for (i = 0; i < MAX_REPLY_QUEUES; i++) {
6546                 hpsa_msix_entries[i].vector = 0;
6547                 hpsa_msix_entries[i].entry = i;
6548         }
6549
6550         /* Some boards advertise MSI but don't really support it */
6551         if ((h->board_id == 0x40700E11) || (h->board_id == 0x40800E11) ||
6552             (h->board_id == 0x40820E11) || (h->board_id == 0x40830E11))
6553                 goto default_int_mode;
6554         if (pci_find_capability(h->pdev, PCI_CAP_ID_MSIX)) {
6555                 dev_info(&h->pdev->dev, "MSI-X capable controller\n");
6556                 h->msix_vector = MAX_REPLY_QUEUES;
6557                 if (h->msix_vector > num_online_cpus())
6558                         h->msix_vector = num_online_cpus();
6559                 err = pci_enable_msix_range(h->pdev, hpsa_msix_entries,
6560                                             1, h->msix_vector);
6561                 if (err < 0) {
6562                         dev_warn(&h->pdev->dev, "MSI-X init failed %d\n", err);
6563                         h->msix_vector = 0;
6564                         goto single_msi_mode;
6565                 } else if (err < h->msix_vector) {
6566                         dev_warn(&h->pdev->dev, "only %d MSI-X vectors "
6567                                "available\n", err);
6568                 }
6569                 h->msix_vector = err;
6570                 for (i = 0; i < h->msix_vector; i++)
6571                         h->intr[i] = hpsa_msix_entries[i].vector;
6572                 return;
6573         }
6574 single_msi_mode:
6575         if (pci_find_capability(h->pdev, PCI_CAP_ID_MSI)) {
6576                 dev_info(&h->pdev->dev, "MSI capable controller\n");
6577                 if (!pci_enable_msi(h->pdev))
6578                         h->msi_vector = 1;
6579                 else
6580                         dev_warn(&h->pdev->dev, "MSI init failed\n");
6581         }
6582 default_int_mode:
6583 #endif                          /* CONFIG_PCI_MSI */
6584         /* if we get here we're going to use the default interrupt mode */
6585         h->intr[h->intr_mode] = h->pdev->irq;
6586 }
6587
6588 static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id)
6589 {
6590         int i;
6591         u32 subsystem_vendor_id, subsystem_device_id;
6592
6593         subsystem_vendor_id = pdev->subsystem_vendor;
6594         subsystem_device_id = pdev->subsystem_device;
6595         *board_id = ((subsystem_device_id << 16) & 0xffff0000) |
6596                     subsystem_vendor_id;
6597
6598         for (i = 0; i < ARRAY_SIZE(products); i++)
6599                 if (*board_id == products[i].board_id)
6600                         return i;
6601
6602         if ((subsystem_vendor_id != PCI_VENDOR_ID_HP &&
6603                 subsystem_vendor_id != PCI_VENDOR_ID_COMPAQ) ||
6604                 !hpsa_allow_any) {
6605                 dev_warn(&pdev->dev, "unrecognized board ID: "
6606                         "0x%08x, ignoring.\n", *board_id);
6607                         return -ENODEV;
6608         }
6609         return ARRAY_SIZE(products) - 1; /* generic unknown smart array */
6610 }
6611
6612 static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
6613                                     unsigned long *memory_bar)
6614 {
6615         int i;
6616
6617         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
6618                 if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
6619                         /* addressing mode bits already removed */
6620                         *memory_bar = pci_resource_start(pdev, i);
6621                         dev_dbg(&pdev->dev, "memory BAR = %lx\n",
6622                                 *memory_bar);
6623                         return 0;
6624                 }
6625         dev_warn(&pdev->dev, "no memory BAR found\n");
6626         return -ENODEV;
6627 }
6628
6629 static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
6630                                      int wait_for_ready)
6631 {
6632         int i, iterations;
6633         u32 scratchpad;
6634         if (wait_for_ready)
6635                 iterations = HPSA_BOARD_READY_ITERATIONS;
6636         else
6637                 iterations = HPSA_BOARD_NOT_READY_ITERATIONS;
6638
6639         for (i = 0; i < iterations; i++) {
6640                 scratchpad = readl(vaddr + SA5_SCRATCHPAD_OFFSET);
6641                 if (wait_for_ready) {
6642                         if (scratchpad == HPSA_FIRMWARE_READY)
6643                                 return 0;
6644                 } else {
6645                         if (scratchpad != HPSA_FIRMWARE_READY)
6646                                 return 0;
6647                 }
6648                 msleep(HPSA_BOARD_READY_POLL_INTERVAL_MSECS);
6649         }
6650         dev_warn(&pdev->dev, "board not ready, timed out.\n");
6651         return -ENODEV;
6652 }
6653
6654 static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
6655                                u32 *cfg_base_addr, u64 *cfg_base_addr_index,
6656                                u64 *cfg_offset)
6657 {
6658         *cfg_base_addr = readl(vaddr + SA5_CTCFG_OFFSET);
6659         *cfg_offset = readl(vaddr + SA5_CTMEM_OFFSET);
6660         *cfg_base_addr &= (u32) 0x0000ffff;
6661         *cfg_base_addr_index = find_PCI_BAR_index(pdev, *cfg_base_addr);
6662         if (*cfg_base_addr_index == -1) {
6663                 dev_warn(&pdev->dev, "cannot find cfg_base_addr_index\n");
6664                 return -ENODEV;
6665         }
6666         return 0;
6667 }
6668
6669 static void hpsa_free_cfgtables(struct ctlr_info *h)
6670 {
6671         if (h->transtable) {
6672                 iounmap(h->transtable);
6673                 h->transtable = NULL;
6674         }
6675         if (h->cfgtable) {
6676                 iounmap(h->cfgtable);
6677                 h->cfgtable = NULL;
6678         }
6679 }
6680
6681 /* Find and map CISS config table and transfer table
6682 + * several items must be unmapped (freed) later
6683 + * */
6684 static int hpsa_find_cfgtables(struct ctlr_info *h)
6685 {
6686         u64 cfg_offset;
6687         u32 cfg_base_addr;
6688         u64 cfg_base_addr_index;
6689         u32 trans_offset;
6690         int rc;
6691
6692         rc = hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
6693                 &cfg_base_addr_index, &cfg_offset);
6694         if (rc)
6695                 return rc;
6696         h->cfgtable = remap_pci_mem(pci_resource_start(h->pdev,
6697                        cfg_base_addr_index) + cfg_offset, sizeof(*h->cfgtable));
6698         if (!h->cfgtable) {
6699                 dev_err(&h->pdev->dev, "Failed mapping cfgtable\n");
6700                 return -ENOMEM;
6701         }
6702         rc = write_driver_ver_to_cfgtable(h->cfgtable);
6703         if (rc)
6704                 return rc;
6705         /* Find performant mode table. */
6706         trans_offset = readl(&h->cfgtable->TransMethodOffset);
6707         h->transtable = remap_pci_mem(pci_resource_start(h->pdev,
6708                                 cfg_base_addr_index)+cfg_offset+trans_offset,
6709                                 sizeof(*h->transtable));
6710         if (!h->transtable) {
6711                 dev_err(&h->pdev->dev, "Failed mapping transfer table\n");
6712                 hpsa_free_cfgtables(h);
6713                 return -ENOMEM;
6714         }
6715         return 0;
6716 }
6717
6718 static void hpsa_get_max_perf_mode_cmds(struct ctlr_info *h)
6719 {
6720 #define MIN_MAX_COMMANDS 16
6721         BUILD_BUG_ON(MIN_MAX_COMMANDS <= HPSA_NRESERVED_CMDS);
6722
6723         h->max_commands = readl(&h->cfgtable->MaxPerformantModeCommands);
6724
6725         /* Limit commands in memory limited kdump scenario. */
6726         if (reset_devices && h->max_commands > 32)
6727                 h->max_commands = 32;
6728
6729         if (h->max_commands < MIN_MAX_COMMANDS) {
6730                 dev_warn(&h->pdev->dev,
6731                         "Controller reports max supported commands of %d Using %d instead. Ensure that firmware is up to date.\n",
6732                         h->max_commands,
6733                         MIN_MAX_COMMANDS);
6734                 h->max_commands = MIN_MAX_COMMANDS;
6735         }
6736 }
6737
6738 /* If the controller reports that the total max sg entries is greater than 512,
6739  * then we know that chained SG blocks work.  (Original smart arrays did not
6740  * support chained SG blocks and would return zero for max sg entries.)
6741  */
6742 static int hpsa_supports_chained_sg_blocks(struct ctlr_info *h)
6743 {
6744         return h->maxsgentries > 512;
6745 }
6746
6747 /* Interrogate the hardware for some limits:
6748  * max commands, max SG elements without chaining, and with chaining,
6749  * SG chain block size, etc.
6750  */
6751 static void hpsa_find_board_params(struct ctlr_info *h)
6752 {
6753         hpsa_get_max_perf_mode_cmds(h);
6754         h->nr_cmds = h->max_commands;
6755         h->maxsgentries = readl(&(h->cfgtable->MaxScatterGatherElements));
6756         h->fw_support = readl(&(h->cfgtable->misc_fw_support));
6757         if (hpsa_supports_chained_sg_blocks(h)) {
6758                 /* Limit in-command s/g elements to 32 save dma'able memory. */
6759                 h->max_cmd_sg_entries = 32;
6760                 h->chainsize = h->maxsgentries - h->max_cmd_sg_entries;
6761                 h->maxsgentries--; /* save one for chain pointer */
6762         } else {
6763                 /*
6764                  * Original smart arrays supported at most 31 s/g entries
6765                  * embedded inline in the command (trying to use more
6766                  * would lock up the controller)
6767                  */
6768                 h->max_cmd_sg_entries = 31;
6769                 h->maxsgentries = 31; /* default to traditional values */
6770                 h->chainsize = 0;
6771         }
6772
6773         /* Find out what task management functions are supported and cache */
6774         h->TMFSupportFlags = readl(&(h->cfgtable->TMFSupportFlags));
6775         if (!(HPSATMF_PHYS_TASK_ABORT & h->TMFSupportFlags))
6776                 dev_warn(&h->pdev->dev, "Physical aborts not supported\n");
6777         if (!(HPSATMF_LOG_TASK_ABORT & h->TMFSupportFlags))
6778                 dev_warn(&h->pdev->dev, "Logical aborts not supported\n");
6779         if (!(HPSATMF_IOACCEL_ENABLED & h->TMFSupportFlags))
6780                 dev_warn(&h->pdev->dev, "HP SSD Smart Path aborts not supported\n");
6781 }
6782
6783 static inline bool hpsa_CISS_signature_present(struct ctlr_info *h)
6784 {
6785         if (!check_signature(h->cfgtable->Signature, "CISS", 4)) {
6786                 dev_err(&h->pdev->dev, "not a valid CISS config table\n");
6787                 return false;
6788         }
6789         return true;
6790 }
6791
6792 static inline void hpsa_set_driver_support_bits(struct ctlr_info *h)
6793 {
6794         u32 driver_support;
6795
6796         driver_support = readl(&(h->cfgtable->driver_support));
6797         /* Need to enable prefetch in the SCSI core for 6400 in x86 */
6798 #ifdef CONFIG_X86
6799         driver_support |= ENABLE_SCSI_PREFETCH;
6800 #endif
6801         driver_support |= ENABLE_UNIT_ATTN;
6802         writel(driver_support, &(h->cfgtable->driver_support));
6803 }
6804
6805 /* Disable DMA prefetch for the P600.  Otherwise an ASIC bug may result
6806  * in a prefetch beyond physical memory.
6807  */
6808 static inline void hpsa_p600_dma_prefetch_quirk(struct ctlr_info *h)
6809 {
6810         u32 dma_prefetch;
6811
6812         if (h->board_id != 0x3225103C)
6813                 return;
6814         dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
6815         dma_prefetch |= 0x8000;
6816         writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
6817 }
6818
6819 static int hpsa_wait_for_clear_event_notify_ack(struct ctlr_info *h)
6820 {
6821         int i;
6822         u32 doorbell_value;
6823         unsigned long flags;
6824         /* wait until the clear_event_notify bit 6 is cleared by controller. */
6825         for (i = 0; i < MAX_CLEAR_EVENT_WAIT; i++) {
6826                 spin_lock_irqsave(&h->lock, flags);
6827                 doorbell_value = readl(h->vaddr + SA5_DOORBELL);
6828                 spin_unlock_irqrestore(&h->lock, flags);
6829                 if (!(doorbell_value & DOORBELL_CLEAR_EVENTS))
6830                         goto done;
6831                 /* delay and try again */
6832                 msleep(CLEAR_EVENT_WAIT_INTERVAL);
6833         }
6834         return -ENODEV;
6835 done:
6836         return 0;
6837 }
6838
6839 static int hpsa_wait_for_mode_change_ack(struct ctlr_info *h)
6840 {
6841         int i;
6842         u32 doorbell_value;
6843         unsigned long flags;
6844
6845         /* under certain very rare conditions, this can take awhile.
6846          * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
6847          * as we enter this code.)
6848          */
6849         for (i = 0; i < MAX_MODE_CHANGE_WAIT; i++) {
6850                 if (h->remove_in_progress)
6851                         goto done;
6852                 spin_lock_irqsave(&h->lock, flags);
6853                 doorbell_value = readl(h->vaddr + SA5_DOORBELL);
6854                 spin_unlock_irqrestore(&h->lock, flags);
6855                 if (!(doorbell_value & CFGTBL_ChangeReq))
6856                         goto done;
6857                 /* delay and try again */
6858                 msleep(MODE_CHANGE_WAIT_INTERVAL);
6859         }
6860         return -ENODEV;
6861 done:
6862         return 0;
6863 }
6864
6865 /* return -ENODEV or other reason on error, 0 on success */
6866 static int hpsa_enter_simple_mode(struct ctlr_info *h)
6867 {
6868         u32 trans_support;
6869
6870         trans_support = readl(&(h->cfgtable->TransportSupport));
6871         if (!(trans_support & SIMPLE_MODE))
6872                 return -ENOTSUPP;
6873
6874         h->max_commands = readl(&(h->cfgtable->CmdsOutMax));
6875
6876         /* Update the field, and then ring the doorbell */
6877         writel(CFGTBL_Trans_Simple, &(h->cfgtable->HostWrite.TransportRequest));
6878         writel(0, &h->cfgtable->HostWrite.command_pool_addr_hi);
6879         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
6880         if (hpsa_wait_for_mode_change_ack(h))
6881                 goto error;
6882         print_cfg_table(&h->pdev->dev, h->cfgtable);
6883         if (!(readl(&(h->cfgtable->TransportActive)) & CFGTBL_Trans_Simple))
6884                 goto error;
6885         h->transMethod = CFGTBL_Trans_Simple;
6886         return 0;
6887 error:
6888         dev_err(&h->pdev->dev, "failed to enter simple mode\n");
6889         return -ENODEV;
6890 }
6891
6892 /* free items allocated or mapped by hpsa_pci_init */
6893 static void hpsa_free_pci_init(struct ctlr_info *h)
6894 {
6895         hpsa_free_cfgtables(h);                 /* pci_init 4 */
6896         iounmap(h->vaddr);                      /* pci_init 3 */
6897         h->vaddr = NULL;
6898         hpsa_disable_interrupt_mode(h);         /* pci_init 2 */
6899         pci_release_regions(h->pdev);           /* pci_init 2 */
6900         pci_disable_device(h->pdev);            /* pci_init 1 */
6901 }
6902
6903 /* several items must be freed later */
6904 static int hpsa_pci_init(struct ctlr_info *h)
6905 {
6906         int prod_index, err;
6907
6908         prod_index = hpsa_lookup_board_id(h->pdev, &h->board_id);
6909         if (prod_index < 0)
6910                 return prod_index;
6911         h->product_name = products[prod_index].product_name;
6912         h->access = *(products[prod_index].access);
6913
6914         h->needs_abort_tags_swizzled =
6915                 ctlr_needs_abort_tags_swizzled(h->board_id);
6916
6917         pci_disable_link_state(h->pdev, PCIE_LINK_STATE_L0S |
6918                                PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM);
6919
6920         err = pci_enable_device(h->pdev);
6921         if (err) {
6922                 dev_err(&h->pdev->dev, "failed to enable PCI device\n");
6923                 return err;
6924         }
6925
6926         err = pci_request_regions(h->pdev, HPSA);
6927         if (err) {
6928                 dev_err(&h->pdev->dev,
6929                         "failed to obtain PCI resources\n");
6930                 goto clean1;    /* pci */
6931         }
6932
6933         pci_set_master(h->pdev);
6934
6935         hpsa_interrupt_mode(h);
6936         err = hpsa_pci_find_memory_BAR(h->pdev, &h->paddr);
6937         if (err)
6938                 goto clean2;    /* intmode+region, pci */
6939         h->vaddr = remap_pci_mem(h->paddr, 0x250);
6940         if (!h->vaddr) {
6941                 dev_err(&h->pdev->dev, "failed to remap PCI mem\n");
6942                 err = -ENOMEM;
6943                 goto clean2;    /* intmode+region, pci */
6944         }
6945         err = hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY);
6946         if (err)
6947                 goto clean3;    /* vaddr, intmode+region, pci */
6948         err = hpsa_find_cfgtables(h);
6949         if (err)
6950                 goto clean3;    /* vaddr, intmode+region, pci */
6951         hpsa_find_board_params(h);
6952
6953         if (!hpsa_CISS_signature_present(h)) {
6954                 err = -ENODEV;
6955                 goto clean4;    /* cfgtables, vaddr, intmode+region, pci */
6956         }
6957         hpsa_set_driver_support_bits(h);
6958         hpsa_p600_dma_prefetch_quirk(h);
6959         err = hpsa_enter_simple_mode(h);
6960         if (err)
6961                 goto clean4;    /* cfgtables, vaddr, intmode+region, pci */
6962         return 0;
6963
6964 clean4: /* cfgtables, vaddr, intmode+region, pci */
6965         hpsa_free_cfgtables(h);
6966 clean3: /* vaddr, intmode+region, pci */
6967         iounmap(h->vaddr);
6968         h->vaddr = NULL;
6969 clean2: /* intmode+region, pci */
6970         hpsa_disable_interrupt_mode(h);
6971         pci_release_regions(h->pdev);
6972 clean1: /* pci */
6973         pci_disable_device(h->pdev);
6974         return err;
6975 }
6976
6977 static void hpsa_hba_inquiry(struct ctlr_info *h)
6978 {
6979         int rc;
6980
6981 #define HBA_INQUIRY_BYTE_COUNT 64
6982         h->hba_inquiry_data = kmalloc(HBA_INQUIRY_BYTE_COUNT, GFP_KERNEL);
6983         if (!h->hba_inquiry_data)
6984                 return;
6985         rc = hpsa_scsi_do_inquiry(h, RAID_CTLR_LUNID, 0,
6986                 h->hba_inquiry_data, HBA_INQUIRY_BYTE_COUNT);
6987         if (rc != 0) {
6988                 kfree(h->hba_inquiry_data);
6989                 h->hba_inquiry_data = NULL;
6990         }
6991 }
6992
6993 static int hpsa_init_reset_devices(struct pci_dev *pdev, u32 board_id)
6994 {
6995         int rc, i;
6996         void __iomem *vaddr;
6997
6998         if (!reset_devices)
6999                 return 0;
7000
7001         /* kdump kernel is loading, we don't know in which state is
7002          * the pci interface. The dev->enable_cnt is equal zero
7003          * so we call enable+disable, wait a while and switch it on.
7004          */
7005         rc = pci_enable_device(pdev);
7006         if (rc) {
7007                 dev_warn(&pdev->dev, "Failed to enable PCI device\n");
7008                 return -ENODEV;
7009         }
7010         pci_disable_device(pdev);
7011         msleep(260);                    /* a randomly chosen number */
7012         rc = pci_enable_device(pdev);
7013         if (rc) {
7014                 dev_warn(&pdev->dev, "failed to enable device.\n");
7015                 return -ENODEV;
7016         }
7017
7018         pci_set_master(pdev);
7019
7020         vaddr = pci_ioremap_bar(pdev, 0);
7021         if (vaddr == NULL) {
7022                 rc = -ENOMEM;
7023                 goto out_disable;
7024         }
7025         writel(SA5_INTR_OFF, vaddr + SA5_REPLY_INTR_MASK_OFFSET);
7026         iounmap(vaddr);
7027
7028         /* Reset the controller with a PCI power-cycle or via doorbell */
7029         rc = hpsa_kdump_hard_reset_controller(pdev, board_id);
7030
7031         /* -ENOTSUPP here means we cannot reset the controller
7032          * but it's already (and still) up and running in
7033          * "performant mode".  Or, it might be 640x, which can't reset
7034          * due to concerns about shared bbwc between 6402/6404 pair.
7035          */
7036         if (rc)
7037                 goto out_disable;
7038
7039         /* Now try to get the controller to respond to a no-op */
7040         dev_info(&pdev->dev, "Waiting for controller to respond to no-op\n");
7041         for (i = 0; i < HPSA_POST_RESET_NOOP_RETRIES; i++) {
7042                 if (hpsa_noop(pdev) == 0)
7043                         break;
7044                 else
7045                         dev_warn(&pdev->dev, "no-op failed%s\n",
7046                                         (i < 11 ? "; re-trying" : ""));
7047         }
7048
7049 out_disable:
7050
7051         pci_disable_device(pdev);
7052         return rc;
7053 }
7054
7055 static void hpsa_free_cmd_pool(struct ctlr_info *h)
7056 {
7057         kfree(h->cmd_pool_bits);
7058         h->cmd_pool_bits = NULL;
7059         if (h->cmd_pool) {
7060                 pci_free_consistent(h->pdev,
7061                                 h->nr_cmds * sizeof(struct CommandList),
7062                                 h->cmd_pool,
7063                                 h->cmd_pool_dhandle);
7064                 h->cmd_pool = NULL;
7065                 h->cmd_pool_dhandle = 0;
7066         }
7067         if (h->errinfo_pool) {
7068                 pci_free_consistent(h->pdev,
7069                                 h->nr_cmds * sizeof(struct ErrorInfo),
7070                                 h->errinfo_pool,
7071                                 h->errinfo_pool_dhandle);
7072                 h->errinfo_pool = NULL;
7073                 h->errinfo_pool_dhandle = 0;
7074         }
7075 }
7076
7077 static int hpsa_alloc_cmd_pool(struct ctlr_info *h)
7078 {
7079         h->cmd_pool_bits = kzalloc(
7080                 DIV_ROUND_UP(h->nr_cmds, BITS_PER_LONG) *
7081                 sizeof(unsigned long), GFP_KERNEL);
7082         h->cmd_pool = pci_alloc_consistent(h->pdev,
7083                     h->nr_cmds * sizeof(*h->cmd_pool),
7084                     &(h->cmd_pool_dhandle));
7085         h->errinfo_pool = pci_alloc_consistent(h->pdev,
7086                     h->nr_cmds * sizeof(*h->errinfo_pool),
7087                     &(h->errinfo_pool_dhandle));
7088         if ((h->cmd_pool_bits == NULL)
7089             || (h->cmd_pool == NULL)
7090             || (h->errinfo_pool == NULL)) {
7091                 dev_err(&h->pdev->dev, "out of memory in %s", __func__);
7092                 goto clean_up;
7093         }
7094         hpsa_preinitialize_commands(h);
7095         return 0;
7096 clean_up:
7097         hpsa_free_cmd_pool(h);
7098         return -ENOMEM;
7099 }
7100
7101 static void hpsa_irq_affinity_hints(struct ctlr_info *h)
7102 {
7103         int i, cpu;
7104
7105         cpu = cpumask_first(cpu_online_mask);
7106         for (i = 0; i < h->msix_vector; i++) {
7107                 irq_set_affinity_hint(h->intr[i], get_cpu_mask(cpu));
7108                 cpu = cpumask_next(cpu, cpu_online_mask);
7109         }
7110 }
7111
7112 /* clear affinity hints and free MSI-X, MSI, or legacy INTx vectors */
7113 static void hpsa_free_irqs(struct ctlr_info *h)
7114 {
7115         int i;
7116
7117         if (!h->msix_vector || h->intr_mode != PERF_MODE_INT) {
7118                 /* Single reply queue, only one irq to free */
7119                 i = h->intr_mode;
7120                 irq_set_affinity_hint(h->intr[i], NULL);
7121                 free_irq(h->intr[i], &h->q[i]);
7122                 h->q[i] = 0;
7123                 return;
7124         }
7125
7126         for (i = 0; i < h->msix_vector; i++) {
7127                 irq_set_affinity_hint(h->intr[i], NULL);
7128                 free_irq(h->intr[i], &h->q[i]);
7129                 h->q[i] = 0;
7130         }
7131         for (; i < MAX_REPLY_QUEUES; i++)
7132                 h->q[i] = 0;
7133 }
7134
7135 /* returns 0 on success; cleans up and returns -Enn on error */
7136 static int hpsa_request_irqs(struct ctlr_info *h,
7137         irqreturn_t (*msixhandler)(int, void *),
7138         irqreturn_t (*intxhandler)(int, void *))
7139 {
7140         int rc, i;
7141
7142         /*
7143          * initialize h->q[x] = x so that interrupt handlers know which
7144          * queue to process.
7145          */
7146         for (i = 0; i < MAX_REPLY_QUEUES; i++)
7147                 h->q[i] = (u8) i;
7148
7149         if (h->intr_mode == PERF_MODE_INT && h->msix_vector > 0) {
7150                 /* If performant mode and MSI-X, use multiple reply queues */
7151                 for (i = 0; i < h->msix_vector; i++) {
7152                         rc = request_irq(h->intr[i], msixhandler,
7153                                         0, h->devname,
7154                                         &h->q[i]);
7155                         if (rc) {
7156                                 int j;
7157
7158                                 dev_err(&h->pdev->dev,
7159                                         "failed to get irq %d for %s\n",
7160                                        h->intr[i], h->devname);
7161                                 for (j = 0; j < i; j++) {
7162                                         free_irq(h->intr[j], &h->q[j]);
7163                                         h->q[j] = 0;
7164                                 }
7165                                 for (; j < MAX_REPLY_QUEUES; j++)
7166                                         h->q[j] = 0;
7167                                 return rc;
7168                         }
7169                 }
7170                 hpsa_irq_affinity_hints(h);
7171         } else {
7172                 /* Use single reply pool */
7173                 if (h->msix_vector > 0 || h->msi_vector) {
7174                         rc = request_irq(h->intr[h->intr_mode],
7175                                 msixhandler, 0, h->devname,
7176                                 &h->q[h->intr_mode]);
7177                 } else {
7178                         rc = request_irq(h->intr[h->intr_mode],
7179                                 intxhandler, IRQF_SHARED, h->devname,
7180                                 &h->q[h->intr_mode]);
7181                 }
7182                 irq_set_affinity_hint(h->intr[h->intr_mode], NULL);
7183         }
7184         if (rc) {
7185                 dev_err(&h->pdev->dev, "failed to get irq %d for %s\n",
7186                        h->intr[h->intr_mode], h->devname);
7187                 hpsa_free_irqs(h);
7188                 return -ENODEV;
7189         }
7190         return 0;
7191 }
7192
7193 static int hpsa_kdump_soft_reset(struct ctlr_info *h)
7194 {
7195         hpsa_send_host_reset(h, RAID_CTLR_LUNID, HPSA_RESET_TYPE_CONTROLLER);
7196
7197         dev_info(&h->pdev->dev, "Waiting for board to soft reset.\n");
7198         if (hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_NOT_READY)) {
7199                 dev_warn(&h->pdev->dev, "Soft reset had no effect.\n");
7200                 return -1;
7201         }
7202
7203         dev_info(&h->pdev->dev, "Board reset, awaiting READY status.\n");
7204         if (hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY)) {
7205                 dev_warn(&h->pdev->dev, "Board failed to become ready "
7206                         "after soft reset.\n");
7207                 return -1;
7208         }
7209
7210         return 0;
7211 }
7212
7213 static void hpsa_free_reply_queues(struct ctlr_info *h)
7214 {
7215         int i;
7216
7217         for (i = 0; i < h->nreply_queues; i++) {
7218                 if (!h->reply_queue[i].head)
7219                         continue;
7220                 pci_free_consistent(h->pdev,
7221                                         h->reply_queue_size,
7222                                         h->reply_queue[i].head,
7223                                         h->reply_queue[i].busaddr);
7224                 h->reply_queue[i].head = NULL;
7225                 h->reply_queue[i].busaddr = 0;
7226         }
7227         h->reply_queue_size = 0;
7228 }
7229
7230 static void hpsa_undo_allocations_after_kdump_soft_reset(struct ctlr_info *h)
7231 {
7232         hpsa_free_performant_mode(h);           /* init_one 7 */
7233         hpsa_free_sg_chain_blocks(h);           /* init_one 6 */
7234         hpsa_free_cmd_pool(h);                  /* init_one 5 */
7235         hpsa_free_irqs(h);                      /* init_one 4 */
7236         hpsa_free_pci_init(h);                  /* init_one 3 */
7237         kfree(h);                               /* init_one 1 */
7238 }
7239
7240 /* Called when controller lockup detected. */
7241 static void fail_all_outstanding_cmds(struct ctlr_info *h)
7242 {
7243         int i, refcount;
7244         struct CommandList *c;
7245         int failcount = 0;
7246
7247         flush_workqueue(h->resubmit_wq); /* ensure all cmds are fully built */
7248         for (i = 0; i < h->nr_cmds; i++) {
7249                 c = h->cmd_pool + i;
7250                 refcount = atomic_inc_return(&c->refcount);
7251                 if (refcount > 1) {
7252                         c->err_info->CommandStatus = CMD_CTLR_LOCKUP;
7253                         finish_cmd(c);
7254                         atomic_dec(&h->commands_outstanding);
7255                         failcount++;
7256                 }
7257                 cmd_free(h, c);
7258         }
7259         dev_warn(&h->pdev->dev,
7260                 "failed %d commands in fail_all\n", failcount);
7261 }
7262
7263 static void set_lockup_detected_for_all_cpus(struct ctlr_info *h, u32 value)
7264 {
7265         int cpu;
7266
7267         for_each_online_cpu(cpu) {
7268                 u32 *lockup_detected;
7269                 lockup_detected = per_cpu_ptr(h->lockup_detected, cpu);
7270                 *lockup_detected = value;
7271         }
7272         wmb(); /* be sure the per-cpu variables are out to memory */
7273 }
7274
7275 static void controller_lockup_detected(struct ctlr_info *h)
7276 {
7277         unsigned long flags;
7278         u32 lockup_detected;
7279
7280         h->access.set_intr_mask(h, HPSA_INTR_OFF);
7281         spin_lock_irqsave(&h->lock, flags);
7282         lockup_detected = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
7283         if (!lockup_detected) {
7284                 /* no heartbeat, but controller gave us a zero. */
7285                 dev_warn(&h->pdev->dev,
7286                         "lockup detected after %d but scratchpad register is zero\n",
7287                         h->heartbeat_sample_interval / HZ);
7288                 lockup_detected = 0xffffffff;
7289         }
7290         set_lockup_detected_for_all_cpus(h, lockup_detected);
7291         spin_unlock_irqrestore(&h->lock, flags);
7292         dev_warn(&h->pdev->dev, "Controller lockup detected: 0x%08x after %d\n",
7293                         lockup_detected, h->heartbeat_sample_interval / HZ);
7294         pci_disable_device(h->pdev);
7295         fail_all_outstanding_cmds(h);
7296 }
7297
7298 static int detect_controller_lockup(struct ctlr_info *h)
7299 {
7300         u64 now;
7301         u32 heartbeat;
7302         unsigned long flags;
7303
7304         now = get_jiffies_64();
7305         /* If we've received an interrupt recently, we're ok. */
7306         if (time_after64(h->last_intr_timestamp +
7307                                 (h->heartbeat_sample_interval), now))
7308                 return false;
7309
7310         /*
7311          * If we've already checked the heartbeat recently, we're ok.
7312          * This could happen if someone sends us a signal. We
7313          * otherwise don't care about signals in this thread.
7314          */
7315         if (time_after64(h->last_heartbeat_timestamp +
7316                                 (h->heartbeat_sample_interval), now))
7317                 return false;
7318
7319         /* If heartbeat has not changed since we last looked, we're not ok. */
7320         spin_lock_irqsave(&h->lock, flags);
7321         heartbeat = readl(&h->cfgtable->HeartBeat);
7322         spin_unlock_irqrestore(&h->lock, flags);
7323         if (h->last_heartbeat == heartbeat) {
7324                 controller_lockup_detected(h);
7325                 return true;
7326         }
7327
7328         /* We're ok. */
7329         h->last_heartbeat = heartbeat;
7330         h->last_heartbeat_timestamp = now;
7331         return false;
7332 }
7333
7334 static void hpsa_ack_ctlr_events(struct ctlr_info *h)
7335 {
7336         int i;
7337         char *event_type;
7338
7339         if (!(h->fw_support & MISC_FW_EVENT_NOTIFY))
7340                 return;
7341
7342         /* Ask the controller to clear the events we're handling. */
7343         if ((h->transMethod & (CFGTBL_Trans_io_accel1
7344                         | CFGTBL_Trans_io_accel2)) &&
7345                 (h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_STATE_CHANGE ||
7346                  h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_CONFIG_CHANGE)) {
7347
7348                 if (h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_STATE_CHANGE)
7349                         event_type = "state change";
7350                 if (h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_CONFIG_CHANGE)
7351                         event_type = "configuration change";
7352                 /* Stop sending new RAID offload reqs via the IO accelerator */
7353                 scsi_block_requests(h->scsi_host);
7354                 for (i = 0; i < h->ndevices; i++)
7355                         h->dev[i]->offload_enabled = 0;
7356                 hpsa_drain_accel_commands(h);
7357                 /* Set 'accelerator path config change' bit */
7358                 dev_warn(&h->pdev->dev,
7359                         "Acknowledging event: 0x%08x (HP SSD Smart Path %s)\n",
7360                         h->events, event_type);
7361                 writel(h->events, &(h->cfgtable->clear_event_notify));
7362                 /* Set the "clear event notify field update" bit 6 */
7363                 writel(DOORBELL_CLEAR_EVENTS, h->vaddr + SA5_DOORBELL);
7364                 /* Wait until ctlr clears 'clear event notify field', bit 6 */
7365                 hpsa_wait_for_clear_event_notify_ack(h);
7366                 scsi_unblock_requests(h->scsi_host);
7367         } else {
7368                 /* Acknowledge controller notification events. */
7369                 writel(h->events, &(h->cfgtable->clear_event_notify));
7370                 writel(DOORBELL_CLEAR_EVENTS, h->vaddr + SA5_DOORBELL);
7371                 hpsa_wait_for_clear_event_notify_ack(h);
7372 #if 0
7373                 writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
7374                 hpsa_wait_for_mode_change_ack(h);
7375 #endif
7376         }
7377         return;
7378 }
7379
7380 /* Check a register on the controller to see if there are configuration
7381  * changes (added/changed/removed logical drives, etc.) which mean that
7382  * we should rescan the controller for devices.
7383  * Also check flag for driver-initiated rescan.
7384  */
7385 static int hpsa_ctlr_needs_rescan(struct ctlr_info *h)
7386 {
7387         if (!(h->fw_support & MISC_FW_EVENT_NOTIFY))
7388                 return 0;
7389
7390         h->events = readl(&(h->cfgtable->event_notify));
7391         return h->events & RESCAN_REQUIRED_EVENT_BITS;
7392 }
7393
7394 /*
7395  * Check if any of the offline devices have become ready
7396  */
7397 static int hpsa_offline_devices_ready(struct ctlr_info *h)
7398 {
7399         unsigned long flags;
7400         struct offline_device_entry *d;
7401         struct list_head *this, *tmp;
7402
7403         spin_lock_irqsave(&h->offline_device_lock, flags);
7404         list_for_each_safe(this, tmp, &h->offline_device_list) {
7405                 d = list_entry(this, struct offline_device_entry,
7406                                 offline_list);
7407                 spin_unlock_irqrestore(&h->offline_device_lock, flags);
7408                 if (!hpsa_volume_offline(h, d->scsi3addr)) {
7409                         spin_lock_irqsave(&h->offline_device_lock, flags);
7410                         list_del(&d->offline_list);
7411                         spin_unlock_irqrestore(&h->offline_device_lock, flags);
7412                         return 1;
7413                 }
7414                 spin_lock_irqsave(&h->offline_device_lock, flags);
7415         }
7416         spin_unlock_irqrestore(&h->offline_device_lock, flags);
7417         return 0;
7418 }
7419
7420 static void hpsa_rescan_ctlr_worker(struct work_struct *work)
7421 {
7422         unsigned long flags;
7423         struct ctlr_info *h = container_of(to_delayed_work(work),
7424                                         struct ctlr_info, rescan_ctlr_work);
7425
7426
7427         if (h->remove_in_progress)
7428                 return;
7429
7430         if (hpsa_ctlr_needs_rescan(h) || hpsa_offline_devices_ready(h)) {
7431                 scsi_host_get(h->scsi_host);
7432                 hpsa_ack_ctlr_events(h);
7433                 hpsa_scan_start(h->scsi_host);
7434                 scsi_host_put(h->scsi_host);
7435         }
7436         spin_lock_irqsave(&h->lock, flags);
7437         if (!h->remove_in_progress)
7438                 queue_delayed_work(h->rescan_ctlr_wq, &h->rescan_ctlr_work,
7439                                 h->heartbeat_sample_interval);
7440         spin_unlock_irqrestore(&h->lock, flags);
7441 }
7442
7443 static void hpsa_monitor_ctlr_worker(struct work_struct *work)
7444 {
7445         unsigned long flags;
7446         struct ctlr_info *h = container_of(to_delayed_work(work),
7447                                         struct ctlr_info, monitor_ctlr_work);
7448
7449         detect_controller_lockup(h);
7450         if (lockup_detected(h))
7451                 return;
7452
7453         spin_lock_irqsave(&h->lock, flags);
7454         if (!h->remove_in_progress)
7455                 schedule_delayed_work(&h->monitor_ctlr_work,
7456                                 h->heartbeat_sample_interval);
7457         spin_unlock_irqrestore(&h->lock, flags);
7458 }
7459
7460 static struct workqueue_struct *hpsa_create_controller_wq(struct ctlr_info *h,
7461                                                 char *name)
7462 {
7463         struct workqueue_struct *wq = NULL;
7464
7465         wq = alloc_ordered_workqueue("%s_%d_hpsa", 0, name, h->ctlr);
7466         if (!wq)
7467                 dev_err(&h->pdev->dev, "failed to create %s workqueue\n", name);
7468
7469         return wq;
7470 }
7471
7472 static int hpsa_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
7473 {
7474         int dac, rc;
7475         struct ctlr_info *h;
7476         int try_soft_reset = 0;
7477         unsigned long flags;
7478         u32 board_id;
7479
7480         if (number_of_controllers == 0)
7481                 printk(KERN_INFO DRIVER_NAME "\n");
7482
7483         rc = hpsa_lookup_board_id(pdev, &board_id);
7484         if (rc < 0) {
7485                 dev_warn(&pdev->dev, "Board ID not found\n");
7486                 return rc;
7487         }
7488
7489         rc = hpsa_init_reset_devices(pdev, board_id);
7490         if (rc) {
7491                 if (rc != -ENOTSUPP)
7492                         return rc;
7493                 /* If the reset fails in a particular way (it has no way to do
7494                  * a proper hard reset, so returns -ENOTSUPP) we can try to do
7495                  * a soft reset once we get the controller configured up to the
7496                  * point that it can accept a command.
7497                  */
7498                 try_soft_reset = 1;
7499                 rc = 0;
7500         }
7501
7502 reinit_after_soft_reset:
7503
7504         /* Command structures must be aligned on a 32-byte boundary because
7505          * the 5 lower bits of the address are used by the hardware. and by
7506          * the driver.  See comments in hpsa.h for more info.
7507          */
7508         BUILD_BUG_ON(sizeof(struct CommandList) % COMMANDLIST_ALIGNMENT);
7509         h = kzalloc(sizeof(*h), GFP_KERNEL);
7510         if (!h) {
7511                 dev_err(&pdev->dev, "Failed to allocate controller head\n");
7512                 return -ENOMEM;
7513         }
7514
7515         h->pdev = pdev;
7516
7517         h->intr_mode = hpsa_simple_mode ? SIMPLE_MODE_INT : PERF_MODE_INT;
7518         INIT_LIST_HEAD(&h->offline_device_list);
7519         spin_lock_init(&h->lock);
7520         spin_lock_init(&h->offline_device_lock);
7521         spin_lock_init(&h->scan_lock);
7522         atomic_set(&h->passthru_cmds_avail, HPSA_MAX_CONCURRENT_PASSTHRUS);
7523         atomic_set(&h->abort_cmds_available, HPSA_CMDS_RESERVED_FOR_ABORTS);
7524
7525         h->rescan_ctlr_wq = hpsa_create_controller_wq(h, "rescan");
7526         if (!h->rescan_ctlr_wq) {
7527                 rc = -ENOMEM;
7528                 goto clean1;
7529         }
7530
7531         h->resubmit_wq = hpsa_create_controller_wq(h, "resubmit");
7532         if (!h->resubmit_wq) {
7533                 rc = -ENOMEM;
7534                 goto clean1;    /* aer/h */
7535         }
7536
7537         /* Allocate and clear per-cpu variable lockup_detected */
7538         h->lockup_detected = alloc_percpu(u32);
7539         if (!h->lockup_detected) {
7540                 dev_err(&h->pdev->dev, "Failed to allocate lockup detector\n");
7541                 rc = -ENOMEM;
7542                 goto clean1;    /* wq/aer/h */
7543         }
7544         set_lockup_detected_for_all_cpus(h, 0);
7545
7546         rc = hpsa_pci_init(h);
7547         if (rc)
7548                 goto clean2;    /* lockup, wq/aer/h */
7549
7550         sprintf(h->devname, HPSA "%d", number_of_controllers);
7551         h->ctlr = number_of_controllers;
7552         number_of_controllers++;
7553
7554         /* configure PCI DMA stuff */
7555         rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
7556         if (rc == 0) {
7557                 dac = 1;
7558         } else {
7559                 rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
7560                 if (rc == 0) {
7561                         dac = 0;
7562                 } else {
7563                         dev_err(&pdev->dev, "no suitable DMA available\n");
7564                         goto clean3;    /* pci, lockup, wq/aer/h */
7565                 }
7566         }
7567
7568         /* make sure the board interrupts are off */
7569         h->access.set_intr_mask(h, HPSA_INTR_OFF);
7570
7571         rc = hpsa_request_irqs(h, do_hpsa_intr_msi, do_hpsa_intr_intx);
7572         if (rc)
7573                 goto clean3;    /* pci, lockup, wq/aer/h */
7574         dev_info(&pdev->dev, "%s: <0x%x> at IRQ %d%s using DAC\n",
7575                h->devname, pdev->device,
7576                h->intr[h->intr_mode], dac ? "" : " not");
7577         rc = hpsa_alloc_cmd_pool(h);
7578         if (rc)
7579                 goto clean4;    /* irq, pci, lockup, wq/aer/h */
7580         rc = hpsa_alloc_sg_chain_blocks(h);
7581         if (rc)
7582                 goto clean5;    /* cmd, irq, pci, lockup, wq/aer/h */
7583         init_waitqueue_head(&h->scan_wait_queue);
7584         init_waitqueue_head(&h->abort_cmd_wait_queue);
7585         h->scan_finished = 1; /* no scan currently in progress */
7586
7587         pci_set_drvdata(pdev, h);
7588         h->ndevices = 0;
7589         h->hba_mode_enabled = 0;
7590         h->scsi_host = NULL;
7591         spin_lock_init(&h->devlock);
7592         rc = hpsa_put_ctlr_into_performant_mode(h);
7593         if (rc)
7594                 goto clean6;    /* sg, cmd, irq, pci, lockup, wq/aer/h */
7595
7596         /*
7597          * At this point, the controller is ready to take commands.
7598          * Now, if reset_devices and the hard reset didn't work, try
7599          * the soft reset and see if that works.
7600          */
7601         if (try_soft_reset) {
7602
7603                 /* This is kind of gross.  We may or may not get a completion
7604                  * from the soft reset command, and if we do, then the value
7605                  * from the fifo may or may not be valid.  So, we wait 10 secs
7606                  * after the reset throwing away any completions we get during
7607                  * that time.  Unregister the interrupt handler and register
7608                  * fake ones to scoop up any residual completions.
7609                  */
7610                 spin_lock_irqsave(&h->lock, flags);
7611                 h->access.set_intr_mask(h, HPSA_INTR_OFF);
7612                 spin_unlock_irqrestore(&h->lock, flags);
7613                 hpsa_free_irqs(h);
7614                 rc = hpsa_request_irqs(h, hpsa_msix_discard_completions,
7615                                         hpsa_intx_discard_completions);
7616                 if (rc) {
7617                         dev_warn(&h->pdev->dev,
7618                                 "Failed to request_irq after soft reset.\n");
7619                         goto clean4;
7620                 }
7621
7622                 rc = hpsa_kdump_soft_reset(h);
7623                 if (rc)
7624                         /* Neither hard nor soft reset worked, we're hosed. */
7625                         goto clean4;
7626
7627                 dev_info(&h->pdev->dev, "Board READY.\n");
7628                 dev_info(&h->pdev->dev,
7629                         "Waiting for stale completions to drain.\n");
7630                 h->access.set_intr_mask(h, HPSA_INTR_ON);
7631                 msleep(10000);
7632                 h->access.set_intr_mask(h, HPSA_INTR_OFF);
7633
7634                 rc = controller_reset_failed(h->cfgtable);
7635                 if (rc)
7636                         dev_info(&h->pdev->dev,
7637                                 "Soft reset appears to have failed.\n");
7638
7639                 /* since the controller's reset, we have to go back and re-init
7640                  * everything.  Easiest to just forget what we've done and do it
7641                  * all over again.
7642                  */
7643                 hpsa_undo_allocations_after_kdump_soft_reset(h);
7644                 try_soft_reset = 0;
7645                 if (rc)
7646                         /* don't go to clean4, we already unallocated */
7647                         return -ENODEV;
7648
7649                 goto reinit_after_soft_reset;
7650         }
7651
7652         /* Enable Accelerated IO path at driver layer */
7653         h->acciopath_status = 1;
7654
7655
7656         /* Turn the interrupts on so we can service requests */
7657         h->access.set_intr_mask(h, HPSA_INTR_ON);
7658
7659         hpsa_hba_inquiry(h);
7660         rc = hpsa_register_scsi(h);     /* hook ourselves into SCSI subsystem */
7661         if (rc)
7662                 goto clean7;
7663
7664         /* Monitor the controller for firmware lockups */
7665         h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
7666         INIT_DELAYED_WORK(&h->monitor_ctlr_work, hpsa_monitor_ctlr_worker);
7667         schedule_delayed_work(&h->monitor_ctlr_work,
7668                                 h->heartbeat_sample_interval);
7669         INIT_DELAYED_WORK(&h->rescan_ctlr_work, hpsa_rescan_ctlr_worker);
7670         queue_delayed_work(h->rescan_ctlr_wq, &h->rescan_ctlr_work,
7671                                 h->heartbeat_sample_interval);
7672         return 0;
7673
7674 clean7: /* perf, sg, cmd, irq, pci, lockup, wq/aer/h */
7675         kfree(h->hba_inquiry_data);
7676         hpsa_free_performant_mode(h);
7677         h->access.set_intr_mask(h, HPSA_INTR_OFF);
7678 clean6: /* sg, cmd, irq, pci, lockup, wq/aer/h */
7679         hpsa_free_sg_chain_blocks(h);
7680 clean5: /* cmd, irq, pci, lockup, wq/aer/h */
7681         hpsa_free_cmd_pool(h);
7682 clean4: /* irq, pci, lockup, wq/aer/h */
7683         hpsa_free_irqs(h);
7684 clean3: /* pci, lockup, wq/aer/h */
7685         hpsa_free_pci_init(h);
7686 clean2: /* lockup, wq/aer/h */
7687         if (h->lockup_detected) {
7688                 free_percpu(h->lockup_detected);
7689                 h->lockup_detected = NULL;
7690         }
7691 clean1: /* wq/aer/h */
7692         if (h->resubmit_wq) {
7693                 destroy_workqueue(h->resubmit_wq);
7694                 h->resubmit_wq = NULL;
7695         }
7696         if (h->rescan_ctlr_wq) {
7697                 destroy_workqueue(h->rescan_ctlr_wq);
7698                 h->rescan_ctlr_wq = NULL;
7699         }
7700         kfree(h);
7701         return rc;
7702 }
7703
7704 static void hpsa_flush_cache(struct ctlr_info *h)
7705 {
7706         char *flush_buf;
7707         struct CommandList *c;
7708         int rc;
7709
7710         if (unlikely(lockup_detected(h)))
7711                 return;
7712         flush_buf = kzalloc(4, GFP_KERNEL);
7713         if (!flush_buf)
7714                 return;
7715
7716         c = cmd_alloc(h);
7717
7718         if (fill_cmd(c, HPSA_CACHE_FLUSH, h, flush_buf, 4, 0,
7719                 RAID_CTLR_LUNID, TYPE_CMD)) {
7720                 goto out;
7721         }
7722         rc = hpsa_scsi_do_simple_cmd_with_retry(h, c,
7723                                         PCI_DMA_TODEVICE, NO_TIMEOUT);
7724         if (rc)
7725                 goto out;
7726         if (c->err_info->CommandStatus != 0)
7727 out:
7728                 dev_warn(&h->pdev->dev,
7729                         "error flushing cache on controller\n");
7730         cmd_free(h, c);
7731         kfree(flush_buf);
7732 }
7733
7734 static void hpsa_shutdown(struct pci_dev *pdev)
7735 {
7736         struct ctlr_info *h;
7737
7738         h = pci_get_drvdata(pdev);
7739         /* Turn board interrupts off  and send the flush cache command
7740          * sendcmd will turn off interrupt, and send the flush...
7741          * To write all data in the battery backed cache to disks
7742          */
7743         hpsa_flush_cache(h);
7744         h->access.set_intr_mask(h, HPSA_INTR_OFF);
7745         hpsa_free_irqs(h);                      /* init_one 4 */
7746         hpsa_disable_interrupt_mode(h);         /* pci_init 2 */
7747 }
7748
7749 static void hpsa_free_device_info(struct ctlr_info *h)
7750 {
7751         int i;
7752
7753         for (i = 0; i < h->ndevices; i++) {
7754                 kfree(h->dev[i]);
7755                 h->dev[i] = NULL;
7756         }
7757 }
7758
7759 static void hpsa_remove_one(struct pci_dev *pdev)
7760 {
7761         struct ctlr_info *h;
7762         unsigned long flags;
7763
7764         if (pci_get_drvdata(pdev) == NULL) {
7765                 dev_err(&pdev->dev, "unable to remove device\n");
7766                 return;
7767         }
7768         h = pci_get_drvdata(pdev);
7769
7770         /* Get rid of any controller monitoring work items */
7771         spin_lock_irqsave(&h->lock, flags);
7772         h->remove_in_progress = 1;
7773         spin_unlock_irqrestore(&h->lock, flags);
7774         cancel_delayed_work_sync(&h->monitor_ctlr_work);
7775         cancel_delayed_work_sync(&h->rescan_ctlr_work);
7776         destroy_workqueue(h->rescan_ctlr_wq);
7777         destroy_workqueue(h->resubmit_wq);
7778
7779         /* includes hpsa_free_irqs - init_one 4 */
7780         /* includes hpsa_disable_interrupt_mode - pci_init 2 */
7781         hpsa_shutdown(pdev);
7782
7783         hpsa_free_device_info(h);               /* scan */
7784
7785         hpsa_unregister_scsi(h);                        /* init_one "8" */
7786         kfree(h->hba_inquiry_data);                     /* init_one "8" */
7787         h->hba_inquiry_data = NULL;                     /* init_one "8" */
7788         hpsa_free_performant_mode(h);                   /* init_one 7 */
7789         hpsa_free_sg_chain_blocks(h);                   /* init_one 6 */
7790         hpsa_free_cmd_pool(h);                          /* init_one 5 */
7791
7792         /* hpsa_free_irqs already called via hpsa_shutdown init_one 4 */
7793
7794         /* includes hpsa_disable_interrupt_mode - pci_init 2 */
7795         hpsa_free_pci_init(h);                          /* init_one 3 */
7796
7797         free_percpu(h->lockup_detected);                /* init_one 2 */
7798         h->lockup_detected = NULL;                      /* init_one 2 */
7799         /* (void) pci_disable_pcie_error_reporting(pdev); */    /* init_one 1 */
7800         kfree(h);                                       /* init_one 1 */
7801 }
7802
7803 static int hpsa_suspend(__attribute__((unused)) struct pci_dev *pdev,
7804         __attribute__((unused)) pm_message_t state)
7805 {
7806         return -ENOSYS;
7807 }
7808
7809 static int hpsa_resume(__attribute__((unused)) struct pci_dev *pdev)
7810 {
7811         return -ENOSYS;
7812 }
7813
7814 static struct pci_driver hpsa_pci_driver = {
7815         .name = HPSA,
7816         .probe = hpsa_init_one,
7817         .remove = hpsa_remove_one,
7818         .id_table = hpsa_pci_device_id, /* id_table */
7819         .shutdown = hpsa_shutdown,
7820         .suspend = hpsa_suspend,
7821         .resume = hpsa_resume,
7822 };
7823
7824 /* Fill in bucket_map[], given nsgs (the max number of
7825  * scatter gather elements supported) and bucket[],
7826  * which is an array of 8 integers.  The bucket[] array
7827  * contains 8 different DMA transfer sizes (in 16
7828  * byte increments) which the controller uses to fetch
7829  * commands.  This function fills in bucket_map[], which
7830  * maps a given number of scatter gather elements to one of
7831  * the 8 DMA transfer sizes.  The point of it is to allow the
7832  * controller to only do as much DMA as needed to fetch the
7833  * command, with the DMA transfer size encoded in the lower
7834  * bits of the command address.
7835  */
7836 static void  calc_bucket_map(int bucket[], int num_buckets,
7837         int nsgs, int min_blocks, u32 *bucket_map)
7838 {
7839         int i, j, b, size;
7840
7841         /* Note, bucket_map must have nsgs+1 entries. */
7842         for (i = 0; i <= nsgs; i++) {
7843                 /* Compute size of a command with i SG entries */
7844                 size = i + min_blocks;
7845                 b = num_buckets; /* Assume the biggest bucket */
7846                 /* Find the bucket that is just big enough */
7847                 for (j = 0; j < num_buckets; j++) {
7848                         if (bucket[j] >= size) {
7849                                 b = j;
7850                                 break;
7851                         }
7852                 }
7853                 /* for a command with i SG entries, use bucket b. */
7854                 bucket_map[i] = b;
7855         }
7856 }
7857
7858 /*
7859  * return -ENODEV on err, 0 on success (or no action)
7860  * allocates numerous items that must be freed later
7861  */
7862 static int hpsa_enter_performant_mode(struct ctlr_info *h, u32 trans_support)
7863 {
7864         int i;
7865         unsigned long register_value;
7866         unsigned long transMethod = CFGTBL_Trans_Performant |
7867                         (trans_support & CFGTBL_Trans_use_short_tags) |
7868                                 CFGTBL_Trans_enable_directed_msix |
7869                         (trans_support & (CFGTBL_Trans_io_accel1 |
7870                                 CFGTBL_Trans_io_accel2));
7871         struct access_method access = SA5_performant_access;
7872
7873         /* This is a bit complicated.  There are 8 registers on
7874          * the controller which we write to to tell it 8 different
7875          * sizes of commands which there may be.  It's a way of
7876          * reducing the DMA done to fetch each command.  Encoded into
7877          * each command's tag are 3 bits which communicate to the controller
7878          * which of the eight sizes that command fits within.  The size of
7879          * each command depends on how many scatter gather entries there are.
7880          * Each SG entry requires 16 bytes.  The eight registers are programmed
7881          * with the number of 16-byte blocks a command of that size requires.
7882          * The smallest command possible requires 5 such 16 byte blocks.
7883          * the largest command possible requires SG_ENTRIES_IN_CMD + 4 16-byte
7884          * blocks.  Note, this only extends to the SG entries contained
7885          * within the command block, and does not extend to chained blocks
7886          * of SG elements.   bft[] contains the eight values we write to
7887          * the registers.  They are not evenly distributed, but have more
7888          * sizes for small commands, and fewer sizes for larger commands.
7889          */
7890         int bft[8] = {5, 6, 8, 10, 12, 20, 28, SG_ENTRIES_IN_CMD + 4};
7891 #define MIN_IOACCEL2_BFT_ENTRY 5
7892 #define HPSA_IOACCEL2_HEADER_SZ 4
7893         int bft2[16] = {MIN_IOACCEL2_BFT_ENTRY, 6, 7, 8, 9, 10, 11, 12,
7894                         13, 14, 15, 16, 17, 18, 19,
7895                         HPSA_IOACCEL2_HEADER_SZ + IOACCEL2_MAXSGENTRIES};
7896         BUILD_BUG_ON(ARRAY_SIZE(bft2) != 16);
7897         BUILD_BUG_ON(ARRAY_SIZE(bft) != 8);
7898         BUILD_BUG_ON(offsetof(struct io_accel2_cmd, sg) >
7899                                  16 * MIN_IOACCEL2_BFT_ENTRY);
7900         BUILD_BUG_ON(sizeof(struct ioaccel2_sg_element) != 16);
7901         BUILD_BUG_ON(28 > SG_ENTRIES_IN_CMD + 4);
7902         /*  5 = 1 s/g entry or 4k
7903          *  6 = 2 s/g entry or 8k
7904          *  8 = 4 s/g entry or 16k
7905          * 10 = 6 s/g entry or 24k
7906          */
7907
7908         /* If the controller supports either ioaccel method then
7909          * we can also use the RAID stack submit path that does not
7910          * perform the superfluous readl() after each command submission.
7911          */
7912         if (trans_support & (CFGTBL_Trans_io_accel1 | CFGTBL_Trans_io_accel2))
7913                 access = SA5_performant_access_no_read;
7914
7915         /* Controller spec: zero out this buffer. */
7916         for (i = 0; i < h->nreply_queues; i++)
7917                 memset(h->reply_queue[i].head, 0, h->reply_queue_size);
7918
7919         bft[7] = SG_ENTRIES_IN_CMD + 4;
7920         calc_bucket_map(bft, ARRAY_SIZE(bft),
7921                                 SG_ENTRIES_IN_CMD, 4, h->blockFetchTable);
7922         for (i = 0; i < 8; i++)
7923                 writel(bft[i], &h->transtable->BlockFetch[i]);
7924
7925         /* size of controller ring buffer */
7926         writel(h->max_commands, &h->transtable->RepQSize);
7927         writel(h->nreply_queues, &h->transtable->RepQCount);
7928         writel(0, &h->transtable->RepQCtrAddrLow32);
7929         writel(0, &h->transtable->RepQCtrAddrHigh32);
7930
7931         for (i = 0; i < h->nreply_queues; i++) {
7932                 writel(0, &h->transtable->RepQAddr[i].upper);
7933                 writel(h->reply_queue[i].busaddr,
7934                         &h->transtable->RepQAddr[i].lower);
7935         }
7936
7937         writel(0, &h->cfgtable->HostWrite.command_pool_addr_hi);
7938         writel(transMethod, &(h->cfgtable->HostWrite.TransportRequest));
7939         /*
7940          * enable outbound interrupt coalescing in accelerator mode;
7941          */
7942         if (trans_support & CFGTBL_Trans_io_accel1) {
7943                 access = SA5_ioaccel_mode1_access;
7944                 writel(10, &h->cfgtable->HostWrite.CoalIntDelay);
7945                 writel(4, &h->cfgtable->HostWrite.CoalIntCount);
7946         } else {
7947                 if (trans_support & CFGTBL_Trans_io_accel2) {
7948                         access = SA5_ioaccel_mode2_access;
7949                         writel(10, &h->cfgtable->HostWrite.CoalIntDelay);
7950                         writel(4, &h->cfgtable->HostWrite.CoalIntCount);
7951                 }
7952         }
7953         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
7954         if (hpsa_wait_for_mode_change_ack(h)) {
7955                 dev_err(&h->pdev->dev,
7956                         "performant mode problem - doorbell timeout\n");
7957                 return -ENODEV;
7958         }
7959         register_value = readl(&(h->cfgtable->TransportActive));
7960         if (!(register_value & CFGTBL_Trans_Performant)) {
7961                 dev_err(&h->pdev->dev,
7962                         "performant mode problem - transport not active\n");
7963                 return -ENODEV;
7964         }
7965         /* Change the access methods to the performant access methods */
7966         h->access = access;
7967         h->transMethod = transMethod;
7968
7969         if (!((trans_support & CFGTBL_Trans_io_accel1) ||
7970                 (trans_support & CFGTBL_Trans_io_accel2)))
7971                 return 0;
7972
7973         if (trans_support & CFGTBL_Trans_io_accel1) {
7974                 /* Set up I/O accelerator mode */
7975                 for (i = 0; i < h->nreply_queues; i++) {
7976                         writel(i, h->vaddr + IOACCEL_MODE1_REPLY_QUEUE_INDEX);
7977                         h->reply_queue[i].current_entry =
7978                                 readl(h->vaddr + IOACCEL_MODE1_PRODUCER_INDEX);
7979                 }
7980                 bft[7] = h->ioaccel_maxsg + 8;
7981                 calc_bucket_map(bft, ARRAY_SIZE(bft), h->ioaccel_maxsg, 8,
7982                                 h->ioaccel1_blockFetchTable);
7983
7984                 /* initialize all reply queue entries to unused */
7985                 for (i = 0; i < h->nreply_queues; i++)
7986                         memset(h->reply_queue[i].head,
7987                                 (u8) IOACCEL_MODE1_REPLY_UNUSED,
7988                                 h->reply_queue_size);
7989
7990                 /* set all the constant fields in the accelerator command
7991                  * frames once at init time to save CPU cycles later.
7992                  */
7993                 for (i = 0; i < h->nr_cmds; i++) {
7994                         struct io_accel1_cmd *cp = &h->ioaccel_cmd_pool[i];
7995
7996                         cp->function = IOACCEL1_FUNCTION_SCSIIO;
7997                         cp->err_info = (u32) (h->errinfo_pool_dhandle +
7998                                         (i * sizeof(struct ErrorInfo)));
7999                         cp->err_info_len = sizeof(struct ErrorInfo);
8000                         cp->sgl_offset = IOACCEL1_SGLOFFSET;
8001                         cp->host_context_flags =
8002                                 cpu_to_le16(IOACCEL1_HCFLAGS_CISS_FORMAT);
8003                         cp->timeout_sec = 0;
8004                         cp->ReplyQueue = 0;
8005                         cp->tag =
8006                                 cpu_to_le64((i << DIRECT_LOOKUP_SHIFT));
8007                         cp->host_addr =
8008                                 cpu_to_le64(h->ioaccel_cmd_pool_dhandle +
8009                                         (i * sizeof(struct io_accel1_cmd)));
8010                 }
8011         } else if (trans_support & CFGTBL_Trans_io_accel2) {
8012                 u64 cfg_offset, cfg_base_addr_index;
8013                 u32 bft2_offset, cfg_base_addr;
8014                 int rc;
8015
8016                 rc = hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
8017                         &cfg_base_addr_index, &cfg_offset);
8018                 BUILD_BUG_ON(offsetof(struct io_accel2_cmd, sg) != 64);
8019                 bft2[15] = h->ioaccel_maxsg + HPSA_IOACCEL2_HEADER_SZ;
8020                 calc_bucket_map(bft2, ARRAY_SIZE(bft2), h->ioaccel_maxsg,
8021                                 4, h->ioaccel2_blockFetchTable);
8022                 bft2_offset = readl(&h->cfgtable->io_accel_request_size_offset);
8023                 BUILD_BUG_ON(offsetof(struct CfgTable,
8024                                 io_accel_request_size_offset) != 0xb8);
8025                 h->ioaccel2_bft2_regs =
8026                         remap_pci_mem(pci_resource_start(h->pdev,
8027                                         cfg_base_addr_index) +
8028                                         cfg_offset + bft2_offset,
8029                                         ARRAY_SIZE(bft2) *
8030                                         sizeof(*h->ioaccel2_bft2_regs));
8031                 for (i = 0; i < ARRAY_SIZE(bft2); i++)
8032                         writel(bft2[i], &h->ioaccel2_bft2_regs[i]);
8033         }
8034         writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
8035         if (hpsa_wait_for_mode_change_ack(h)) {
8036                 dev_err(&h->pdev->dev,
8037                         "performant mode problem - enabling ioaccel mode\n");
8038                 return -ENODEV;
8039         }
8040         return 0;
8041 }
8042
8043 /* Free ioaccel1 mode command blocks and block fetch table */
8044 static void hpsa_free_ioaccel1_cmd_and_bft(struct ctlr_info *h)
8045 {
8046         if (h->ioaccel_cmd_pool) {
8047                 pci_free_consistent(h->pdev,
8048                         h->nr_cmds * sizeof(*h->ioaccel_cmd_pool),
8049                         h->ioaccel_cmd_pool,
8050                         h->ioaccel_cmd_pool_dhandle);
8051                 h->ioaccel_cmd_pool = NULL;
8052                 h->ioaccel_cmd_pool_dhandle = 0;
8053         }
8054         kfree(h->ioaccel1_blockFetchTable);
8055         h->ioaccel1_blockFetchTable = NULL;
8056 }
8057
8058 /* Allocate ioaccel1 mode command blocks and block fetch table */
8059 static int hpsa_alloc_ioaccel1_cmd_and_bft(struct ctlr_info *h)
8060 {
8061         h->ioaccel_maxsg =
8062                 readl(&(h->cfgtable->io_accel_max_embedded_sg_count));
8063         if (h->ioaccel_maxsg > IOACCEL1_MAXSGENTRIES)
8064                 h->ioaccel_maxsg = IOACCEL1_MAXSGENTRIES;
8065
8066         /* Command structures must be aligned on a 128-byte boundary
8067          * because the 7 lower bits of the address are used by the
8068          * hardware.
8069          */
8070         BUILD_BUG_ON(sizeof(struct io_accel1_cmd) %
8071                         IOACCEL1_COMMANDLIST_ALIGNMENT);
8072         h->ioaccel_cmd_pool =
8073                 pci_alloc_consistent(h->pdev,
8074                         h->nr_cmds * sizeof(*h->ioaccel_cmd_pool),
8075                         &(h->ioaccel_cmd_pool_dhandle));
8076
8077         h->ioaccel1_blockFetchTable =
8078                 kmalloc(((h->ioaccel_maxsg + 1) *
8079                                 sizeof(u32)), GFP_KERNEL);
8080
8081         if ((h->ioaccel_cmd_pool == NULL) ||
8082                 (h->ioaccel1_blockFetchTable == NULL))
8083                 goto clean_up;
8084
8085         memset(h->ioaccel_cmd_pool, 0,
8086                 h->nr_cmds * sizeof(*h->ioaccel_cmd_pool));
8087         return 0;
8088
8089 clean_up:
8090         hpsa_free_ioaccel1_cmd_and_bft(h);
8091         return -ENOMEM;
8092 }
8093
8094 /* Free ioaccel2 mode command blocks and block fetch table */
8095 static void hpsa_free_ioaccel2_cmd_and_bft(struct ctlr_info *h)
8096 {
8097         hpsa_free_ioaccel2_sg_chain_blocks(h);
8098
8099         if (h->ioaccel2_cmd_pool) {
8100                 pci_free_consistent(h->pdev,
8101                         h->nr_cmds * sizeof(*h->ioaccel2_cmd_pool),
8102                         h->ioaccel2_cmd_pool,
8103                         h->ioaccel2_cmd_pool_dhandle);
8104                 h->ioaccel2_cmd_pool = NULL;
8105                 h->ioaccel2_cmd_pool_dhandle = 0;
8106         }
8107         kfree(h->ioaccel2_blockFetchTable);
8108         h->ioaccel2_blockFetchTable = NULL;
8109 }
8110
8111 /* Allocate ioaccel2 mode command blocks and block fetch table */
8112 static int hpsa_alloc_ioaccel2_cmd_and_bft(struct ctlr_info *h)
8113 {
8114         int rc;
8115
8116         /* Allocate ioaccel2 mode command blocks and block fetch table */
8117
8118         h->ioaccel_maxsg =
8119                 readl(&(h->cfgtable->io_accel_max_embedded_sg_count));
8120         if (h->ioaccel_maxsg > IOACCEL2_MAXSGENTRIES)
8121                 h->ioaccel_maxsg = IOACCEL2_MAXSGENTRIES;
8122
8123         BUILD_BUG_ON(sizeof(struct io_accel2_cmd) %
8124                         IOACCEL2_COMMANDLIST_ALIGNMENT);
8125         h->ioaccel2_cmd_pool =
8126                 pci_alloc_consistent(h->pdev,
8127                         h->nr_cmds * sizeof(*h->ioaccel2_cmd_pool),
8128                         &(h->ioaccel2_cmd_pool_dhandle));
8129
8130         h->ioaccel2_blockFetchTable =
8131                 kmalloc(((h->ioaccel_maxsg + 1) *
8132                                 sizeof(u32)), GFP_KERNEL);
8133
8134         if ((h->ioaccel2_cmd_pool == NULL) ||
8135                 (h->ioaccel2_blockFetchTable == NULL)) {
8136                 rc = -ENOMEM;
8137                 goto clean_up;
8138         }
8139
8140         rc = hpsa_allocate_ioaccel2_sg_chain_blocks(h);
8141         if (rc)
8142                 goto clean_up;
8143
8144         memset(h->ioaccel2_cmd_pool, 0,
8145                 h->nr_cmds * sizeof(*h->ioaccel2_cmd_pool));
8146         return 0;
8147
8148 clean_up:
8149         hpsa_free_ioaccel2_cmd_and_bft(h);
8150         return rc;
8151 }
8152
8153 /* Free items allocated by hpsa_put_ctlr_into_performant_mode */
8154 static void hpsa_free_performant_mode(struct ctlr_info *h)
8155 {
8156         kfree(h->blockFetchTable);
8157         h->blockFetchTable = NULL;
8158         hpsa_free_reply_queues(h);
8159         hpsa_free_ioaccel1_cmd_and_bft(h);
8160         hpsa_free_ioaccel2_cmd_and_bft(h);
8161 }
8162
8163 /* return -ENODEV on error, 0 on success (or no action)
8164  * allocates numerous items that must be freed later
8165  */
8166 static int hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h)
8167 {
8168         u32 trans_support;
8169         unsigned long transMethod = CFGTBL_Trans_Performant |
8170                                         CFGTBL_Trans_use_short_tags;
8171         int i, rc;
8172
8173         if (hpsa_simple_mode)
8174                 return 0;
8175
8176         trans_support = readl(&(h->cfgtable->TransportSupport));
8177         if (!(trans_support & PERFORMANT_MODE))
8178                 return 0;
8179
8180         /* Check for I/O accelerator mode support */
8181         if (trans_support & CFGTBL_Trans_io_accel1) {
8182                 transMethod |= CFGTBL_Trans_io_accel1 |
8183                                 CFGTBL_Trans_enable_directed_msix;
8184                 rc = hpsa_alloc_ioaccel1_cmd_and_bft(h);
8185                 if (rc)
8186                         return rc;
8187         } else if (trans_support & CFGTBL_Trans_io_accel2) {
8188                 transMethod |= CFGTBL_Trans_io_accel2 |
8189                                 CFGTBL_Trans_enable_directed_msix;
8190                 rc = hpsa_alloc_ioaccel2_cmd_and_bft(h);
8191                 if (rc)
8192                         return rc;
8193         }
8194
8195         h->nreply_queues = h->msix_vector > 0 ? h->msix_vector : 1;
8196         hpsa_get_max_perf_mode_cmds(h);
8197         /* Performant mode ring buffer and supporting data structures */
8198         h->reply_queue_size = h->max_commands * sizeof(u64);
8199
8200         for (i = 0; i < h->nreply_queues; i++) {
8201                 h->reply_queue[i].head = pci_alloc_consistent(h->pdev,
8202                                                 h->reply_queue_size,
8203                                                 &(h->reply_queue[i].busaddr));
8204                 if (!h->reply_queue[i].head) {
8205                         rc = -ENOMEM;
8206                         goto clean1;    /* rq, ioaccel */
8207                 }
8208                 h->reply_queue[i].size = h->max_commands;
8209                 h->reply_queue[i].wraparound = 1;  /* spec: init to 1 */
8210                 h->reply_queue[i].current_entry = 0;
8211         }
8212
8213         /* Need a block fetch table for performant mode */
8214         h->blockFetchTable = kmalloc(((SG_ENTRIES_IN_CMD + 1) *
8215                                 sizeof(u32)), GFP_KERNEL);
8216         if (!h->blockFetchTable) {
8217                 rc = -ENOMEM;
8218                 goto clean1;    /* rq, ioaccel */
8219         }
8220
8221         rc = hpsa_enter_performant_mode(h, trans_support);
8222         if (rc)
8223                 goto clean2;    /* bft, rq, ioaccel */
8224         return 0;
8225
8226 clean2: /* bft, rq, ioaccel */
8227         kfree(h->blockFetchTable);
8228         h->blockFetchTable = NULL;
8229 clean1: /* rq, ioaccel */
8230         hpsa_free_reply_queues(h);
8231         hpsa_free_ioaccel1_cmd_and_bft(h);
8232         hpsa_free_ioaccel2_cmd_and_bft(h);
8233         return rc;
8234 }
8235
8236 static int is_accelerated_cmd(struct CommandList *c)
8237 {
8238         return c->cmd_type == CMD_IOACCEL1 || c->cmd_type == CMD_IOACCEL2;
8239 }
8240
8241 static void hpsa_drain_accel_commands(struct ctlr_info *h)
8242 {
8243         struct CommandList *c = NULL;
8244         int i, accel_cmds_out;
8245         int refcount;
8246
8247         do { /* wait for all outstanding ioaccel commands to drain out */
8248                 accel_cmds_out = 0;
8249                 for (i = 0; i < h->nr_cmds; i++) {
8250                         c = h->cmd_pool + i;
8251                         refcount = atomic_inc_return(&c->refcount);
8252                         if (refcount > 1) /* Command is allocated */
8253                                 accel_cmds_out += is_accelerated_cmd(c);
8254                         cmd_free(h, c);
8255                 }
8256                 if (accel_cmds_out <= 0)
8257                         break;
8258                 msleep(100);
8259         } while (1);
8260 }
8261
8262 /*
8263  *  This is it.  Register the PCI driver information for the cards we control
8264  *  the OS will call our registered routines when it finds one of our cards.
8265  */
8266 static int __init hpsa_init(void)
8267 {
8268         return pci_register_driver(&hpsa_pci_driver);
8269 }
8270
8271 static void __exit hpsa_cleanup(void)
8272 {
8273         pci_unregister_driver(&hpsa_pci_driver);
8274 }
8275
8276 static void __attribute__((unused)) verify_offsets(void)
8277 {
8278 #define VERIFY_OFFSET(member, offset) \
8279         BUILD_BUG_ON(offsetof(struct raid_map_data, member) != offset)
8280
8281         VERIFY_OFFSET(structure_size, 0);
8282         VERIFY_OFFSET(volume_blk_size, 4);
8283         VERIFY_OFFSET(volume_blk_cnt, 8);
8284         VERIFY_OFFSET(phys_blk_shift, 16);
8285         VERIFY_OFFSET(parity_rotation_shift, 17);
8286         VERIFY_OFFSET(strip_size, 18);
8287         VERIFY_OFFSET(disk_starting_blk, 20);
8288         VERIFY_OFFSET(disk_blk_cnt, 28);
8289         VERIFY_OFFSET(data_disks_per_row, 36);
8290         VERIFY_OFFSET(metadata_disks_per_row, 38);
8291         VERIFY_OFFSET(row_cnt, 40);
8292         VERIFY_OFFSET(layout_map_count, 42);
8293         VERIFY_OFFSET(flags, 44);
8294         VERIFY_OFFSET(dekindex, 46);
8295         /* VERIFY_OFFSET(reserved, 48 */
8296         VERIFY_OFFSET(data, 64);
8297
8298 #undef VERIFY_OFFSET
8299
8300 #define VERIFY_OFFSET(member, offset) \
8301         BUILD_BUG_ON(offsetof(struct io_accel2_cmd, member) != offset)
8302
8303         VERIFY_OFFSET(IU_type, 0);
8304         VERIFY_OFFSET(direction, 1);
8305         VERIFY_OFFSET(reply_queue, 2);
8306         /* VERIFY_OFFSET(reserved1, 3);  */
8307         VERIFY_OFFSET(scsi_nexus, 4);
8308         VERIFY_OFFSET(Tag, 8);
8309         VERIFY_OFFSET(cdb, 16);
8310         VERIFY_OFFSET(cciss_lun, 32);
8311         VERIFY_OFFSET(data_len, 40);
8312         VERIFY_OFFSET(cmd_priority_task_attr, 44);
8313         VERIFY_OFFSET(sg_count, 45);
8314         /* VERIFY_OFFSET(reserved3 */
8315         VERIFY_OFFSET(err_ptr, 48);
8316         VERIFY_OFFSET(err_len, 56);
8317         /* VERIFY_OFFSET(reserved4  */
8318         VERIFY_OFFSET(sg, 64);
8319
8320 #undef VERIFY_OFFSET
8321
8322 #define VERIFY_OFFSET(member, offset) \
8323         BUILD_BUG_ON(offsetof(struct io_accel1_cmd, member) != offset)
8324
8325         VERIFY_OFFSET(dev_handle, 0x00);
8326         VERIFY_OFFSET(reserved1, 0x02);
8327         VERIFY_OFFSET(function, 0x03);
8328         VERIFY_OFFSET(reserved2, 0x04);
8329         VERIFY_OFFSET(err_info, 0x0C);
8330         VERIFY_OFFSET(reserved3, 0x10);
8331         VERIFY_OFFSET(err_info_len, 0x12);
8332         VERIFY_OFFSET(reserved4, 0x13);
8333         VERIFY_OFFSET(sgl_offset, 0x14);
8334         VERIFY_OFFSET(reserved5, 0x15);
8335         VERIFY_OFFSET(transfer_len, 0x1C);
8336         VERIFY_OFFSET(reserved6, 0x20);
8337         VERIFY_OFFSET(io_flags, 0x24);
8338         VERIFY_OFFSET(reserved7, 0x26);
8339         VERIFY_OFFSET(LUN, 0x34);
8340         VERIFY_OFFSET(control, 0x3C);
8341         VERIFY_OFFSET(CDB, 0x40);
8342         VERIFY_OFFSET(reserved8, 0x50);
8343         VERIFY_OFFSET(host_context_flags, 0x60);
8344         VERIFY_OFFSET(timeout_sec, 0x62);
8345         VERIFY_OFFSET(ReplyQueue, 0x64);
8346         VERIFY_OFFSET(reserved9, 0x65);
8347         VERIFY_OFFSET(tag, 0x68);
8348         VERIFY_OFFSET(host_addr, 0x70);
8349         VERIFY_OFFSET(CISS_LUN, 0x78);
8350         VERIFY_OFFSET(SG, 0x78 + 8);
8351 #undef VERIFY_OFFSET
8352 }
8353
8354 module_init(hpsa_init);
8355 module_exit(hpsa_cleanup);