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