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