xref: /linux/drivers/scsi/hpsa.c (revision d0105247ca7e281aac61216d8a641576200f262f)
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, u16 *sense_code)
357 {
358 	struct scsi_sense_hdr sshdr;
359 	bool rc;
360 
361 	*sense_key = -1;
362 	*sense_code = -1;
363 
364 	if (sense_data_len < 1)
365 		return;
366 
367 	rc = scsi_normalize_sense(sense_data, sense_data_len, &sshdr);
368 	if (rc) {
369 		*sense_key = sshdr.sense_key;
370 		*sense_code = sshdr.sense_code;
371 	}
372 }
373 
374 static int check_for_unit_attention(struct ctlr_info *h,
375 	struct CommandList *c)
376 {
377 	u8 sense_key;
378 	u16 sense_code;
379 	int sense_len;
380 
381 	if (c->err_info->SenseLen > sizeof(c->err_info->SenseInfo))
382 		sense_len = sizeof(c->err_info->SenseInfo);
383 	else
384 		sense_len = c->err_info->SenseLen;
385 
386 	decode_sense_data(c->err_info->SenseInfo, sense_len,
387 			  &sense_key, &sense_code);
388 	if (sense_key != UNIT_ATTENTION ||
389 	    scsi_sense_code_asc(sense_code) == 0xff)
390 		return 0;
391 
392 	switch (scsi_sense_code_asc(sense_code)) {
393 	case ASC_PARAMETERS_CHANGED:
394 		dev_warn(&h->pdev->dev,
395 			"%s: a state change detected, command retried\n",
396 			h->devname);
397 		break;
398 	case ASC_LU_HAS_NOT_SELF_CONFIGURED_YET:
399 		dev_warn(&h->pdev->dev,
400 			"%s: LUN failure detected\n", h->devname);
401 		break;
402 	case ASC_TARGET_OPERATING_CONDITIONS_HAVE_CHANGED:
403 		dev_warn(&h->pdev->dev,
404 			"%s: report LUN data changed\n", h->devname);
405 	/*
406 	 * Note: this ASC_TARGET_OPERATING_CONDITIONS_HAVE_CHANGED condition
407 	 * only occurs on the external target (array) devices.
408 	 */
409 		break;
410 	case ASC_POWER_ON_RESET_OR_BUS_DEVICE_RESET_OCCURRED:
411 		dev_warn(&h->pdev->dev,
412 			"%s: a power on or device reset detected\n",
413 			h->devname);
414 		break;
415 	case ASC_COMMANDS_CLEARED_BY_ANOTHER_INITIATOR:
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 	u8 sense_key;
2566 	u16 sense_code;
2567 	unsigned long sense_data_size;
2568 
2569 	ei = cp->err_info;
2570 	cmd = cp->scsi_cmd;
2571 	h = cp->h;
2572 
2573 	if (!cmd->device) {
2574 		cmd->result = DID_NO_CONNECT << 16;
2575 		return hpsa_cmd_free_and_done(h, cp, cmd);
2576 	}
2577 
2578 	dev = cmd->device->hostdata;
2579 	if (!dev) {
2580 		cmd->result = DID_NO_CONNECT << 16;
2581 		return hpsa_cmd_free_and_done(h, cp, cmd);
2582 	}
2583 	c2 = &h->ioaccel2_cmd_pool[cp->cmdindex];
2584 
2585 	scsi_dma_unmap(cmd); /* undo the DMA mappings */
2586 	if ((cp->cmd_type == CMD_SCSI) &&
2587 		(le16_to_cpu(cp->Header.SGTotal) > h->max_cmd_sg_entries))
2588 		hpsa_unmap_sg_chain_block(h, cp);
2589 
2590 	if ((cp->cmd_type == CMD_IOACCEL2) &&
2591 		(c2->sg[0].chain_indicator == IOACCEL2_CHAIN))
2592 		hpsa_unmap_ioaccel2_sg_chain_block(h, c2);
2593 
2594 	cmd->result = (DID_OK << 16);		/* host byte */
2595 
2596 	/* SCSI command has already been cleaned up in SML */
2597 	if (dev->was_removed) {
2598 		hpsa_cmd_resolve_and_free(h, cp);
2599 		return;
2600 	}
2601 
2602 	if (cp->cmd_type == CMD_IOACCEL2 || cp->cmd_type == CMD_IOACCEL1) {
2603 		if (dev->physical_device && dev->expose_device &&
2604 			dev->removed) {
2605 			cmd->result = DID_NO_CONNECT << 16;
2606 			return hpsa_cmd_free_and_done(h, cp, cmd);
2607 		}
2608 		if (likely(cp->phys_disk != NULL))
2609 			atomic_dec(&cp->phys_disk->ioaccel_cmds_out);
2610 	}
2611 
2612 	/*
2613 	 * We check for lockup status here as it may be set for
2614 	 * CMD_SCSI, CMD_IOACCEL1 and CMD_IOACCEL2 commands by
2615 	 * fail_all_oustanding_cmds()
2616 	 */
2617 	if (unlikely(ei->CommandStatus == CMD_CTLR_LOCKUP)) {
2618 		/* DID_NO_CONNECT will prevent a retry */
2619 		cmd->result = DID_NO_CONNECT << 16;
2620 		return hpsa_cmd_free_and_done(h, cp, cmd);
2621 	}
2622 
2623 	if (cp->cmd_type == CMD_IOACCEL2)
2624 		return process_ioaccel2_completion(h, cp, cmd, dev);
2625 
2626 	scsi_set_resid(cmd, ei->ResidualCnt);
2627 	if (ei->CommandStatus == 0)
2628 		return hpsa_cmd_free_and_done(h, cp, cmd);
2629 
2630 	/* For I/O accelerator commands, copy over some fields to the normal
2631 	 * CISS header used below for error handling.
2632 	 */
2633 	if (cp->cmd_type == CMD_IOACCEL1) {
2634 		struct io_accel1_cmd *c = &h->ioaccel_cmd_pool[cp->cmdindex];
2635 		cp->Header.SGList = scsi_sg_count(cmd);
2636 		cp->Header.SGTotal = cpu_to_le16(cp->Header.SGList);
2637 		cp->Request.CDBLen = le16_to_cpu(c->io_flags) &
2638 			IOACCEL1_IOFLAGS_CDBLEN_MASK;
2639 		cp->Header.tag = c->tag;
2640 		memcpy(cp->Header.LUN.LunAddrBytes, c->CISS_LUN, 8);
2641 		memcpy(cp->Request.CDB, c->CDB, cp->Request.CDBLen);
2642 
2643 		/* Any RAID offload error results in retry which will use
2644 		 * the normal I/O path so the controller can handle whatever's
2645 		 * wrong.
2646 		 */
2647 		if (is_logical_device(dev)) {
2648 			if (ei->CommandStatus == CMD_IOACCEL_DISABLED)
2649 				dev->offload_enabled = 0;
2650 			return hpsa_retry_cmd(h, cp);
2651 		}
2652 	}
2653 
2654 	/* an error has occurred */
2655 	switch (ei->CommandStatus) {
2656 
2657 	case CMD_TARGET_STATUS:
2658 		cmd->result |= ei->ScsiStatus;
2659 		/* copy the sense data */
2660 		sense_data_size = min_t(unsigned long, SCSI_SENSE_BUFFERSIZE,
2661 					sizeof(ei->SenseInfo));
2662 		if (ei->SenseLen < sense_data_size)
2663 			sense_data_size = ei->SenseLen;
2664 		memcpy(cmd->sense_buffer, ei->SenseInfo, sense_data_size);
2665 		if (ei->ScsiStatus)
2666 			decode_sense_data(ei->SenseInfo, sense_data_size,
2667 				&sense_key, &sense_code);
2668 		if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION) {
2669 			switch (sense_key) {
2670 			case ABORTED_COMMAND:
2671 				cmd->result |= DID_SOFT_ERROR << 16;
2672 				break;
2673 			case UNIT_ATTENTION:
2674 				if (sense_code ==
2675 				    REPORTED_LUNS_DATA_HAS_CHANGED)
2676 					h->drv_req_rescan = 1;
2677 				break;
2678 			case ILLEGAL_REQUEST:
2679 				if (sense_code == LU_NOT_SUPPORTED) {
2680 					dev->removed = 1;
2681 					cmd->result = DID_NO_CONNECT << 16;
2682 				}
2683 				break;
2684 			}
2685 			break;
2686 		}
2687 		/* Problem was not a check condition
2688 		 * Pass it up to the upper layers...
2689 		 */
2690 		if (ei->ScsiStatus) {
2691 			dev_warn(&h->pdev->dev, "cp %p has status 0x%x "
2692 				"Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
2693 				"Returning result: 0x%x\n",
2694 				cp, ei->ScsiStatus,
2695 				sense_key,
2696 				scsi_sense_code_asc(sense_code),
2697 				scsi_sense_code_ascq(sense_code),
2698 				cmd->result);
2699 		} else {  /* scsi status is zero??? How??? */
2700 			dev_warn(&h->pdev->dev, "cp %p SCSI status was 0. "
2701 				"Returning no connection.\n", cp),
2702 
2703 			/* Ordinarily, this case should never happen,
2704 			 * but there is a bug in some released firmware
2705 			 * revisions that allows it to happen if, for
2706 			 * example, a 4100 backplane loses power and
2707 			 * the tape drive is in it.  We assume that
2708 			 * it's a fatal error of some kind because we
2709 			 * can't show that it wasn't. We will make it
2710 			 * look like selection timeout since that is
2711 			 * the most common reason for this to occur,
2712 			 * and it's severe enough.
2713 			 */
2714 
2715 			cmd->result = DID_NO_CONNECT << 16;
2716 		}
2717 		break;
2718 
2719 	case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
2720 		break;
2721 	case CMD_DATA_OVERRUN:
2722 		dev_warn(&h->pdev->dev,
2723 			"CDB %16phN data overrun\n", cp->Request.CDB);
2724 		break;
2725 	case CMD_INVALID: {
2726 		/* print_bytes(cp, sizeof(*cp), 1, 0);
2727 		print_cmd(cp); */
2728 		/* We get CMD_INVALID if you address a non-existent device
2729 		 * instead of a selection timeout (no response).  You will
2730 		 * see this if you yank out a drive, then try to access it.
2731 		 * This is kind of a shame because it means that any other
2732 		 * CMD_INVALID (e.g. driver bug) will get interpreted as a
2733 		 * missing target. */
2734 		cmd->result = DID_NO_CONNECT << 16;
2735 	}
2736 		break;
2737 	case CMD_PROTOCOL_ERR:
2738 		cmd->result = DID_ERROR << 16;
2739 		dev_warn(&h->pdev->dev, "CDB %16phN : protocol error\n",
2740 				cp->Request.CDB);
2741 		break;
2742 	case CMD_HARDWARE_ERR:
2743 		cmd->result = DID_ERROR << 16;
2744 		dev_warn(&h->pdev->dev, "CDB %16phN : hardware error\n",
2745 			cp->Request.CDB);
2746 		break;
2747 	case CMD_CONNECTION_LOST:
2748 		cmd->result = DID_ERROR << 16;
2749 		dev_warn(&h->pdev->dev, "CDB %16phN : connection lost\n",
2750 			cp->Request.CDB);
2751 		break;
2752 	case CMD_ABORTED:
2753 		cmd->result = DID_ABORT << 16;
2754 		break;
2755 	case CMD_ABORT_FAILED:
2756 		cmd->result = DID_ERROR << 16;
2757 		dev_warn(&h->pdev->dev, "CDB %16phN : abort failed\n",
2758 			cp->Request.CDB);
2759 		break;
2760 	case CMD_UNSOLICITED_ABORT:
2761 		cmd->result = DID_SOFT_ERROR << 16; /* retry the command */
2762 		dev_warn(&h->pdev->dev, "CDB %16phN : unsolicited abort\n",
2763 			cp->Request.CDB);
2764 		break;
2765 	case CMD_TIMEOUT:
2766 		cmd->result = DID_TIME_OUT << 16;
2767 		dev_warn(&h->pdev->dev, "CDB %16phN timed out\n",
2768 			cp->Request.CDB);
2769 		break;
2770 	case CMD_UNABORTABLE:
2771 		cmd->result = DID_ERROR << 16;
2772 		dev_warn(&h->pdev->dev, "Command unabortable\n");
2773 		break;
2774 	case CMD_TMF_STATUS:
2775 		if (hpsa_evaluate_tmf_status(h, cp)) /* TMF failed? */
2776 			cmd->result = DID_ERROR << 16;
2777 		break;
2778 	case CMD_IOACCEL_DISABLED:
2779 		/* This only handles the direct pass-through case since RAID
2780 		 * offload is handled above.  Just attempt a retry.
2781 		 */
2782 		cmd->result = DID_SOFT_ERROR << 16;
2783 		dev_warn(&h->pdev->dev,
2784 				"cp %p had HP SSD Smart Path error\n", cp);
2785 		break;
2786 	default:
2787 		cmd->result = DID_ERROR << 16;
2788 		dev_warn(&h->pdev->dev, "cp %p returned unknown status %x\n",
2789 				cp, ei->CommandStatus);
2790 	}
2791 
2792 	return hpsa_cmd_free_and_done(h, cp, cmd);
2793 }
2794 
2795 static void hpsa_pci_unmap(struct pci_dev *pdev, struct CommandList *c,
2796 		int sg_used, enum dma_data_direction data_direction)
2797 {
2798 	int i;
2799 
2800 	for (i = 0; i < sg_used; i++)
2801 		dma_unmap_single(&pdev->dev, le64_to_cpu(c->SG[i].Addr),
2802 				le32_to_cpu(c->SG[i].Len),
2803 				data_direction);
2804 }
2805 
2806 static int hpsa_map_one(struct pci_dev *pdev,
2807 		struct CommandList *cp,
2808 		unsigned char *buf,
2809 		size_t buflen,
2810 		enum dma_data_direction data_direction)
2811 {
2812 	u64 addr64;
2813 
2814 	if (buflen == 0 || data_direction == DMA_NONE) {
2815 		cp->Header.SGList = 0;
2816 		cp->Header.SGTotal = cpu_to_le16(0);
2817 		return 0;
2818 	}
2819 
2820 	addr64 = dma_map_single(&pdev->dev, buf, buflen, data_direction);
2821 	if (dma_mapping_error(&pdev->dev, addr64)) {
2822 		/* Prevent subsequent unmap of something never mapped */
2823 		cp->Header.SGList = 0;
2824 		cp->Header.SGTotal = cpu_to_le16(0);
2825 		return -1;
2826 	}
2827 	cp->SG[0].Addr = cpu_to_le64(addr64);
2828 	cp->SG[0].Len = cpu_to_le32(buflen);
2829 	cp->SG[0].Ext = cpu_to_le32(HPSA_SG_LAST); /* we are not chaining */
2830 	cp->Header.SGList = 1;   /* no. SGs contig in this cmd */
2831 	cp->Header.SGTotal = cpu_to_le16(1); /* total sgs in cmd list */
2832 	return 0;
2833 }
2834 
2835 #define NO_TIMEOUT ((unsigned long) -1)
2836 #define DEFAULT_TIMEOUT 30000 /* milliseconds */
2837 static int hpsa_scsi_do_simple_cmd_core(struct ctlr_info *h,
2838 	struct CommandList *c, int reply_queue, unsigned long timeout_msecs)
2839 {
2840 	DECLARE_COMPLETION_ONSTACK(wait);
2841 
2842 	c->waiting = &wait;
2843 	__enqueue_cmd_and_start_io(h, c, reply_queue);
2844 	if (timeout_msecs == NO_TIMEOUT) {
2845 		/* TODO: get rid of this no-timeout thing */
2846 		wait_for_completion_io(&wait);
2847 		return IO_OK;
2848 	}
2849 	if (!wait_for_completion_io_timeout(&wait,
2850 					msecs_to_jiffies(timeout_msecs))) {
2851 		dev_warn(&h->pdev->dev, "Command timed out.\n");
2852 		return -ETIMEDOUT;
2853 	}
2854 	return IO_OK;
2855 }
2856 
2857 static int hpsa_scsi_do_simple_cmd(struct ctlr_info *h, struct CommandList *c,
2858 				   int reply_queue, unsigned long timeout_msecs)
2859 {
2860 	if (unlikely(lockup_detected(h))) {
2861 		c->err_info->CommandStatus = CMD_CTLR_LOCKUP;
2862 		return IO_OK;
2863 	}
2864 	return hpsa_scsi_do_simple_cmd_core(h, c, reply_queue, timeout_msecs);
2865 }
2866 
2867 static u32 lockup_detected(struct ctlr_info *h)
2868 {
2869 	int cpu;
2870 	u32 rc, *lockup_detected;
2871 
2872 	cpu = get_cpu();
2873 	lockup_detected = per_cpu_ptr(h->lockup_detected, cpu);
2874 	rc = *lockup_detected;
2875 	put_cpu();
2876 	return rc;
2877 }
2878 
2879 #define MAX_DRIVER_CMD_RETRIES 25
2880 static int hpsa_scsi_do_simple_cmd_with_retry(struct ctlr_info *h,
2881 		struct CommandList *c, enum dma_data_direction data_direction,
2882 		unsigned long timeout_msecs)
2883 {
2884 	int backoff_time = 10, retry_count = 0;
2885 	int rc;
2886 
2887 	do {
2888 		memset(c->err_info, 0, sizeof(*c->err_info));
2889 		rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE,
2890 						  timeout_msecs);
2891 		if (rc)
2892 			break;
2893 		retry_count++;
2894 		if (retry_count > 3) {
2895 			msleep(backoff_time);
2896 			if (backoff_time < 1000)
2897 				backoff_time *= 2;
2898 		}
2899 	} while ((check_for_unit_attention(h, c) ||
2900 			check_for_busy(h, c)) &&
2901 			retry_count <= MAX_DRIVER_CMD_RETRIES);
2902 	hpsa_pci_unmap(h->pdev, c, 1, data_direction);
2903 	if (retry_count > MAX_DRIVER_CMD_RETRIES)
2904 		rc = -EIO;
2905 	return rc;
2906 }
2907 
2908 static void hpsa_print_cmd(struct ctlr_info *h, char *txt,
2909 				struct CommandList *c)
2910 {
2911 	const u8 *cdb = c->Request.CDB;
2912 	const u8 *lun = c->Header.LUN.LunAddrBytes;
2913 
2914 	dev_warn(&h->pdev->dev, "%s: LUN:%8phN CDB:%16phN\n",
2915 		 txt, lun, cdb);
2916 }
2917 
2918 static void hpsa_scsi_interpret_error(struct ctlr_info *h,
2919 			struct CommandList *cp)
2920 {
2921 	const struct ErrorInfo *ei = cp->err_info;
2922 	struct device *d = &cp->h->pdev->dev;
2923 	u8 sense_key;
2924 	u16 sense_code;
2925 	int sense_len;
2926 
2927 	switch (ei->CommandStatus) {
2928 	case CMD_TARGET_STATUS:
2929 		if (ei->SenseLen > sizeof(ei->SenseInfo))
2930 			sense_len = sizeof(ei->SenseInfo);
2931 		else
2932 			sense_len = ei->SenseLen;
2933 		decode_sense_data(ei->SenseInfo, sense_len, &sense_key,
2934 				  &sense_code);
2935 		hpsa_print_cmd(h, "SCSI status", cp);
2936 		if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION)
2937 			dev_warn(d, "SCSI Status = 02, Sense key = 0x%02x, ASC = 0x%02x, ASCQ = 0x%02x\n",
2938 				sense_key, scsi_sense_code_asc(sense_code),
2939 				 scsi_sense_code_ascq(sense_code));
2940 		else
2941 			dev_warn(d, "SCSI Status = 0x%02x\n", ei->ScsiStatus);
2942 		if (ei->ScsiStatus == 0)
2943 			dev_warn(d, "SCSI status is abnormally zero.  "
2944 			"(probably indicates selection timeout "
2945 			"reported incorrectly due to a known "
2946 			"firmware bug, circa July, 2001.)\n");
2947 		break;
2948 	case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
2949 		break;
2950 	case CMD_DATA_OVERRUN:
2951 		hpsa_print_cmd(h, "overrun condition", cp);
2952 		break;
2953 	case CMD_INVALID: {
2954 		/* controller unfortunately reports SCSI passthru's
2955 		 * to non-existent targets as invalid commands.
2956 		 */
2957 		hpsa_print_cmd(h, "invalid command", cp);
2958 		dev_warn(d, "probably means device no longer present\n");
2959 		}
2960 		break;
2961 	case CMD_PROTOCOL_ERR:
2962 		hpsa_print_cmd(h, "protocol error", cp);
2963 		break;
2964 	case CMD_HARDWARE_ERR:
2965 		hpsa_print_cmd(h, "hardware error", cp);
2966 		break;
2967 	case CMD_CONNECTION_LOST:
2968 		hpsa_print_cmd(h, "connection lost", cp);
2969 		break;
2970 	case CMD_ABORTED:
2971 		hpsa_print_cmd(h, "aborted", cp);
2972 		break;
2973 	case CMD_ABORT_FAILED:
2974 		hpsa_print_cmd(h, "abort failed", cp);
2975 		break;
2976 	case CMD_UNSOLICITED_ABORT:
2977 		hpsa_print_cmd(h, "unsolicited abort", cp);
2978 		break;
2979 	case CMD_TIMEOUT:
2980 		hpsa_print_cmd(h, "timed out", cp);
2981 		break;
2982 	case CMD_UNABORTABLE:
2983 		hpsa_print_cmd(h, "unabortable", cp);
2984 		break;
2985 	case CMD_CTLR_LOCKUP:
2986 		hpsa_print_cmd(h, "controller lockup detected", cp);
2987 		break;
2988 	default:
2989 		hpsa_print_cmd(h, "unknown status", cp);
2990 		dev_warn(d, "Unknown command status %x\n",
2991 				ei->CommandStatus);
2992 	}
2993 }
2994 
2995 static int hpsa_do_receive_diagnostic(struct ctlr_info *h, u8 *scsi3addr,
2996 					u8 page, u8 *buf, size_t bufsize)
2997 {
2998 	int rc = IO_OK;
2999 	struct CommandList *c;
3000 	struct ErrorInfo *ei;
3001 
3002 	c = cmd_alloc(h);
3003 	if (fill_cmd(c, RECEIVE_DIAGNOSTIC, h, buf, bufsize,
3004 			page, scsi3addr, TYPE_CMD)) {
3005 		rc = -1;
3006 		goto out;
3007 	}
3008 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3009 			NO_TIMEOUT);
3010 	if (rc)
3011 		goto out;
3012 	ei = c->err_info;
3013 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3014 		hpsa_scsi_interpret_error(h, c);
3015 		rc = -1;
3016 	}
3017 out:
3018 	cmd_free(h, c);
3019 	return rc;
3020 }
3021 
3022 static u64 hpsa_get_enclosure_logical_identifier(struct ctlr_info *h,
3023 						u8 *scsi3addr)
3024 {
3025 	u8 *buf;
3026 	u64 sa = 0;
3027 	int rc = 0;
3028 
3029 	buf = kzalloc(1024, GFP_KERNEL);
3030 	if (!buf)
3031 		return 0;
3032 
3033 	rc = hpsa_do_receive_diagnostic(h, scsi3addr, RECEIVE_DIAGNOSTIC,
3034 					buf, 1024);
3035 
3036 	if (rc)
3037 		goto out;
3038 
3039 	sa = get_unaligned_be64(buf+12);
3040 
3041 out:
3042 	kfree(buf);
3043 	return sa;
3044 }
3045 
3046 static int hpsa_scsi_do_inquiry(struct ctlr_info *h, unsigned char *scsi3addr,
3047 			u16 page, unsigned char *buf,
3048 			unsigned char bufsize)
3049 {
3050 	int rc = IO_OK;
3051 	struct CommandList *c;
3052 	struct ErrorInfo *ei;
3053 
3054 	c = cmd_alloc(h);
3055 
3056 	if (fill_cmd(c, HPSA_INQUIRY, h, buf, bufsize,
3057 			page, scsi3addr, TYPE_CMD)) {
3058 		rc = -1;
3059 		goto out;
3060 	}
3061 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3062 			NO_TIMEOUT);
3063 	if (rc)
3064 		goto out;
3065 	ei = c->err_info;
3066 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3067 		hpsa_scsi_interpret_error(h, c);
3068 		rc = -1;
3069 	}
3070 out:
3071 	cmd_free(h, c);
3072 	return rc;
3073 }
3074 
3075 static int hpsa_send_reset(struct ctlr_info *h, struct hpsa_scsi_dev_t *dev,
3076 	u8 reset_type, int reply_queue)
3077 {
3078 	int rc = IO_OK;
3079 	struct CommandList *c;
3080 	struct ErrorInfo *ei;
3081 
3082 	c = cmd_alloc(h);
3083 	c->device = dev;
3084 
3085 	/* fill_cmd can't fail here, no data buffer to map. */
3086 	(void) fill_cmd(c, reset_type, h, NULL, 0, 0, dev->scsi3addr, TYPE_MSG);
3087 	rc = hpsa_scsi_do_simple_cmd(h, c, reply_queue, NO_TIMEOUT);
3088 	if (rc) {
3089 		dev_warn(&h->pdev->dev, "Failed to send reset command\n");
3090 		goto out;
3091 	}
3092 	/* no unmap needed here because no data xfer. */
3093 
3094 	ei = c->err_info;
3095 	if (ei->CommandStatus != 0) {
3096 		hpsa_scsi_interpret_error(h, c);
3097 		rc = -1;
3098 	}
3099 out:
3100 	cmd_free(h, c);
3101 	return rc;
3102 }
3103 
3104 static bool hpsa_cmd_dev_match(struct ctlr_info *h, struct CommandList *c,
3105 			       struct hpsa_scsi_dev_t *dev,
3106 			       unsigned char *scsi3addr)
3107 {
3108 	int i;
3109 	bool match = false;
3110 	struct io_accel2_cmd *c2 = &h->ioaccel2_cmd_pool[c->cmdindex];
3111 	struct hpsa_tmf_struct *ac = (struct hpsa_tmf_struct *) c2;
3112 
3113 	if (hpsa_is_cmd_idle(c))
3114 		return false;
3115 
3116 	switch (c->cmd_type) {
3117 	case CMD_SCSI:
3118 	case CMD_IOCTL_PEND:
3119 		match = !memcmp(scsi3addr, &c->Header.LUN.LunAddrBytes,
3120 				sizeof(c->Header.LUN.LunAddrBytes));
3121 		break;
3122 
3123 	case CMD_IOACCEL1:
3124 	case CMD_IOACCEL2:
3125 		if (c->phys_disk == dev) {
3126 			/* HBA mode match */
3127 			match = true;
3128 		} else {
3129 			/* Possible RAID mode -- check each phys dev. */
3130 			/* FIXME:  Do we need to take out a lock here?  If
3131 			 * so, we could just call hpsa_get_pdisk_of_ioaccel2()
3132 			 * instead. */
3133 			for (i = 0; i < dev->nphysical_disks && !match; i++) {
3134 				/* FIXME: an alternate test might be
3135 				 *
3136 				 * match = dev->phys_disk[i]->ioaccel_handle
3137 				 *              == c2->scsi_nexus;      */
3138 				match = dev->phys_disk[i] == c->phys_disk;
3139 			}
3140 		}
3141 		break;
3142 
3143 	case IOACCEL2_TMF:
3144 		for (i = 0; i < dev->nphysical_disks && !match; i++) {
3145 			match = dev->phys_disk[i]->ioaccel_handle ==
3146 					le32_to_cpu(ac->it_nexus);
3147 		}
3148 		break;
3149 
3150 	case 0:		/* The command is in the middle of being initialized. */
3151 		match = false;
3152 		break;
3153 
3154 	default:
3155 		dev_err(&h->pdev->dev, "unexpected cmd_type: %d\n",
3156 			c->cmd_type);
3157 		BUG();
3158 	}
3159 
3160 	return match;
3161 }
3162 
3163 static int hpsa_do_reset(struct ctlr_info *h, struct hpsa_scsi_dev_t *dev,
3164 	u8 reset_type, int reply_queue)
3165 {
3166 	int rc = 0;
3167 
3168 	/* We can really only handle one reset at a time */
3169 	if (mutex_lock_interruptible(&h->reset_mutex) == -EINTR) {
3170 		dev_warn(&h->pdev->dev, "concurrent reset wait interrupted.\n");
3171 		return -EINTR;
3172 	}
3173 
3174 	rc = hpsa_send_reset(h, dev, reset_type, reply_queue);
3175 	if (!rc) {
3176 		/* incremented by sending the reset request */
3177 		atomic_dec(&dev->commands_outstanding);
3178 		wait_event(h->event_sync_wait_queue,
3179 			atomic_read(&dev->commands_outstanding) <= 0 ||
3180 			lockup_detected(h));
3181 	}
3182 
3183 	if (unlikely(lockup_detected(h))) {
3184 		dev_warn(&h->pdev->dev,
3185 			 "Controller lockup detected during reset wait\n");
3186 		rc = -ENODEV;
3187 	}
3188 
3189 	if (!rc)
3190 		rc = wait_for_device_to_become_ready(h, dev->scsi3addr, 0);
3191 
3192 	mutex_unlock(&h->reset_mutex);
3193 	return rc;
3194 }
3195 
3196 static void hpsa_get_raid_level(struct ctlr_info *h,
3197 	unsigned char *scsi3addr, unsigned char *raid_level)
3198 {
3199 	int rc;
3200 	unsigned char *buf;
3201 
3202 	*raid_level = RAID_UNKNOWN;
3203 	buf = kzalloc(64, GFP_KERNEL);
3204 	if (!buf)
3205 		return;
3206 
3207 	if (!hpsa_vpd_page_supported(h, scsi3addr,
3208 		HPSA_VPD_LV_DEVICE_GEOMETRY))
3209 		goto exit;
3210 
3211 	rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE |
3212 		HPSA_VPD_LV_DEVICE_GEOMETRY, buf, 64);
3213 
3214 	if (rc == 0)
3215 		*raid_level = buf[8];
3216 	if (*raid_level > RAID_UNKNOWN)
3217 		*raid_level = RAID_UNKNOWN;
3218 exit:
3219 	kfree(buf);
3220 	return;
3221 }
3222 
3223 #define HPSA_MAP_DEBUG
3224 #ifdef HPSA_MAP_DEBUG
3225 static void hpsa_debug_map_buff(struct ctlr_info *h, int rc,
3226 				struct raid_map_data *map_buff)
3227 {
3228 	struct raid_map_disk_data *dd = &map_buff->data[0];
3229 	int map, row, col;
3230 	u16 map_cnt, row_cnt, disks_per_row;
3231 
3232 	if (rc != 0)
3233 		return;
3234 
3235 	/* Show details only if debugging has been activated. */
3236 	if (h->raid_offload_debug < 2)
3237 		return;
3238 
3239 	dev_info(&h->pdev->dev, "structure_size = %u\n",
3240 				le32_to_cpu(map_buff->structure_size));
3241 	dev_info(&h->pdev->dev, "volume_blk_size = %u\n",
3242 			le32_to_cpu(map_buff->volume_blk_size));
3243 	dev_info(&h->pdev->dev, "volume_blk_cnt = 0x%llx\n",
3244 			le64_to_cpu(map_buff->volume_blk_cnt));
3245 	dev_info(&h->pdev->dev, "physicalBlockShift = %u\n",
3246 			map_buff->phys_blk_shift);
3247 	dev_info(&h->pdev->dev, "parity_rotation_shift = %u\n",
3248 			map_buff->parity_rotation_shift);
3249 	dev_info(&h->pdev->dev, "strip_size = %u\n",
3250 			le16_to_cpu(map_buff->strip_size));
3251 	dev_info(&h->pdev->dev, "disk_starting_blk = 0x%llx\n",
3252 			le64_to_cpu(map_buff->disk_starting_blk));
3253 	dev_info(&h->pdev->dev, "disk_blk_cnt = 0x%llx\n",
3254 			le64_to_cpu(map_buff->disk_blk_cnt));
3255 	dev_info(&h->pdev->dev, "data_disks_per_row = %u\n",
3256 			le16_to_cpu(map_buff->data_disks_per_row));
3257 	dev_info(&h->pdev->dev, "metadata_disks_per_row = %u\n",
3258 			le16_to_cpu(map_buff->metadata_disks_per_row));
3259 	dev_info(&h->pdev->dev, "row_cnt = %u\n",
3260 			le16_to_cpu(map_buff->row_cnt));
3261 	dev_info(&h->pdev->dev, "layout_map_count = %u\n",
3262 			le16_to_cpu(map_buff->layout_map_count));
3263 	dev_info(&h->pdev->dev, "flags = 0x%x\n",
3264 			le16_to_cpu(map_buff->flags));
3265 	dev_info(&h->pdev->dev, "encryption = %s\n",
3266 			le16_to_cpu(map_buff->flags) &
3267 			RAID_MAP_FLAG_ENCRYPT_ON ?  "ON" : "OFF");
3268 	dev_info(&h->pdev->dev, "dekindex = %u\n",
3269 			le16_to_cpu(map_buff->dekindex));
3270 	map_cnt = le16_to_cpu(map_buff->layout_map_count);
3271 	for (map = 0; map < map_cnt; map++) {
3272 		dev_info(&h->pdev->dev, "Map%u:\n", map);
3273 		row_cnt = le16_to_cpu(map_buff->row_cnt);
3274 		for (row = 0; row < row_cnt; row++) {
3275 			dev_info(&h->pdev->dev, "  Row%u:\n", row);
3276 			disks_per_row =
3277 				le16_to_cpu(map_buff->data_disks_per_row);
3278 			for (col = 0; col < disks_per_row; col++, dd++)
3279 				dev_info(&h->pdev->dev,
3280 					"    D%02u: h=0x%04x xor=%u,%u\n",
3281 					col, dd->ioaccel_handle,
3282 					dd->xor_mult[0], dd->xor_mult[1]);
3283 			disks_per_row =
3284 				le16_to_cpu(map_buff->metadata_disks_per_row);
3285 			for (col = 0; col < disks_per_row; col++, dd++)
3286 				dev_info(&h->pdev->dev,
3287 					"    M%02u: h=0x%04x xor=%u,%u\n",
3288 					col, dd->ioaccel_handle,
3289 					dd->xor_mult[0], dd->xor_mult[1]);
3290 		}
3291 	}
3292 }
3293 #else
3294 static void hpsa_debug_map_buff(__attribute__((unused)) struct ctlr_info *h,
3295 			__attribute__((unused)) int rc,
3296 			__attribute__((unused)) struct raid_map_data *map_buff)
3297 {
3298 }
3299 #endif
3300 
3301 static int hpsa_get_raid_map(struct ctlr_info *h,
3302 	unsigned char *scsi3addr, struct hpsa_scsi_dev_t *this_device)
3303 {
3304 	int rc = 0;
3305 	struct CommandList *c;
3306 	struct ErrorInfo *ei;
3307 
3308 	c = cmd_alloc(h);
3309 
3310 	if (fill_cmd(c, HPSA_GET_RAID_MAP, h, &this_device->raid_map,
3311 			sizeof(this_device->raid_map), 0,
3312 			scsi3addr, TYPE_CMD)) {
3313 		dev_warn(&h->pdev->dev, "hpsa_get_raid_map fill_cmd failed\n");
3314 		cmd_free(h, c);
3315 		return -1;
3316 	}
3317 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3318 			NO_TIMEOUT);
3319 	if (rc)
3320 		goto out;
3321 	ei = c->err_info;
3322 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3323 		hpsa_scsi_interpret_error(h, c);
3324 		rc = -1;
3325 		goto out;
3326 	}
3327 	cmd_free(h, c);
3328 
3329 	/* @todo in the future, dynamically allocate RAID map memory */
3330 	if (le32_to_cpu(this_device->raid_map.structure_size) >
3331 				sizeof(this_device->raid_map)) {
3332 		dev_warn(&h->pdev->dev, "RAID map size is too large!\n");
3333 		rc = -1;
3334 	}
3335 	hpsa_debug_map_buff(h, rc, &this_device->raid_map);
3336 	return rc;
3337 out:
3338 	cmd_free(h, c);
3339 	return rc;
3340 }
3341 
3342 static int hpsa_bmic_sense_subsystem_information(struct ctlr_info *h,
3343 		unsigned char scsi3addr[], u16 bmic_device_index,
3344 		struct bmic_sense_subsystem_info *buf, size_t bufsize)
3345 {
3346 	int rc = IO_OK;
3347 	struct CommandList *c;
3348 	struct ErrorInfo *ei;
3349 
3350 	c = cmd_alloc(h);
3351 
3352 	rc = fill_cmd(c, BMIC_SENSE_SUBSYSTEM_INFORMATION, h, buf, bufsize,
3353 		0, RAID_CTLR_LUNID, TYPE_CMD);
3354 	if (rc)
3355 		goto out;
3356 
3357 	c->Request.CDB[2] = bmic_device_index & 0xff;
3358 	c->Request.CDB[9] = (bmic_device_index >> 8) & 0xff;
3359 
3360 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3361 			NO_TIMEOUT);
3362 	if (rc)
3363 		goto out;
3364 	ei = c->err_info;
3365 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3366 		hpsa_scsi_interpret_error(h, c);
3367 		rc = -1;
3368 	}
3369 out:
3370 	cmd_free(h, c);
3371 	return rc;
3372 }
3373 
3374 static int hpsa_bmic_id_controller(struct ctlr_info *h,
3375 	struct bmic_identify_controller *buf, size_t bufsize)
3376 {
3377 	int rc = IO_OK;
3378 	struct CommandList *c;
3379 	struct ErrorInfo *ei;
3380 
3381 	c = cmd_alloc(h);
3382 
3383 	rc = fill_cmd(c, BMIC_IDENTIFY_CONTROLLER, h, buf, bufsize,
3384 		0, RAID_CTLR_LUNID, TYPE_CMD);
3385 	if (rc)
3386 		goto out;
3387 
3388 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3389 			NO_TIMEOUT);
3390 	if (rc)
3391 		goto out;
3392 	ei = c->err_info;
3393 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3394 		hpsa_scsi_interpret_error(h, c);
3395 		rc = -1;
3396 	}
3397 out:
3398 	cmd_free(h, c);
3399 	return rc;
3400 }
3401 
3402 static int hpsa_bmic_id_physical_device(struct ctlr_info *h,
3403 		unsigned char scsi3addr[], u16 bmic_device_index,
3404 		struct bmic_identify_physical_device *buf, size_t bufsize)
3405 {
3406 	int rc = IO_OK;
3407 	struct CommandList *c;
3408 	struct ErrorInfo *ei;
3409 
3410 	c = cmd_alloc(h);
3411 	rc = fill_cmd(c, BMIC_IDENTIFY_PHYSICAL_DEVICE, h, buf, bufsize,
3412 		0, RAID_CTLR_LUNID, TYPE_CMD);
3413 	if (rc)
3414 		goto out;
3415 
3416 	c->Request.CDB[2] = bmic_device_index & 0xff;
3417 	c->Request.CDB[9] = (bmic_device_index >> 8) & 0xff;
3418 
3419 	hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3420 						NO_TIMEOUT);
3421 	ei = c->err_info;
3422 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3423 		hpsa_scsi_interpret_error(h, c);
3424 		rc = -1;
3425 	}
3426 out:
3427 	cmd_free(h, c);
3428 
3429 	return rc;
3430 }
3431 
3432 /*
3433  * get enclosure information
3434  * struct ReportExtendedLUNdata *rlep - Used for BMIC drive number
3435  * struct hpsa_scsi_dev_t *encl_dev - device entry for enclosure
3436  * Uses id_physical_device to determine the box_index.
3437  */
3438 static void hpsa_get_enclosure_info(struct ctlr_info *h,
3439 			unsigned char *scsi3addr,
3440 			struct ReportExtendedLUNdata *rlep, int rle_index,
3441 			struct hpsa_scsi_dev_t *encl_dev)
3442 {
3443 	int rc = -1;
3444 	struct CommandList *c = NULL;
3445 	struct ErrorInfo *ei = NULL;
3446 	struct bmic_sense_storage_box_params *bssbp = NULL;
3447 	struct bmic_identify_physical_device *id_phys = NULL;
3448 	struct ext_report_lun_entry *rle;
3449 	u16 bmic_device_index = 0;
3450 
3451 	if (rle_index < 0 || rle_index >= HPSA_MAX_PHYS_LUN)
3452 		return;
3453 
3454 	rle = &rlep->LUN[rle_index];
3455 
3456 	encl_dev->eli =
3457 		hpsa_get_enclosure_logical_identifier(h, scsi3addr);
3458 
3459 	bmic_device_index = GET_BMIC_DRIVE_NUMBER(&rle->lunid[0]);
3460 
3461 	if (encl_dev->target == -1 || encl_dev->lun == -1) {
3462 		rc = IO_OK;
3463 		goto out;
3464 	}
3465 
3466 	if (bmic_device_index == 0xFF00 || MASKED_DEVICE(&rle->lunid[0])) {
3467 		rc = IO_OK;
3468 		goto out;
3469 	}
3470 
3471 	bssbp = kzalloc_obj(*bssbp);
3472 	if (!bssbp)
3473 		goto out;
3474 
3475 	id_phys = kzalloc_obj(*id_phys);
3476 	if (!id_phys)
3477 		goto out;
3478 
3479 	rc = hpsa_bmic_id_physical_device(h, scsi3addr, bmic_device_index,
3480 						id_phys, sizeof(*id_phys));
3481 	if (rc) {
3482 		dev_warn(&h->pdev->dev, "%s: id_phys failed %d bdi[0x%x]\n",
3483 			__func__, encl_dev->external, bmic_device_index);
3484 		goto out;
3485 	}
3486 
3487 	c = cmd_alloc(h);
3488 
3489 	rc = fill_cmd(c, BMIC_SENSE_STORAGE_BOX_PARAMS, h, bssbp,
3490 			sizeof(*bssbp), 0, RAID_CTLR_LUNID, TYPE_CMD);
3491 
3492 	if (rc)
3493 		goto out;
3494 
3495 	if (id_phys->phys_connector[1] == 'E')
3496 		c->Request.CDB[5] = id_phys->box_index;
3497 	else
3498 		c->Request.CDB[5] = 0;
3499 
3500 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3501 						NO_TIMEOUT);
3502 	if (rc)
3503 		goto out;
3504 
3505 	ei = c->err_info;
3506 	if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
3507 		rc = -1;
3508 		goto out;
3509 	}
3510 
3511 	encl_dev->box[id_phys->active_path_number] = bssbp->phys_box_on_port;
3512 	memcpy(&encl_dev->phys_connector[id_phys->active_path_number],
3513 		bssbp->phys_connector, sizeof(bssbp->phys_connector));
3514 
3515 	rc = IO_OK;
3516 out:
3517 	kfree(bssbp);
3518 	kfree(id_phys);
3519 
3520 	if (c)
3521 		cmd_free(h, c);
3522 
3523 	if (rc != IO_OK)
3524 		hpsa_show_dev_msg(KERN_INFO, h, encl_dev,
3525 			"Error, could not get enclosure information");
3526 }
3527 
3528 static u64 hpsa_get_sas_address_from_report_physical(struct ctlr_info *h,
3529 						unsigned char *scsi3addr)
3530 {
3531 	struct ReportExtendedLUNdata *physdev;
3532 	u32 nphysicals;
3533 	u64 sa = 0;
3534 	int i;
3535 
3536 	physdev = kzalloc_obj(*physdev);
3537 	if (!physdev)
3538 		return 0;
3539 
3540 	if (hpsa_scsi_do_report_phys_luns(h, physdev, sizeof(*physdev))) {
3541 		dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
3542 		kfree(physdev);
3543 		return 0;
3544 	}
3545 	nphysicals = get_unaligned_be32(physdev->LUNListLength) / 24;
3546 
3547 	for (i = 0; i < nphysicals; i++)
3548 		if (!memcmp(&physdev->LUN[i].lunid[0], scsi3addr, 8)) {
3549 			sa = get_unaligned_be64(&physdev->LUN[i].wwid[0]);
3550 			break;
3551 		}
3552 
3553 	kfree(physdev);
3554 
3555 	return sa;
3556 }
3557 
3558 static void hpsa_get_sas_address(struct ctlr_info *h, unsigned char *scsi3addr,
3559 					struct hpsa_scsi_dev_t *dev)
3560 {
3561 	int rc;
3562 	u64 sa = 0;
3563 
3564 	if (is_hba_lunid(scsi3addr)) {
3565 		struct bmic_sense_subsystem_info *ssi;
3566 
3567 		ssi = kzalloc_obj(*ssi);
3568 		if (!ssi)
3569 			return;
3570 
3571 		rc = hpsa_bmic_sense_subsystem_information(h,
3572 					scsi3addr, 0, ssi, sizeof(*ssi));
3573 		if (rc == 0) {
3574 			sa = get_unaligned_be64(ssi->primary_world_wide_id);
3575 			h->sas_address = sa;
3576 		}
3577 
3578 		kfree(ssi);
3579 	} else
3580 		sa = hpsa_get_sas_address_from_report_physical(h, scsi3addr);
3581 
3582 	dev->sas_address = sa;
3583 }
3584 
3585 static void hpsa_ext_ctrl_present(struct ctlr_info *h,
3586 	struct ReportExtendedLUNdata *physdev)
3587 {
3588 	u32 nphysicals;
3589 	int i;
3590 
3591 	if (h->discovery_polling)
3592 		return;
3593 
3594 	nphysicals = (get_unaligned_be32(physdev->LUNListLength) / 24) + 1;
3595 
3596 	for (i = 0; i < nphysicals; i++) {
3597 		if (physdev->LUN[i].device_type ==
3598 			BMIC_DEVICE_TYPE_CONTROLLER
3599 			&& !is_hba_lunid(physdev->LUN[i].lunid)) {
3600 			dev_info(&h->pdev->dev,
3601 				"External controller present, activate discovery polling and disable rld caching\n");
3602 			hpsa_disable_rld_caching(h);
3603 			h->discovery_polling = 1;
3604 			break;
3605 		}
3606 	}
3607 }
3608 
3609 /* Get a device id from inquiry page 0x83 */
3610 static bool hpsa_vpd_page_supported(struct ctlr_info *h,
3611 	unsigned char scsi3addr[], u8 page)
3612 {
3613 	int rc;
3614 	int i;
3615 	int pages;
3616 	unsigned char *buf, bufsize;
3617 
3618 	buf = kzalloc(256, GFP_KERNEL);
3619 	if (!buf)
3620 		return false;
3621 
3622 	/* Get the size of the page list first */
3623 	rc = hpsa_scsi_do_inquiry(h, scsi3addr,
3624 				VPD_PAGE | HPSA_VPD_SUPPORTED_PAGES,
3625 				buf, HPSA_VPD_HEADER_SZ);
3626 	if (rc != 0)
3627 		goto exit_unsupported;
3628 	pages = buf[3];
3629 	bufsize = min(pages + HPSA_VPD_HEADER_SZ, 255);
3630 
3631 	/* Get the whole VPD page list */
3632 	rc = hpsa_scsi_do_inquiry(h, scsi3addr,
3633 				VPD_PAGE | HPSA_VPD_SUPPORTED_PAGES,
3634 				buf, bufsize);
3635 	if (rc != 0)
3636 		goto exit_unsupported;
3637 
3638 	pages = buf[3];
3639 	for (i = 1; i <= pages; i++)
3640 		if (buf[3 + i] == page)
3641 			goto exit_supported;
3642 exit_unsupported:
3643 	kfree(buf);
3644 	return false;
3645 exit_supported:
3646 	kfree(buf);
3647 	return true;
3648 }
3649 
3650 /*
3651  * Called during a scan operation.
3652  * Sets ioaccel status on the new device list, not the existing device list
3653  *
3654  * The device list used during I/O will be updated later in
3655  * adjust_hpsa_scsi_table.
3656  */
3657 static void hpsa_get_ioaccel_status(struct ctlr_info *h,
3658 	unsigned char *scsi3addr, struct hpsa_scsi_dev_t *this_device)
3659 {
3660 	int rc;
3661 	unsigned char *buf;
3662 	u8 ioaccel_status;
3663 
3664 	this_device->offload_config = 0;
3665 	this_device->offload_enabled = 0;
3666 	this_device->offload_to_be_enabled = 0;
3667 
3668 	buf = kzalloc(64, GFP_KERNEL);
3669 	if (!buf)
3670 		return;
3671 	if (!hpsa_vpd_page_supported(h, scsi3addr, HPSA_VPD_LV_IOACCEL_STATUS))
3672 		goto out;
3673 	rc = hpsa_scsi_do_inquiry(h, scsi3addr,
3674 			VPD_PAGE | HPSA_VPD_LV_IOACCEL_STATUS, buf, 64);
3675 	if (rc != 0)
3676 		goto out;
3677 
3678 #define IOACCEL_STATUS_BYTE 4
3679 #define OFFLOAD_CONFIGURED_BIT 0x01
3680 #define OFFLOAD_ENABLED_BIT 0x02
3681 	ioaccel_status = buf[IOACCEL_STATUS_BYTE];
3682 	this_device->offload_config =
3683 		!!(ioaccel_status & OFFLOAD_CONFIGURED_BIT);
3684 	if (this_device->offload_config) {
3685 		bool offload_enabled =
3686 			!!(ioaccel_status & OFFLOAD_ENABLED_BIT);
3687 		/*
3688 		 * Check to see if offload can be enabled.
3689 		 */
3690 		if (offload_enabled) {
3691 			rc = hpsa_get_raid_map(h, scsi3addr, this_device);
3692 			if (rc) /* could not load raid_map */
3693 				goto out;
3694 			this_device->offload_to_be_enabled = 1;
3695 		}
3696 	}
3697 
3698 out:
3699 	kfree(buf);
3700 	return;
3701 }
3702 
3703 /* Get the device id from inquiry page 0x83 */
3704 static int hpsa_get_device_id(struct ctlr_info *h, unsigned char *scsi3addr,
3705 	unsigned char *device_id, int index, int buflen)
3706 {
3707 	int rc;
3708 	unsigned char *buf;
3709 
3710 	/* Does controller have VPD for device id? */
3711 	if (!hpsa_vpd_page_supported(h, scsi3addr, HPSA_VPD_LV_DEVICE_ID))
3712 		return 1; /* not supported */
3713 
3714 	buf = kzalloc(64, GFP_KERNEL);
3715 	if (!buf)
3716 		return -ENOMEM;
3717 
3718 	rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE |
3719 					HPSA_VPD_LV_DEVICE_ID, buf, 64);
3720 	if (rc == 0) {
3721 		if (buflen > 16)
3722 			buflen = 16;
3723 		memcpy(device_id, &buf[8], buflen);
3724 	}
3725 
3726 	kfree(buf);
3727 
3728 	return rc; /*0 - got id,  otherwise, didn't */
3729 }
3730 
3731 static int hpsa_scsi_do_report_luns(struct ctlr_info *h, int logical,
3732 		void *buf, int bufsize,
3733 		int extended_response)
3734 {
3735 	int rc = IO_OK;
3736 	struct CommandList *c;
3737 	unsigned char scsi3addr[8];
3738 	struct ErrorInfo *ei;
3739 
3740 	c = cmd_alloc(h);
3741 
3742 	/* address the controller */
3743 	memset(scsi3addr, 0, sizeof(scsi3addr));
3744 	if (fill_cmd(c, logical ? HPSA_REPORT_LOG : HPSA_REPORT_PHYS, h,
3745 		buf, bufsize, 0, scsi3addr, TYPE_CMD)) {
3746 		rc = -EAGAIN;
3747 		goto out;
3748 	}
3749 	if (extended_response)
3750 		c->Request.CDB[1] = extended_response;
3751 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
3752 			NO_TIMEOUT);
3753 	if (rc)
3754 		goto out;
3755 	ei = c->err_info;
3756 	if (ei->CommandStatus != 0 &&
3757 	    ei->CommandStatus != CMD_DATA_UNDERRUN) {
3758 		hpsa_scsi_interpret_error(h, c);
3759 		rc = -EIO;
3760 	} else {
3761 		struct ReportLUNdata *rld = buf;
3762 
3763 		if (rld->extended_response_flag != extended_response) {
3764 			if (!h->legacy_board) {
3765 				dev_err(&h->pdev->dev,
3766 					"report luns requested format %u, got %u\n",
3767 					extended_response,
3768 					rld->extended_response_flag);
3769 				rc = -EINVAL;
3770 			} else
3771 				rc = -EOPNOTSUPP;
3772 		}
3773 	}
3774 out:
3775 	cmd_free(h, c);
3776 	return rc;
3777 }
3778 
3779 static inline int hpsa_scsi_do_report_phys_luns(struct ctlr_info *h,
3780 		struct ReportExtendedLUNdata *buf, int bufsize)
3781 {
3782 	int rc;
3783 	struct ReportLUNdata *lbuf;
3784 
3785 	rc = hpsa_scsi_do_report_luns(h, 0, buf, bufsize,
3786 				      HPSA_REPORT_PHYS_EXTENDED);
3787 	if (!rc || rc != -EOPNOTSUPP)
3788 		return rc;
3789 
3790 	/* REPORT PHYS EXTENDED is not supported */
3791 	lbuf = kzalloc_obj(*lbuf);
3792 	if (!lbuf)
3793 		return -ENOMEM;
3794 
3795 	rc = hpsa_scsi_do_report_luns(h, 0, lbuf, sizeof(*lbuf), 0);
3796 	if (!rc) {
3797 		int i;
3798 		u32 nphys;
3799 
3800 		/* Copy ReportLUNdata header */
3801 		memcpy(buf, lbuf, 8);
3802 		nphys = be32_to_cpu(*((__be32 *)lbuf->LUNListLength)) / 8;
3803 		for (i = 0; i < nphys; i++)
3804 			memcpy(buf->LUN[i].lunid, lbuf->LUN[i], 8);
3805 	}
3806 	kfree(lbuf);
3807 	return rc;
3808 }
3809 
3810 static inline int hpsa_scsi_do_report_log_luns(struct ctlr_info *h,
3811 		struct ReportLUNdata *buf, int bufsize)
3812 {
3813 	return hpsa_scsi_do_report_luns(h, 1, buf, bufsize, 0);
3814 }
3815 
3816 static inline void hpsa_set_bus_target_lun(struct hpsa_scsi_dev_t *device,
3817 	int bus, int target, int lun)
3818 {
3819 	device->bus = bus;
3820 	device->target = target;
3821 	device->lun = lun;
3822 }
3823 
3824 /* Use VPD inquiry to get details of volume status */
3825 static int hpsa_get_volume_status(struct ctlr_info *h,
3826 					unsigned char scsi3addr[])
3827 {
3828 	int rc;
3829 	int status;
3830 	int size;
3831 	unsigned char *buf;
3832 
3833 	buf = kzalloc(64, GFP_KERNEL);
3834 	if (!buf)
3835 		return HPSA_VPD_LV_STATUS_UNSUPPORTED;
3836 
3837 	/* Does controller have VPD for logical volume status? */
3838 	if (!hpsa_vpd_page_supported(h, scsi3addr, HPSA_VPD_LV_STATUS))
3839 		goto exit_failed;
3840 
3841 	/* Get the size of the VPD return buffer */
3842 	rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE | HPSA_VPD_LV_STATUS,
3843 					buf, HPSA_VPD_HEADER_SZ);
3844 	if (rc != 0)
3845 		goto exit_failed;
3846 	size = buf[3];
3847 
3848 	/* Now get the whole VPD buffer */
3849 	rc = hpsa_scsi_do_inquiry(h, scsi3addr, VPD_PAGE | HPSA_VPD_LV_STATUS,
3850 					buf, size + HPSA_VPD_HEADER_SZ);
3851 	if (rc != 0)
3852 		goto exit_failed;
3853 	status = buf[4]; /* status byte */
3854 
3855 	kfree(buf);
3856 	return status;
3857 exit_failed:
3858 	kfree(buf);
3859 	return HPSA_VPD_LV_STATUS_UNSUPPORTED;
3860 }
3861 
3862 /* Determine offline status of a volume.
3863  * Return either:
3864  *  0 (not offline)
3865  *  0xff (offline for unknown reasons)
3866  *  # (integer code indicating one of several NOT READY states
3867  *     describing why a volume is to be kept offline)
3868  */
3869 static unsigned char hpsa_volume_offline(struct ctlr_info *h,
3870 					unsigned char scsi3addr[])
3871 {
3872 	struct CommandList *c;
3873 	unsigned char *sense;
3874 	u8 sense_key;
3875 	u16 sense_code;
3876 	int sense_len;
3877 	int rc, ldstat = 0;
3878 
3879 	c = cmd_alloc(h);
3880 
3881 	(void) fill_cmd(c, TEST_UNIT_READY, h, NULL, 0, 0, scsi3addr, TYPE_CMD);
3882 	rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE,
3883 					NO_TIMEOUT);
3884 	if (rc) {
3885 		cmd_free(h, c);
3886 		return HPSA_VPD_LV_STATUS_UNSUPPORTED;
3887 	}
3888 	sense = c->err_info->SenseInfo;
3889 	if (c->err_info->SenseLen > sizeof(c->err_info->SenseInfo))
3890 		sense_len = sizeof(c->err_info->SenseInfo);
3891 	else
3892 		sense_len = c->err_info->SenseLen;
3893 	decode_sense_data(sense, sense_len, &sense_key, &sense_code);
3894 	cmd_free(h, c);
3895 
3896 	/* Determine the reason for not ready state */
3897 	ldstat = hpsa_get_volume_status(h, scsi3addr);
3898 
3899 	/* Keep volume offline in certain cases: */
3900 	switch (ldstat) {
3901 	case HPSA_LV_FAILED:
3902 	case HPSA_LV_UNDERGOING_ERASE:
3903 	case HPSA_LV_NOT_AVAILABLE:
3904 	case HPSA_LV_UNDERGOING_RPI:
3905 	case HPSA_LV_PENDING_RPI:
3906 	case HPSA_LV_ENCRYPTED_NO_KEY:
3907 	case HPSA_LV_PLAINTEXT_IN_ENCRYPT_ONLY_CONTROLLER:
3908 	case HPSA_LV_UNDERGOING_ENCRYPTION:
3909 	case HPSA_LV_UNDERGOING_ENCRYPTION_REKEYING:
3910 	case HPSA_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
3911 		return ldstat;
3912 	case HPSA_VPD_LV_STATUS_UNSUPPORTED:
3913 		/* If VPD status page isn't available,
3914 		 * use ASC/ASCQ to determine state
3915 		 */
3916 		if (sense_code == LU_NOT_READY_FORMAT_IN_PROGRESS ||
3917 		    sense_code == LU_NOT_READY_INITIALIZING_COMMAND_REQUIRED)
3918 			return ldstat;
3919 		break;
3920 	default:
3921 		break;
3922 	}
3923 	return HPSA_LV_OK;
3924 }
3925 
3926 static int hpsa_update_device_info(struct ctlr_info *h,
3927 	unsigned char scsi3addr[], struct hpsa_scsi_dev_t *this_device,
3928 	unsigned char *is_OBDR_device)
3929 {
3930 
3931 #define OBDR_SIG_OFFSET 43
3932 #define OBDR_TAPE_SIG "$DR-10"
3933 #define OBDR_SIG_LEN (sizeof(OBDR_TAPE_SIG) - 1)
3934 #define OBDR_TAPE_INQ_SIZE (OBDR_SIG_OFFSET + OBDR_SIG_LEN)
3935 
3936 	unsigned char *inq_buff;
3937 	unsigned char *obdr_sig;
3938 	int rc = 0;
3939 
3940 	inq_buff = kzalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
3941 	if (!inq_buff) {
3942 		rc = -ENOMEM;
3943 		goto bail_out;
3944 	}
3945 
3946 	/* Do an inquiry to the device to see what it is. */
3947 	if (hpsa_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
3948 		(unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
3949 		dev_err(&h->pdev->dev,
3950 			"%s: inquiry failed, device will be skipped.\n",
3951 			__func__);
3952 		rc = HPSA_INQUIRY_FAILED;
3953 		goto bail_out;
3954 	}
3955 
3956 	scsi_sanitize_inquiry_string(&inq_buff[8], 8);
3957 	scsi_sanitize_inquiry_string(&inq_buff[16], 16);
3958 
3959 	this_device->devtype = (inq_buff[0] & 0x1f);
3960 	memcpy(this_device->scsi3addr, scsi3addr, 8);
3961 	memcpy(this_device->vendor, &inq_buff[8],
3962 		sizeof(this_device->vendor));
3963 	memcpy(this_device->model, &inq_buff[16],
3964 		sizeof(this_device->model));
3965 	this_device->rev = inq_buff[2];
3966 	memset(this_device->device_id, 0,
3967 		sizeof(this_device->device_id));
3968 	if (hpsa_get_device_id(h, scsi3addr, this_device->device_id, 8,
3969 		sizeof(this_device->device_id)) < 0) {
3970 		dev_err(&h->pdev->dev,
3971 			"hpsa%d: %s: can't get device id for [%d:%d:%d:%d]\t%s\t%.16s\n",
3972 			h->ctlr, __func__,
3973 			h->scsi_host->host_no,
3974 			this_device->bus, this_device->target,
3975 			this_device->lun,
3976 			scsi_device_type(this_device->devtype),
3977 			this_device->model);
3978 		rc = HPSA_LV_FAILED;
3979 		goto bail_out;
3980 	}
3981 
3982 	if ((this_device->devtype == TYPE_DISK ||
3983 		this_device->devtype == TYPE_ZBC) &&
3984 		is_logical_dev_addr_mode(scsi3addr)) {
3985 		unsigned char volume_offline;
3986 
3987 		hpsa_get_raid_level(h, scsi3addr, &this_device->raid_level);
3988 		if (h->fw_support & MISC_FW_RAID_OFFLOAD_BASIC)
3989 			hpsa_get_ioaccel_status(h, scsi3addr, this_device);
3990 		volume_offline = hpsa_volume_offline(h, scsi3addr);
3991 		if (volume_offline == HPSA_VPD_LV_STATUS_UNSUPPORTED &&
3992 		    h->legacy_board) {
3993 			/*
3994 			 * Legacy boards might not support volume status
3995 			 */
3996 			dev_info(&h->pdev->dev,
3997 				 "C0:T%d:L%d Volume status not available, assuming online.\n",
3998 				 this_device->target, this_device->lun);
3999 			volume_offline = 0;
4000 		}
4001 		this_device->volume_offline = volume_offline;
4002 		if (volume_offline == HPSA_LV_FAILED) {
4003 			rc = HPSA_LV_FAILED;
4004 			dev_err(&h->pdev->dev,
4005 				"%s: LV failed, device will be skipped.\n",
4006 				__func__);
4007 			goto bail_out;
4008 		}
4009 	} else {
4010 		this_device->raid_level = RAID_UNKNOWN;
4011 		this_device->offload_config = 0;
4012 		hpsa_turn_off_ioaccel_for_device(this_device);
4013 		this_device->hba_ioaccel_enabled = 0;
4014 		this_device->volume_offline = 0;
4015 		this_device->queue_depth = h->nr_cmds;
4016 	}
4017 
4018 	if (this_device->external)
4019 		this_device->queue_depth = EXTERNAL_QD;
4020 
4021 	if (is_OBDR_device) {
4022 		/* See if this is a One-Button-Disaster-Recovery device
4023 		 * by looking for "$DR-10" at offset 43 in inquiry data.
4024 		 */
4025 		obdr_sig = &inq_buff[OBDR_SIG_OFFSET];
4026 		*is_OBDR_device = (this_device->devtype == TYPE_ROM &&
4027 					strncmp(obdr_sig, OBDR_TAPE_SIG,
4028 						OBDR_SIG_LEN) == 0);
4029 	}
4030 	kfree(inq_buff);
4031 	return 0;
4032 
4033 bail_out:
4034 	kfree(inq_buff);
4035 	return rc;
4036 }
4037 
4038 /*
4039  * Helper function to assign bus, target, lun mapping of devices.
4040  * Logical drive target and lun are assigned at this time, but
4041  * physical device lun and target assignment are deferred (assigned
4042  * in hpsa_find_target_lun, called by hpsa_scsi_add_entry.)
4043 */
4044 static void figure_bus_target_lun(struct ctlr_info *h,
4045 	u8 *lunaddrbytes, struct hpsa_scsi_dev_t *device)
4046 {
4047 	u32 lunid = get_unaligned_le32(lunaddrbytes);
4048 
4049 	if (!is_logical_dev_addr_mode(lunaddrbytes)) {
4050 		/* physical device, target and lun filled in later */
4051 		if (is_hba_lunid(lunaddrbytes)) {
4052 			int bus = HPSA_HBA_BUS;
4053 
4054 			if (!device->rev)
4055 				bus = HPSA_LEGACY_HBA_BUS;
4056 			hpsa_set_bus_target_lun(device,
4057 					bus, 0, lunid & 0x3fff);
4058 		} else
4059 			/* defer target, lun assignment for physical devices */
4060 			hpsa_set_bus_target_lun(device,
4061 					HPSA_PHYSICAL_DEVICE_BUS, -1, -1);
4062 		return;
4063 	}
4064 	/* It's a logical device */
4065 	if (device->external) {
4066 		hpsa_set_bus_target_lun(device,
4067 			HPSA_EXTERNAL_RAID_VOLUME_BUS, (lunid >> 16) & 0x3fff,
4068 			lunid & 0x00ff);
4069 		return;
4070 	}
4071 	hpsa_set_bus_target_lun(device, HPSA_RAID_VOLUME_BUS,
4072 				0, lunid & 0x3fff);
4073 }
4074 
4075 static int  figure_external_status(struct ctlr_info *h, int raid_ctlr_position,
4076 	int i, int nphysicals, int nlocal_logicals)
4077 {
4078 	/* In report logicals, local logicals are listed first,
4079 	* then any externals.
4080 	*/
4081 	int logicals_start = nphysicals + (raid_ctlr_position == 0);
4082 
4083 	if (i == raid_ctlr_position)
4084 		return 0;
4085 
4086 	if (i < logicals_start)
4087 		return 0;
4088 
4089 	/* i is in logicals range, but still within local logicals */
4090 	if ((i - nphysicals - (raid_ctlr_position == 0)) < nlocal_logicals)
4091 		return 0;
4092 
4093 	return 1; /* it's an external lun */
4094 }
4095 
4096 /*
4097  * Do CISS_REPORT_PHYS and CISS_REPORT_LOG.  Data is returned in physdev,
4098  * logdev.  The number of luns in physdev and logdev are returned in
4099  * *nphysicals and *nlogicals, respectively.
4100  * Returns 0 on success, -1 otherwise.
4101  */
4102 static int hpsa_gather_lun_info(struct ctlr_info *h,
4103 	struct ReportExtendedLUNdata *physdev, u32 *nphysicals,
4104 	struct ReportLUNdata *logdev, u32 *nlogicals)
4105 {
4106 	if (hpsa_scsi_do_report_phys_luns(h, physdev, sizeof(*physdev))) {
4107 		dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
4108 		return -1;
4109 	}
4110 	*nphysicals = be32_to_cpu(*((__be32 *)physdev->LUNListLength)) / 24;
4111 	if (*nphysicals > HPSA_MAX_PHYS_LUN) {
4112 		dev_warn(&h->pdev->dev, "maximum physical LUNs (%d) exceeded. %d LUNs ignored.\n",
4113 			HPSA_MAX_PHYS_LUN, *nphysicals - HPSA_MAX_PHYS_LUN);
4114 		*nphysicals = HPSA_MAX_PHYS_LUN;
4115 	}
4116 	if (hpsa_scsi_do_report_log_luns(h, logdev, sizeof(*logdev))) {
4117 		dev_err(&h->pdev->dev, "report logical LUNs failed.\n");
4118 		return -1;
4119 	}
4120 	*nlogicals = be32_to_cpu(*((__be32 *) logdev->LUNListLength)) / 8;
4121 	/* Reject Logicals in excess of our max capability. */
4122 	if (*nlogicals > HPSA_MAX_LUN) {
4123 		dev_warn(&h->pdev->dev,
4124 			"maximum logical LUNs (%d) exceeded.  "
4125 			"%d LUNs ignored.\n", HPSA_MAX_LUN,
4126 			*nlogicals - HPSA_MAX_LUN);
4127 		*nlogicals = HPSA_MAX_LUN;
4128 	}
4129 	if (*nlogicals + *nphysicals > HPSA_MAX_PHYS_LUN) {
4130 		dev_warn(&h->pdev->dev,
4131 			"maximum logical + physical LUNs (%d) exceeded. "
4132 			"%d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
4133 			*nphysicals + *nlogicals - HPSA_MAX_PHYS_LUN);
4134 		*nlogicals = HPSA_MAX_PHYS_LUN - *nphysicals;
4135 	}
4136 	return 0;
4137 }
4138 
4139 static u8 *figure_lunaddrbytes(struct ctlr_info *h, int raid_ctlr_position,
4140 	int i, int nphysicals, int nlogicals,
4141 	struct ReportExtendedLUNdata *physdev_list,
4142 	struct ReportLUNdata *logdev_list)
4143 {
4144 	/* Helper function, figure out where the LUN ID info is coming from
4145 	 * given index i, lists of physical and logical devices, where in
4146 	 * the list the raid controller is supposed to appear (first or last)
4147 	 */
4148 
4149 	int logicals_start = nphysicals + (raid_ctlr_position == 0);
4150 	int last_device = nphysicals + nlogicals + (raid_ctlr_position == 0);
4151 
4152 	if (i == raid_ctlr_position)
4153 		return RAID_CTLR_LUNID;
4154 
4155 	if (i < logicals_start)
4156 		return &physdev_list->LUN[i -
4157 				(raid_ctlr_position == 0)].lunid[0];
4158 
4159 	if (i < last_device)
4160 		return &logdev_list->LUN[i - nphysicals -
4161 			(raid_ctlr_position == 0)][0];
4162 	BUG();
4163 	return NULL;
4164 }
4165 
4166 /* get physical drive ioaccel handle and queue depth */
4167 static void hpsa_get_ioaccel_drive_info(struct ctlr_info *h,
4168 		struct hpsa_scsi_dev_t *dev,
4169 		struct ReportExtendedLUNdata *rlep, int rle_index,
4170 		struct bmic_identify_physical_device *id_phys)
4171 {
4172 	int rc;
4173 	struct ext_report_lun_entry *rle;
4174 
4175 	if (rle_index < 0 || rle_index >= HPSA_MAX_PHYS_LUN)
4176 		return;
4177 
4178 	rle = &rlep->LUN[rle_index];
4179 
4180 	dev->ioaccel_handle = rle->ioaccel_handle;
4181 	if ((rle->device_flags & 0x08) && dev->ioaccel_handle)
4182 		dev->hba_ioaccel_enabled = 1;
4183 	memset(id_phys, 0, sizeof(*id_phys));
4184 	rc = hpsa_bmic_id_physical_device(h, &rle->lunid[0],
4185 			GET_BMIC_DRIVE_NUMBER(&rle->lunid[0]), id_phys,
4186 			sizeof(*id_phys));
4187 	if (!rc)
4188 		/* Reserve space for FW operations */
4189 #define DRIVE_CMDS_RESERVED_FOR_FW 2
4190 #define DRIVE_QUEUE_DEPTH 7
4191 		dev->queue_depth =
4192 			le16_to_cpu(id_phys->current_queue_depth_limit) -
4193 				DRIVE_CMDS_RESERVED_FOR_FW;
4194 	else
4195 		dev->queue_depth = DRIVE_QUEUE_DEPTH; /* conservative */
4196 }
4197 
4198 static void hpsa_get_path_info(struct hpsa_scsi_dev_t *this_device,
4199 	struct ReportExtendedLUNdata *rlep, int rle_index,
4200 	struct bmic_identify_physical_device *id_phys)
4201 {
4202 	struct ext_report_lun_entry *rle;
4203 
4204 	if (rle_index < 0 || rle_index >= HPSA_MAX_PHYS_LUN)
4205 		return;
4206 
4207 	rle = &rlep->LUN[rle_index];
4208 
4209 	if ((rle->device_flags & 0x08) && this_device->ioaccel_handle)
4210 		this_device->hba_ioaccel_enabled = 1;
4211 
4212 	memcpy(&this_device->active_path_index,
4213 		&id_phys->active_path_number,
4214 		sizeof(this_device->active_path_index));
4215 	memcpy(&this_device->path_map,
4216 		&id_phys->redundant_path_present_map,
4217 		sizeof(this_device->path_map));
4218 	memcpy(&this_device->box,
4219 		&id_phys->alternate_paths_phys_box_on_port,
4220 		sizeof(this_device->box));
4221 	memcpy(&this_device->phys_connector,
4222 		&id_phys->alternate_paths_phys_connector,
4223 		sizeof(this_device->phys_connector));
4224 	memcpy(&this_device->bay,
4225 		&id_phys->phys_bay_in_box,
4226 		sizeof(this_device->bay));
4227 }
4228 
4229 /* get number of local logical disks. */
4230 static int hpsa_set_local_logical_count(struct ctlr_info *h,
4231 	struct bmic_identify_controller *id_ctlr,
4232 	u32 *nlocals)
4233 {
4234 	int rc;
4235 
4236 	if (!id_ctlr) {
4237 		dev_warn(&h->pdev->dev, "%s: id_ctlr buffer is NULL.\n",
4238 			__func__);
4239 		return -ENOMEM;
4240 	}
4241 	memset(id_ctlr, 0, sizeof(*id_ctlr));
4242 	rc = hpsa_bmic_id_controller(h, id_ctlr, sizeof(*id_ctlr));
4243 	if (!rc)
4244 		if (id_ctlr->configured_logical_drive_count < 255)
4245 			*nlocals = id_ctlr->configured_logical_drive_count;
4246 		else
4247 			*nlocals = le16_to_cpu(
4248 					id_ctlr->extended_logical_unit_count);
4249 	else
4250 		*nlocals = -1;
4251 	return rc;
4252 }
4253 
4254 static bool hpsa_is_disk_spare(struct ctlr_info *h, u8 *lunaddrbytes)
4255 {
4256 	struct bmic_identify_physical_device *id_phys;
4257 	bool is_spare = false;
4258 	int rc;
4259 
4260 	id_phys = kzalloc_obj(*id_phys);
4261 	if (!id_phys)
4262 		return false;
4263 
4264 	rc = hpsa_bmic_id_physical_device(h,
4265 					lunaddrbytes,
4266 					GET_BMIC_DRIVE_NUMBER(lunaddrbytes),
4267 					id_phys, sizeof(*id_phys));
4268 	if (rc == 0)
4269 		is_spare = (id_phys->more_flags >> 6) & 0x01;
4270 
4271 	kfree(id_phys);
4272 	return is_spare;
4273 }
4274 
4275 #define RPL_DEV_FLAG_NON_DISK                           0x1
4276 #define RPL_DEV_FLAG_UNCONFIG_DISK_REPORTING_SUPPORTED  0x2
4277 #define RPL_DEV_FLAG_UNCONFIG_DISK                      0x4
4278 
4279 #define BMIC_DEVICE_TYPE_ENCLOSURE  6
4280 
4281 static bool hpsa_skip_device(struct ctlr_info *h, u8 *lunaddrbytes,
4282 				struct ext_report_lun_entry *rle)
4283 {
4284 	u8 device_flags;
4285 	u8 device_type;
4286 
4287 	if (!MASKED_DEVICE(lunaddrbytes))
4288 		return false;
4289 
4290 	device_flags = rle->device_flags;
4291 	device_type = rle->device_type;
4292 
4293 	if (device_flags & RPL_DEV_FLAG_NON_DISK) {
4294 		if (device_type == BMIC_DEVICE_TYPE_ENCLOSURE)
4295 			return false;
4296 		return true;
4297 	}
4298 
4299 	if (!(device_flags & RPL_DEV_FLAG_UNCONFIG_DISK_REPORTING_SUPPORTED))
4300 		return false;
4301 
4302 	if (device_flags & RPL_DEV_FLAG_UNCONFIG_DISK)
4303 		return false;
4304 
4305 	/*
4306 	 * Spares may be spun down, we do not want to
4307 	 * do an Inquiry to a RAID set spare drive as
4308 	 * that would have them spun up, that is a
4309 	 * performance hit because I/O to the RAID device
4310 	 * stops while the spin up occurs which can take
4311 	 * over 50 seconds.
4312 	 */
4313 	if (hpsa_is_disk_spare(h, lunaddrbytes))
4314 		return true;
4315 
4316 	return false;
4317 }
4318 
4319 static void hpsa_update_scsi_devices(struct ctlr_info *h)
4320 {
4321 	/* the idea here is we could get notified
4322 	 * that some devices have changed, so we do a report
4323 	 * physical luns and report logical luns cmd, and adjust
4324 	 * our list of devices accordingly.
4325 	 *
4326 	 * The scsi3addr's of devices won't change so long as the
4327 	 * adapter is not reset.  That means we can rescan and
4328 	 * tell which devices we already know about, vs. new
4329 	 * devices, vs.  disappearing devices.
4330 	 */
4331 	struct ReportExtendedLUNdata *physdev_list = NULL;
4332 	struct ReportLUNdata *logdev_list = NULL;
4333 	struct bmic_identify_physical_device *id_phys = NULL;
4334 	struct bmic_identify_controller *id_ctlr = NULL;
4335 	u32 nphysicals = 0;
4336 	u32 nlogicals = 0;
4337 	u32 nlocal_logicals = 0;
4338 	u32 ndev_allocated = 0;
4339 	struct hpsa_scsi_dev_t **currentsd, *this_device, *tmpdevice;
4340 	int ncurrent = 0;
4341 	int i, ndevs_to_allocate;
4342 	int raid_ctlr_position;
4343 	bool physical_device;
4344 
4345 	currentsd = kzalloc_objs(*currentsd, HPSA_MAX_DEVICES);
4346 	physdev_list = kzalloc_obj(*physdev_list);
4347 	logdev_list = kzalloc_obj(*logdev_list);
4348 	tmpdevice = kzalloc_obj(*tmpdevice);
4349 	id_phys = kzalloc_obj(*id_phys);
4350 	id_ctlr = kzalloc_obj(*id_ctlr);
4351 
4352 	if (!currentsd || !physdev_list || !logdev_list ||
4353 		!tmpdevice || !id_phys || !id_ctlr) {
4354 		dev_err(&h->pdev->dev, "out of memory\n");
4355 		goto out;
4356 	}
4357 
4358 	h->drv_req_rescan = 0; /* cancel scheduled rescan - we're doing it. */
4359 
4360 	if (hpsa_gather_lun_info(h, physdev_list, &nphysicals,
4361 			logdev_list, &nlogicals)) {
4362 		h->drv_req_rescan = 1;
4363 		goto out;
4364 	}
4365 
4366 	/* Set number of local logicals (non PTRAID) */
4367 	if (hpsa_set_local_logical_count(h, id_ctlr, &nlocal_logicals)) {
4368 		dev_warn(&h->pdev->dev,
4369 			"%s: Can't determine number of local logical devices.\n",
4370 			__func__);
4371 	}
4372 
4373 	/* We might see up to the maximum number of logical and physical disks
4374 	 * plus external target devices, and a device for the local RAID
4375 	 * controller.
4376 	 */
4377 	ndevs_to_allocate = nphysicals + nlogicals + MAX_EXT_TARGETS + 1;
4378 
4379 	hpsa_ext_ctrl_present(h, physdev_list);
4380 
4381 	/* Allocate the per device structures */
4382 	for (i = 0; i < ndevs_to_allocate; i++) {
4383 		if (i >= HPSA_MAX_DEVICES) {
4384 			dev_warn(&h->pdev->dev, "maximum devices (%d) exceeded."
4385 				"  %d devices ignored.\n", HPSA_MAX_DEVICES,
4386 				ndevs_to_allocate - HPSA_MAX_DEVICES);
4387 			break;
4388 		}
4389 
4390 		currentsd[i] = kzalloc_obj(*currentsd[i]);
4391 		if (!currentsd[i]) {
4392 			h->drv_req_rescan = 1;
4393 			goto out;
4394 		}
4395 		ndev_allocated++;
4396 	}
4397 
4398 	if (is_scsi_rev_5(h))
4399 		raid_ctlr_position = 0;
4400 	else
4401 		raid_ctlr_position = nphysicals + nlogicals;
4402 
4403 	/* adjust our table of devices */
4404 	for (i = 0; i < nphysicals + nlogicals + 1; i++) {
4405 		u8 *lunaddrbytes, is_OBDR = 0;
4406 		int rc = 0;
4407 		int phys_dev_index = i - (raid_ctlr_position == 0);
4408 		bool skip_device = false;
4409 
4410 		memset(tmpdevice, 0, sizeof(*tmpdevice));
4411 
4412 		physical_device = i < nphysicals + (raid_ctlr_position == 0);
4413 
4414 		/* Figure out where the LUN ID info is coming from */
4415 		lunaddrbytes = figure_lunaddrbytes(h, raid_ctlr_position,
4416 			i, nphysicals, nlogicals, physdev_list, logdev_list);
4417 
4418 		/* Determine if this is a lun from an external target array */
4419 		tmpdevice->external =
4420 			figure_external_status(h, raid_ctlr_position, i,
4421 						nphysicals, nlocal_logicals);
4422 
4423 		/*
4424 		 * Skip over some devices such as a spare.
4425 		 */
4426 		if (phys_dev_index >= 0 && !tmpdevice->external &&
4427 			physical_device) {
4428 			skip_device = hpsa_skip_device(h, lunaddrbytes,
4429 					&physdev_list->LUN[phys_dev_index]);
4430 			if (skip_device)
4431 				continue;
4432 		}
4433 
4434 		/* Get device type, vendor, model, device id, raid_map */
4435 		rc = hpsa_update_device_info(h, lunaddrbytes, tmpdevice,
4436 							&is_OBDR);
4437 		if (rc == -ENOMEM) {
4438 			dev_warn(&h->pdev->dev,
4439 				"Out of memory, rescan deferred.\n");
4440 			h->drv_req_rescan = 1;
4441 			goto out;
4442 		}
4443 		if (rc) {
4444 			h->drv_req_rescan = 1;
4445 			continue;
4446 		}
4447 
4448 		figure_bus_target_lun(h, lunaddrbytes, tmpdevice);
4449 		this_device = currentsd[ncurrent];
4450 
4451 		*this_device = *tmpdevice;
4452 		this_device->physical_device = physical_device;
4453 
4454 		/*
4455 		 * Expose all devices except for physical devices that
4456 		 * are masked.
4457 		 */
4458 		if (MASKED_DEVICE(lunaddrbytes) && this_device->physical_device)
4459 			this_device->expose_device = 0;
4460 		else
4461 			this_device->expose_device = 1;
4462 
4463 
4464 		/*
4465 		 * Get the SAS address for physical devices that are exposed.
4466 		 */
4467 		if (this_device->physical_device && this_device->expose_device)
4468 			hpsa_get_sas_address(h, lunaddrbytes, this_device);
4469 
4470 		switch (this_device->devtype) {
4471 		case TYPE_ROM:
4472 			/* We don't *really* support actual CD-ROM devices,
4473 			 * just "One Button Disaster Recovery" tape drive
4474 			 * which temporarily pretends to be a CD-ROM drive.
4475 			 * So we check that the device is really an OBDR tape
4476 			 * device by checking for "$DR-10" in bytes 43-48 of
4477 			 * the inquiry data.
4478 			 */
4479 			if (is_OBDR)
4480 				ncurrent++;
4481 			break;
4482 		case TYPE_DISK:
4483 		case TYPE_ZBC:
4484 			if (this_device->physical_device) {
4485 				/* The disk is in HBA mode. */
4486 				/* Never use RAID mapper in HBA mode. */
4487 				this_device->offload_enabled = 0;
4488 				hpsa_get_ioaccel_drive_info(h, this_device,
4489 					physdev_list, phys_dev_index, id_phys);
4490 				hpsa_get_path_info(this_device,
4491 					physdev_list, phys_dev_index, id_phys);
4492 			}
4493 			ncurrent++;
4494 			break;
4495 		case TYPE_TAPE:
4496 		case TYPE_MEDIUM_CHANGER:
4497 			ncurrent++;
4498 			break;
4499 		case TYPE_ENCLOSURE:
4500 			if (!this_device->external)
4501 				hpsa_get_enclosure_info(h, lunaddrbytes,
4502 						physdev_list, phys_dev_index,
4503 						this_device);
4504 			ncurrent++;
4505 			break;
4506 		case TYPE_RAID:
4507 			/* Only present the Smartarray HBA as a RAID controller.
4508 			 * If it's a RAID controller other than the HBA itself
4509 			 * (an external RAID controller, MSA500 or similar)
4510 			 * don't present it.
4511 			 */
4512 			if (!is_hba_lunid(lunaddrbytes))
4513 				break;
4514 			ncurrent++;
4515 			break;
4516 		default:
4517 			break;
4518 		}
4519 		if (ncurrent >= HPSA_MAX_DEVICES)
4520 			break;
4521 	}
4522 
4523 	if (h->sas_host == NULL) {
4524 		int rc = 0;
4525 
4526 		rc = hpsa_add_sas_host(h);
4527 		if (rc) {
4528 			dev_warn(&h->pdev->dev,
4529 				"Could not add sas host %d\n", rc);
4530 			goto out;
4531 		}
4532 	}
4533 
4534 	adjust_hpsa_scsi_table(h, currentsd, ncurrent);
4535 out:
4536 	kfree(tmpdevice);
4537 	for (i = 0; i < ndev_allocated; i++)
4538 		kfree(currentsd[i]);
4539 	kfree(currentsd);
4540 	kfree(physdev_list);
4541 	kfree(logdev_list);
4542 	kfree(id_ctlr);
4543 	kfree(id_phys);
4544 }
4545 
4546 static void hpsa_set_sg_descriptor(struct SGDescriptor *desc,
4547 				   struct scatterlist *sg)
4548 {
4549 	u64 addr64 = (u64) sg_dma_address(sg);
4550 	unsigned int len = sg_dma_len(sg);
4551 
4552 	desc->Addr = cpu_to_le64(addr64);
4553 	desc->Len = cpu_to_le32(len);
4554 	desc->Ext = 0;
4555 }
4556 
4557 /*
4558  * hpsa_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
4559  * dma mapping  and fills in the scatter gather entries of the
4560  * hpsa command, cp.
4561  */
4562 static int hpsa_scatter_gather(struct ctlr_info *h,
4563 		struct CommandList *cp,
4564 		struct scsi_cmnd *cmd)
4565 {
4566 	struct scatterlist *sg;
4567 	int use_sg, i, sg_limit, chained;
4568 	struct SGDescriptor *curr_sg;
4569 
4570 	BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
4571 
4572 	use_sg = scsi_dma_map(cmd);
4573 	if (use_sg < 0)
4574 		return use_sg;
4575 
4576 	if (!use_sg)
4577 		goto sglist_finished;
4578 
4579 	/*
4580 	 * If the number of entries is greater than the max for a single list,
4581 	 * then we have a chained list; we will set up all but one entry in the
4582 	 * first list (the last entry is saved for link information);
4583 	 * otherwise, we don't have a chained list and we'll set up at each of
4584 	 * the entries in the one list.
4585 	 */
4586 	curr_sg = cp->SG;
4587 	chained = use_sg > h->max_cmd_sg_entries;
4588 	sg_limit = chained ? h->max_cmd_sg_entries - 1 : use_sg;
4589 	scsi_for_each_sg(cmd, sg, sg_limit, i) {
4590 		hpsa_set_sg_descriptor(curr_sg, sg);
4591 		curr_sg++;
4592 	}
4593 
4594 	if (chained) {
4595 		/*
4596 		 * Continue with the chained list.  Set curr_sg to the chained
4597 		 * list.  Modify the limit to the total count less the entries
4598 		 * we've already set up.  Resume the scan at the list entry
4599 		 * where the previous loop left off.
4600 		 */
4601 		curr_sg = h->cmd_sg_list[cp->cmdindex];
4602 		sg_limit = use_sg - sg_limit;
4603 		for_each_sg(sg, sg, sg_limit, i) {
4604 			hpsa_set_sg_descriptor(curr_sg, sg);
4605 			curr_sg++;
4606 		}
4607 	}
4608 
4609 	/* Back the pointer up to the last entry and mark it as "last". */
4610 	(curr_sg - 1)->Ext = cpu_to_le32(HPSA_SG_LAST);
4611 
4612 	if (use_sg + chained > h->maxSG)
4613 		h->maxSG = use_sg + chained;
4614 
4615 	if (chained) {
4616 		cp->Header.SGList = h->max_cmd_sg_entries;
4617 		cp->Header.SGTotal = cpu_to_le16(use_sg + 1);
4618 		if (hpsa_map_sg_chain_block(h, cp)) {
4619 			scsi_dma_unmap(cmd);
4620 			return -1;
4621 		}
4622 		return 0;
4623 	}
4624 
4625 sglist_finished:
4626 
4627 	cp->Header.SGList = (u8) use_sg;   /* no. SGs contig in this cmd */
4628 	cp->Header.SGTotal = cpu_to_le16(use_sg); /* total sgs in cmd list */
4629 	return 0;
4630 }
4631 
4632 static inline void warn_zero_length_transfer(struct ctlr_info *h,
4633 						u8 *cdb, int cdb_len,
4634 						const char *func)
4635 {
4636 	dev_warn(&h->pdev->dev,
4637 		 "%s: Blocking zero-length request: CDB:%*phN\n",
4638 		 func, cdb_len, cdb);
4639 }
4640 
4641 #define IO_ACCEL_INELIGIBLE 1
4642 /* zero-length transfers trigger hardware errors. */
4643 static bool is_zero_length_transfer(u8 *cdb)
4644 {
4645 	u32 block_cnt;
4646 
4647 	/* Block zero-length transfer sizes on certain commands. */
4648 	switch (cdb[0]) {
4649 	case READ_10:
4650 	case WRITE_10:
4651 	case VERIFY:		/* 0x2F */
4652 	case WRITE_VERIFY:	/* 0x2E */
4653 		block_cnt = get_unaligned_be16(&cdb[7]);
4654 		break;
4655 	case READ_12:
4656 	case WRITE_12:
4657 	case VERIFY_12: /* 0xAF */
4658 	case WRITE_VERIFY_12:	/* 0xAE */
4659 		block_cnt = get_unaligned_be32(&cdb[6]);
4660 		break;
4661 	case READ_16:
4662 	case WRITE_16:
4663 	case VERIFY_16:		/* 0x8F */
4664 		block_cnt = get_unaligned_be32(&cdb[10]);
4665 		break;
4666 	default:
4667 		return false;
4668 	}
4669 
4670 	return block_cnt == 0;
4671 }
4672 
4673 static int fixup_ioaccel_cdb(u8 *cdb, int *cdb_len)
4674 {
4675 	int is_write = 0;
4676 	u32 block;
4677 	u32 block_cnt;
4678 
4679 	/* Perform some CDB fixups if needed using 10 byte reads/writes only */
4680 	switch (cdb[0]) {
4681 	case WRITE_6:
4682 	case WRITE_12:
4683 		is_write = 1;
4684 		fallthrough;
4685 	case READ_6:
4686 	case READ_12:
4687 		if (*cdb_len == 6) {
4688 			block = (((cdb[1] & 0x1F) << 16) |
4689 				(cdb[2] << 8) |
4690 				cdb[3]);
4691 			block_cnt = cdb[4];
4692 			if (block_cnt == 0)
4693 				block_cnt = 256;
4694 		} else {
4695 			BUG_ON(*cdb_len != 12);
4696 			block = get_unaligned_be32(&cdb[2]);
4697 			block_cnt = get_unaligned_be32(&cdb[6]);
4698 		}
4699 		if (block_cnt > 0xffff)
4700 			return IO_ACCEL_INELIGIBLE;
4701 
4702 		cdb[0] = is_write ? WRITE_10 : READ_10;
4703 		cdb[1] = 0;
4704 		cdb[2] = (u8) (block >> 24);
4705 		cdb[3] = (u8) (block >> 16);
4706 		cdb[4] = (u8) (block >> 8);
4707 		cdb[5] = (u8) (block);
4708 		cdb[6] = 0;
4709 		cdb[7] = (u8) (block_cnt >> 8);
4710 		cdb[8] = (u8) (block_cnt);
4711 		cdb[9] = 0;
4712 		*cdb_len = 10;
4713 		break;
4714 	}
4715 	return 0;
4716 }
4717 
4718 static int hpsa_scsi_ioaccel1_queue_command(struct ctlr_info *h,
4719 	struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
4720 	u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk)
4721 {
4722 	struct scsi_cmnd *cmd = c->scsi_cmd;
4723 	struct io_accel1_cmd *cp = &h->ioaccel_cmd_pool[c->cmdindex];
4724 	unsigned int len;
4725 	unsigned int total_len = 0;
4726 	struct scatterlist *sg;
4727 	u64 addr64;
4728 	int use_sg, i;
4729 	struct SGDescriptor *curr_sg;
4730 	u32 control = IOACCEL1_CONTROL_SIMPLEQUEUE;
4731 
4732 	/* TODO: implement chaining support */
4733 	if (scsi_sg_count(cmd) > h->ioaccel_maxsg) {
4734 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4735 		return IO_ACCEL_INELIGIBLE;
4736 	}
4737 
4738 	BUG_ON(cmd->cmd_len > IOACCEL1_IOFLAGS_CDBLEN_MAX);
4739 
4740 	if (is_zero_length_transfer(cdb)) {
4741 		warn_zero_length_transfer(h, cdb, cdb_len, __func__);
4742 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4743 		return IO_ACCEL_INELIGIBLE;
4744 	}
4745 
4746 	if (fixup_ioaccel_cdb(cdb, &cdb_len)) {
4747 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4748 		return IO_ACCEL_INELIGIBLE;
4749 	}
4750 
4751 	c->cmd_type = CMD_IOACCEL1;
4752 
4753 	/* Adjust the DMA address to point to the accelerated command buffer */
4754 	c->busaddr = (u32) h->ioaccel_cmd_pool_dhandle +
4755 				(c->cmdindex * sizeof(*cp));
4756 	BUG_ON(c->busaddr & 0x0000007F);
4757 
4758 	use_sg = scsi_dma_map(cmd);
4759 	if (use_sg < 0) {
4760 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4761 		return use_sg;
4762 	}
4763 
4764 	if (use_sg) {
4765 		curr_sg = cp->SG;
4766 		scsi_for_each_sg(cmd, sg, use_sg, i) {
4767 			addr64 = (u64) sg_dma_address(sg);
4768 			len  = sg_dma_len(sg);
4769 			total_len += len;
4770 			curr_sg->Addr = cpu_to_le64(addr64);
4771 			curr_sg->Len = cpu_to_le32(len);
4772 			curr_sg->Ext = cpu_to_le32(0);
4773 			curr_sg++;
4774 		}
4775 		(--curr_sg)->Ext = cpu_to_le32(HPSA_SG_LAST);
4776 
4777 		switch (cmd->sc_data_direction) {
4778 		case DMA_TO_DEVICE:
4779 			control |= IOACCEL1_CONTROL_DATA_OUT;
4780 			break;
4781 		case DMA_FROM_DEVICE:
4782 			control |= IOACCEL1_CONTROL_DATA_IN;
4783 			break;
4784 		case DMA_NONE:
4785 			control |= IOACCEL1_CONTROL_NODATAXFER;
4786 			break;
4787 		default:
4788 			dev_err(&h->pdev->dev, "unknown data direction: %d\n",
4789 			cmd->sc_data_direction);
4790 			BUG();
4791 			break;
4792 		}
4793 	} else {
4794 		control |= IOACCEL1_CONTROL_NODATAXFER;
4795 	}
4796 
4797 	c->Header.SGList = use_sg;
4798 	/* Fill out the command structure to submit */
4799 	cp->dev_handle = cpu_to_le16(ioaccel_handle & 0xFFFF);
4800 	cp->transfer_len = cpu_to_le32(total_len);
4801 	cp->io_flags = cpu_to_le16(IOACCEL1_IOFLAGS_IO_REQ |
4802 			(cdb_len & IOACCEL1_IOFLAGS_CDBLEN_MASK));
4803 	cp->control = cpu_to_le32(control);
4804 	memcpy(cp->CDB, cdb, cdb_len);
4805 	memcpy(cp->CISS_LUN, scsi3addr, 8);
4806 	/* Tag was already set at init time. */
4807 	enqueue_cmd_and_start_io(h, c);
4808 	return 0;
4809 }
4810 
4811 /*
4812  * Queue a command directly to a device behind the controller using the
4813  * I/O accelerator path.
4814  */
4815 static int hpsa_scsi_ioaccel_direct_map(struct ctlr_info *h,
4816 	struct CommandList *c)
4817 {
4818 	struct scsi_cmnd *cmd = c->scsi_cmd;
4819 	struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
4820 
4821 	if (!dev)
4822 		return -1;
4823 
4824 	c->phys_disk = dev;
4825 
4826 	if (dev->in_reset)
4827 		return -1;
4828 
4829 	return hpsa_scsi_ioaccel_queue_command(h, c, dev->ioaccel_handle,
4830 		cmd->cmnd, cmd->cmd_len, dev->scsi3addr, dev);
4831 }
4832 
4833 /*
4834  * Set encryption parameters for the ioaccel2 request
4835  */
4836 static void set_encrypt_ioaccel2(struct ctlr_info *h,
4837 	struct CommandList *c, struct io_accel2_cmd *cp)
4838 {
4839 	struct scsi_cmnd *cmd = c->scsi_cmd;
4840 	struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
4841 	struct raid_map_data *map = &dev->raid_map;
4842 	u64 first_block;
4843 
4844 	/* Are we doing encryption on this device */
4845 	if (!(le16_to_cpu(map->flags) & RAID_MAP_FLAG_ENCRYPT_ON))
4846 		return;
4847 	/* Set the data encryption key index. */
4848 	cp->dekindex = map->dekindex;
4849 
4850 	/* Set the encryption enable flag, encoded into direction field. */
4851 	cp->direction |= IOACCEL2_DIRECTION_ENCRYPT_MASK;
4852 
4853 	/* Set encryption tweak values based on logical block address
4854 	 * If block size is 512, tweak value is LBA.
4855 	 * For other block sizes, tweak is (LBA * block size)/ 512)
4856 	 */
4857 	switch (cmd->cmnd[0]) {
4858 	/* Required? 6-byte cdbs eliminated by fixup_ioaccel_cdb */
4859 	case READ_6:
4860 	case WRITE_6:
4861 		first_block = (((cmd->cmnd[1] & 0x1F) << 16) |
4862 				(cmd->cmnd[2] << 8) |
4863 				cmd->cmnd[3]);
4864 		break;
4865 	case WRITE_10:
4866 	case READ_10:
4867 	/* Required? 12-byte cdbs eliminated by fixup_ioaccel_cdb */
4868 	case WRITE_12:
4869 	case READ_12:
4870 		first_block = get_unaligned_be32(&cmd->cmnd[2]);
4871 		break;
4872 	case WRITE_16:
4873 	case READ_16:
4874 		first_block = get_unaligned_be64(&cmd->cmnd[2]);
4875 		break;
4876 	default:
4877 		dev_err(&h->pdev->dev,
4878 			"ERROR: %s: size (0x%x) not supported for encryption\n",
4879 			__func__, cmd->cmnd[0]);
4880 		BUG();
4881 		break;
4882 	}
4883 
4884 	if (le32_to_cpu(map->volume_blk_size) != 512)
4885 		first_block = first_block *
4886 				le32_to_cpu(map->volume_blk_size)/512;
4887 
4888 	cp->tweak_lower = cpu_to_le32(first_block);
4889 	cp->tweak_upper = cpu_to_le32(first_block >> 32);
4890 }
4891 
4892 static int hpsa_scsi_ioaccel2_queue_command(struct ctlr_info *h,
4893 	struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
4894 	u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk)
4895 {
4896 	struct scsi_cmnd *cmd = c->scsi_cmd;
4897 	struct io_accel2_cmd *cp = &h->ioaccel2_cmd_pool[c->cmdindex];
4898 	struct ioaccel2_sg_element *curr_sg;
4899 	int use_sg, i;
4900 	struct scatterlist *sg;
4901 	u64 addr64;
4902 	u32 len;
4903 	u32 total_len = 0;
4904 
4905 	if (!cmd->device)
4906 		return -1;
4907 
4908 	if (!cmd->device->hostdata)
4909 		return -1;
4910 
4911 	BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
4912 
4913 	if (is_zero_length_transfer(cdb)) {
4914 		warn_zero_length_transfer(h, cdb, cdb_len, __func__);
4915 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4916 		return IO_ACCEL_INELIGIBLE;
4917 	}
4918 
4919 	if (fixup_ioaccel_cdb(cdb, &cdb_len)) {
4920 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4921 		return IO_ACCEL_INELIGIBLE;
4922 	}
4923 
4924 	c->cmd_type = CMD_IOACCEL2;
4925 	/* Adjust the DMA address to point to the accelerated command buffer */
4926 	c->busaddr = (u32) h->ioaccel2_cmd_pool_dhandle +
4927 				(c->cmdindex * sizeof(*cp));
4928 	BUG_ON(c->busaddr & 0x0000007F);
4929 
4930 	memset(cp, 0, sizeof(*cp));
4931 	cp->IU_type = IOACCEL2_IU_TYPE;
4932 
4933 	use_sg = scsi_dma_map(cmd);
4934 	if (use_sg < 0) {
4935 		atomic_dec(&phys_disk->ioaccel_cmds_out);
4936 		return use_sg;
4937 	}
4938 
4939 	if (use_sg) {
4940 		curr_sg = cp->sg;
4941 		if (use_sg > h->ioaccel_maxsg) {
4942 			addr64 = le64_to_cpu(
4943 				h->ioaccel2_cmd_sg_list[c->cmdindex]->address);
4944 			curr_sg->address = cpu_to_le64(addr64);
4945 			curr_sg->length = 0;
4946 			curr_sg->reserved[0] = 0;
4947 			curr_sg->reserved[1] = 0;
4948 			curr_sg->reserved[2] = 0;
4949 			curr_sg->chain_indicator = IOACCEL2_CHAIN;
4950 
4951 			curr_sg = h->ioaccel2_cmd_sg_list[c->cmdindex];
4952 		}
4953 		scsi_for_each_sg(cmd, sg, use_sg, i) {
4954 			addr64 = (u64) sg_dma_address(sg);
4955 			len  = sg_dma_len(sg);
4956 			total_len += len;
4957 			curr_sg->address = cpu_to_le64(addr64);
4958 			curr_sg->length = cpu_to_le32(len);
4959 			curr_sg->reserved[0] = 0;
4960 			curr_sg->reserved[1] = 0;
4961 			curr_sg->reserved[2] = 0;
4962 			curr_sg->chain_indicator = 0;
4963 			curr_sg++;
4964 		}
4965 
4966 		/*
4967 		 * Set the last s/g element bit
4968 		 */
4969 		(curr_sg - 1)->chain_indicator = IOACCEL2_LAST_SG;
4970 
4971 		switch (cmd->sc_data_direction) {
4972 		case DMA_TO_DEVICE:
4973 			cp->direction &= ~IOACCEL2_DIRECTION_MASK;
4974 			cp->direction |= IOACCEL2_DIR_DATA_OUT;
4975 			break;
4976 		case DMA_FROM_DEVICE:
4977 			cp->direction &= ~IOACCEL2_DIRECTION_MASK;
4978 			cp->direction |= IOACCEL2_DIR_DATA_IN;
4979 			break;
4980 		case DMA_NONE:
4981 			cp->direction &= ~IOACCEL2_DIRECTION_MASK;
4982 			cp->direction |= IOACCEL2_DIR_NO_DATA;
4983 			break;
4984 		default:
4985 			dev_err(&h->pdev->dev, "unknown data direction: %d\n",
4986 				cmd->sc_data_direction);
4987 			BUG();
4988 			break;
4989 		}
4990 	} else {
4991 		cp->direction &= ~IOACCEL2_DIRECTION_MASK;
4992 		cp->direction |= IOACCEL2_DIR_NO_DATA;
4993 	}
4994 
4995 	/* Set encryption parameters, if necessary */
4996 	set_encrypt_ioaccel2(h, c, cp);
4997 
4998 	cp->scsi_nexus = cpu_to_le32(ioaccel_handle);
4999 	cp->Tag = cpu_to_le32(c->cmdindex << DIRECT_LOOKUP_SHIFT);
5000 	memcpy(cp->cdb, cdb, sizeof(cp->cdb));
5001 
5002 	cp->data_len = cpu_to_le32(total_len);
5003 	cp->err_ptr = cpu_to_le64(c->busaddr +
5004 			offsetof(struct io_accel2_cmd, error_data));
5005 	cp->err_len = cpu_to_le32(sizeof(cp->error_data));
5006 
5007 	/* fill in sg elements */
5008 	if (use_sg > h->ioaccel_maxsg) {
5009 		cp->sg_count = 1;
5010 		cp->sg[0].length = cpu_to_le32(use_sg * sizeof(cp->sg[0]));
5011 		if (hpsa_map_ioaccel2_sg_chain_block(h, cp, c)) {
5012 			atomic_dec(&phys_disk->ioaccel_cmds_out);
5013 			scsi_dma_unmap(cmd);
5014 			return -1;
5015 		}
5016 	} else
5017 		cp->sg_count = (u8) use_sg;
5018 
5019 	if (phys_disk->in_reset) {
5020 		cmd->result = DID_RESET << 16;
5021 		atomic_dec(&phys_disk->ioaccel_cmds_out);
5022 		scsi_dma_unmap(cmd);
5023 		if (use_sg > h->ioaccel_maxsg)
5024 			hpsa_unmap_ioaccel2_sg_chain_block(h, cp);
5025 		return -1;
5026 	}
5027 
5028 	enqueue_cmd_and_start_io(h, c);
5029 	return 0;
5030 }
5031 
5032 /*
5033  * Queue a command to the correct I/O accelerator path.
5034  */
5035 static int hpsa_scsi_ioaccel_queue_command(struct ctlr_info *h,
5036 	struct CommandList *c, u32 ioaccel_handle, u8 *cdb, int cdb_len,
5037 	u8 *scsi3addr, struct hpsa_scsi_dev_t *phys_disk)
5038 {
5039 	if (!c->scsi_cmd->device)
5040 		return -1;
5041 
5042 	if (!c->scsi_cmd->device->hostdata)
5043 		return -1;
5044 
5045 	if (phys_disk->in_reset)
5046 		return -1;
5047 
5048 	/* Try to honor the device's queue depth */
5049 	if (atomic_inc_return(&phys_disk->ioaccel_cmds_out) >
5050 					phys_disk->queue_depth) {
5051 		atomic_dec(&phys_disk->ioaccel_cmds_out);
5052 		return IO_ACCEL_INELIGIBLE;
5053 	}
5054 	if (h->transMethod & CFGTBL_Trans_io_accel1)
5055 		return hpsa_scsi_ioaccel1_queue_command(h, c, ioaccel_handle,
5056 						cdb, cdb_len, scsi3addr,
5057 						phys_disk);
5058 	else
5059 		return hpsa_scsi_ioaccel2_queue_command(h, c, ioaccel_handle,
5060 						cdb, cdb_len, scsi3addr,
5061 						phys_disk);
5062 }
5063 
5064 static void raid_map_helper(struct raid_map_data *map,
5065 		int offload_to_mirror, u32 *map_index, u32 *current_group)
5066 {
5067 	if (offload_to_mirror == 0)  {
5068 		/* use physical disk in the first mirrored group. */
5069 		*map_index %= le16_to_cpu(map->data_disks_per_row);
5070 		return;
5071 	}
5072 	do {
5073 		/* determine mirror group that *map_index indicates */
5074 		*current_group = *map_index /
5075 			le16_to_cpu(map->data_disks_per_row);
5076 		if (offload_to_mirror == *current_group)
5077 			continue;
5078 		if (*current_group < le16_to_cpu(map->layout_map_count) - 1) {
5079 			/* select map index from next group */
5080 			*map_index += le16_to_cpu(map->data_disks_per_row);
5081 			(*current_group)++;
5082 		} else {
5083 			/* select map index from first group */
5084 			*map_index %= le16_to_cpu(map->data_disks_per_row);
5085 			*current_group = 0;
5086 		}
5087 	} while (offload_to_mirror != *current_group);
5088 }
5089 
5090 /*
5091  * Attempt to perform offload RAID mapping for a logical volume I/O.
5092  */
5093 static int hpsa_scsi_ioaccel_raid_map(struct ctlr_info *h,
5094 	struct CommandList *c)
5095 {
5096 	struct scsi_cmnd *cmd = c->scsi_cmd;
5097 	struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
5098 	struct raid_map_data *map = &dev->raid_map;
5099 	struct raid_map_disk_data *dd = &map->data[0];
5100 	int is_write = 0;
5101 	u32 map_index;
5102 	u64 first_block, last_block;
5103 	u32 block_cnt;
5104 	u32 blocks_per_row;
5105 	u64 first_row, last_row;
5106 	u32 first_row_offset, last_row_offset;
5107 	u32 first_column, last_column;
5108 	u64 r0_first_row, r0_last_row;
5109 	u32 r5or6_blocks_per_row;
5110 	u64 r5or6_first_row, r5or6_last_row;
5111 	u32 r5or6_first_row_offset, r5or6_last_row_offset;
5112 	u32 r5or6_first_column, r5or6_last_column;
5113 	u32 total_disks_per_row;
5114 	u32 stripesize;
5115 	u32 first_group, last_group, current_group;
5116 	u32 map_row;
5117 	u32 disk_handle;
5118 	u64 disk_block;
5119 	u32 disk_block_cnt;
5120 	u8 cdb[16];
5121 	u8 cdb_len;
5122 	u16 strip_size;
5123 #if BITS_PER_LONG == 32
5124 	u64 tmpdiv;
5125 #endif
5126 	int offload_to_mirror;
5127 
5128 	if (!dev)
5129 		return -1;
5130 
5131 	if (dev->in_reset)
5132 		return -1;
5133 
5134 	/* check for valid opcode, get LBA and block count */
5135 	switch (cmd->cmnd[0]) {
5136 	case WRITE_6:
5137 		is_write = 1;
5138 		fallthrough;
5139 	case READ_6:
5140 		first_block = (((cmd->cmnd[1] & 0x1F) << 16) |
5141 				(cmd->cmnd[2] << 8) |
5142 				cmd->cmnd[3]);
5143 		block_cnt = cmd->cmnd[4];
5144 		if (block_cnt == 0)
5145 			block_cnt = 256;
5146 		break;
5147 	case WRITE_10:
5148 		is_write = 1;
5149 		fallthrough;
5150 	case READ_10:
5151 		first_block =
5152 			(((u64) cmd->cmnd[2]) << 24) |
5153 			(((u64) cmd->cmnd[3]) << 16) |
5154 			(((u64) cmd->cmnd[4]) << 8) |
5155 			cmd->cmnd[5];
5156 		block_cnt =
5157 			(((u32) cmd->cmnd[7]) << 8) |
5158 			cmd->cmnd[8];
5159 		break;
5160 	case WRITE_12:
5161 		is_write = 1;
5162 		fallthrough;
5163 	case READ_12:
5164 		first_block =
5165 			(((u64) cmd->cmnd[2]) << 24) |
5166 			(((u64) cmd->cmnd[3]) << 16) |
5167 			(((u64) cmd->cmnd[4]) << 8) |
5168 			cmd->cmnd[5];
5169 		block_cnt =
5170 			(((u32) cmd->cmnd[6]) << 24) |
5171 			(((u32) cmd->cmnd[7]) << 16) |
5172 			(((u32) cmd->cmnd[8]) << 8) |
5173 		cmd->cmnd[9];
5174 		break;
5175 	case WRITE_16:
5176 		is_write = 1;
5177 		fallthrough;
5178 	case READ_16:
5179 		first_block =
5180 			(((u64) cmd->cmnd[2]) << 56) |
5181 			(((u64) cmd->cmnd[3]) << 48) |
5182 			(((u64) cmd->cmnd[4]) << 40) |
5183 			(((u64) cmd->cmnd[5]) << 32) |
5184 			(((u64) cmd->cmnd[6]) << 24) |
5185 			(((u64) cmd->cmnd[7]) << 16) |
5186 			(((u64) cmd->cmnd[8]) << 8) |
5187 			cmd->cmnd[9];
5188 		block_cnt =
5189 			(((u32) cmd->cmnd[10]) << 24) |
5190 			(((u32) cmd->cmnd[11]) << 16) |
5191 			(((u32) cmd->cmnd[12]) << 8) |
5192 			cmd->cmnd[13];
5193 		break;
5194 	default:
5195 		return IO_ACCEL_INELIGIBLE; /* process via normal I/O path */
5196 	}
5197 	last_block = first_block + block_cnt - 1;
5198 
5199 	/* check for write to non-RAID-0 */
5200 	if (is_write && dev->raid_level != 0)
5201 		return IO_ACCEL_INELIGIBLE;
5202 
5203 	/* check for invalid block or wraparound */
5204 	if (last_block >= le64_to_cpu(map->volume_blk_cnt) ||
5205 		last_block < first_block)
5206 		return IO_ACCEL_INELIGIBLE;
5207 
5208 	/* calculate stripe information for the request */
5209 	blocks_per_row = le16_to_cpu(map->data_disks_per_row) *
5210 				le16_to_cpu(map->strip_size);
5211 	strip_size = le16_to_cpu(map->strip_size);
5212 #if BITS_PER_LONG == 32
5213 	tmpdiv = first_block;
5214 	(void) do_div(tmpdiv, blocks_per_row);
5215 	first_row = tmpdiv;
5216 	tmpdiv = last_block;
5217 	(void) do_div(tmpdiv, blocks_per_row);
5218 	last_row = tmpdiv;
5219 	first_row_offset = (u32) (first_block - (first_row * blocks_per_row));
5220 	last_row_offset = (u32) (last_block - (last_row * blocks_per_row));
5221 	tmpdiv = first_row_offset;
5222 	(void) do_div(tmpdiv, strip_size);
5223 	first_column = tmpdiv;
5224 	tmpdiv = last_row_offset;
5225 	(void) do_div(tmpdiv, strip_size);
5226 	last_column = tmpdiv;
5227 #else
5228 	first_row = first_block / blocks_per_row;
5229 	last_row = last_block / blocks_per_row;
5230 	first_row_offset = (u32) (first_block - (first_row * blocks_per_row));
5231 	last_row_offset = (u32) (last_block - (last_row * blocks_per_row));
5232 	first_column = first_row_offset / strip_size;
5233 	last_column = last_row_offset / strip_size;
5234 #endif
5235 
5236 	/* if this isn't a single row/column then give to the controller */
5237 	if ((first_row != last_row) || (first_column != last_column))
5238 		return IO_ACCEL_INELIGIBLE;
5239 
5240 	/* proceeding with driver mapping */
5241 	total_disks_per_row = le16_to_cpu(map->data_disks_per_row) +
5242 				le16_to_cpu(map->metadata_disks_per_row);
5243 	map_row = ((u32)(first_row >> map->parity_rotation_shift)) %
5244 				le16_to_cpu(map->row_cnt);
5245 	map_index = (map_row * total_disks_per_row) + first_column;
5246 
5247 	switch (dev->raid_level) {
5248 	case HPSA_RAID_0:
5249 		break; /* nothing special to do */
5250 	case HPSA_RAID_1:
5251 		/* Handles load balance across RAID 1 members.
5252 		 * (2-drive R1 and R10 with even # of drives.)
5253 		 * Appropriate for SSDs, not optimal for HDDs
5254 		 * Ensure we have the correct raid_map.
5255 		 */
5256 		if (le16_to_cpu(map->layout_map_count) != 2) {
5257 			hpsa_turn_off_ioaccel_for_device(dev);
5258 			return IO_ACCEL_INELIGIBLE;
5259 		}
5260 		if (dev->offload_to_mirror)
5261 			map_index += le16_to_cpu(map->data_disks_per_row);
5262 		dev->offload_to_mirror = !dev->offload_to_mirror;
5263 		break;
5264 	case HPSA_RAID_ADM:
5265 		/* Handles N-way mirrors  (R1-ADM)
5266 		 * and R10 with # of drives divisible by 3.)
5267 		 * Ensure we have the correct raid_map.
5268 		 */
5269 		if (le16_to_cpu(map->layout_map_count) != 3) {
5270 			hpsa_turn_off_ioaccel_for_device(dev);
5271 			return IO_ACCEL_INELIGIBLE;
5272 		}
5273 
5274 		offload_to_mirror = dev->offload_to_mirror;
5275 		raid_map_helper(map, offload_to_mirror,
5276 				&map_index, &current_group);
5277 		/* set mirror group to use next time */
5278 		offload_to_mirror =
5279 			(offload_to_mirror >=
5280 			le16_to_cpu(map->layout_map_count) - 1)
5281 			? 0 : offload_to_mirror + 1;
5282 		dev->offload_to_mirror = offload_to_mirror;
5283 		/* Avoid direct use of dev->offload_to_mirror within this
5284 		 * function since multiple threads might simultaneously
5285 		 * increment it beyond the range of dev->layout_map_count -1.
5286 		 */
5287 		break;
5288 	case HPSA_RAID_5:
5289 	case HPSA_RAID_6:
5290 		if (le16_to_cpu(map->layout_map_count) <= 1)
5291 			break;
5292 
5293 		/* Verify first and last block are in same RAID group */
5294 		r5or6_blocks_per_row =
5295 			le16_to_cpu(map->strip_size) *
5296 			le16_to_cpu(map->data_disks_per_row);
5297 		if (r5or6_blocks_per_row == 0) {
5298 			hpsa_turn_off_ioaccel_for_device(dev);
5299 			return IO_ACCEL_INELIGIBLE;
5300 		}
5301 		stripesize = r5or6_blocks_per_row *
5302 			le16_to_cpu(map->layout_map_count);
5303 #if BITS_PER_LONG == 32
5304 		tmpdiv = first_block;
5305 		first_group = do_div(tmpdiv, stripesize);
5306 		tmpdiv = first_group;
5307 		(void) do_div(tmpdiv, r5or6_blocks_per_row);
5308 		first_group = tmpdiv;
5309 		tmpdiv = last_block;
5310 		last_group = do_div(tmpdiv, stripesize);
5311 		tmpdiv = last_group;
5312 		(void) do_div(tmpdiv, r5or6_blocks_per_row);
5313 		last_group = tmpdiv;
5314 #else
5315 		first_group = (first_block % stripesize) / r5or6_blocks_per_row;
5316 		last_group = (last_block % stripesize) / r5or6_blocks_per_row;
5317 #endif
5318 		if (first_group != last_group)
5319 			return IO_ACCEL_INELIGIBLE;
5320 
5321 		/* Verify request is in a single row of RAID 5/6 */
5322 #if BITS_PER_LONG == 32
5323 		tmpdiv = first_block;
5324 		(void) do_div(tmpdiv, stripesize);
5325 		first_row = r5or6_first_row = r0_first_row = tmpdiv;
5326 		tmpdiv = last_block;
5327 		(void) do_div(tmpdiv, stripesize);
5328 		r5or6_last_row = r0_last_row = tmpdiv;
5329 #else
5330 		first_row = r5or6_first_row = r0_first_row =
5331 						first_block / stripesize;
5332 		r5or6_last_row = r0_last_row = last_block / stripesize;
5333 #endif
5334 		if (r5or6_first_row != r5or6_last_row)
5335 			return IO_ACCEL_INELIGIBLE;
5336 
5337 
5338 		/* Verify request is in a single column */
5339 #if BITS_PER_LONG == 32
5340 		tmpdiv = first_block;
5341 		first_row_offset = do_div(tmpdiv, stripesize);
5342 		tmpdiv = first_row_offset;
5343 		first_row_offset = (u32) do_div(tmpdiv, r5or6_blocks_per_row);
5344 		r5or6_first_row_offset = first_row_offset;
5345 		tmpdiv = last_block;
5346 		r5or6_last_row_offset = do_div(tmpdiv, stripesize);
5347 		tmpdiv = r5or6_last_row_offset;
5348 		r5or6_last_row_offset = do_div(tmpdiv, r5or6_blocks_per_row);
5349 		tmpdiv = r5or6_first_row_offset;
5350 		(void) do_div(tmpdiv, map->strip_size);
5351 		first_column = r5or6_first_column = tmpdiv;
5352 		tmpdiv = r5or6_last_row_offset;
5353 		(void) do_div(tmpdiv, map->strip_size);
5354 		r5or6_last_column = tmpdiv;
5355 #else
5356 		first_row_offset = r5or6_first_row_offset =
5357 			(u32)((first_block % stripesize) %
5358 						r5or6_blocks_per_row);
5359 
5360 		r5or6_last_row_offset =
5361 			(u32)((last_block % stripesize) %
5362 						r5or6_blocks_per_row);
5363 
5364 		first_column = r5or6_first_column =
5365 			r5or6_first_row_offset / le16_to_cpu(map->strip_size);
5366 		r5or6_last_column =
5367 			r5or6_last_row_offset / le16_to_cpu(map->strip_size);
5368 #endif
5369 		if (r5or6_first_column != r5or6_last_column)
5370 			return IO_ACCEL_INELIGIBLE;
5371 
5372 		/* Request is eligible */
5373 		map_row = ((u32)(first_row >> map->parity_rotation_shift)) %
5374 			le16_to_cpu(map->row_cnt);
5375 
5376 		map_index = (first_group *
5377 			(le16_to_cpu(map->row_cnt) * total_disks_per_row)) +
5378 			(map_row * total_disks_per_row) + first_column;
5379 		break;
5380 	default:
5381 		return IO_ACCEL_INELIGIBLE;
5382 	}
5383 
5384 	if (unlikely(map_index >= RAID_MAP_MAX_ENTRIES))
5385 		return IO_ACCEL_INELIGIBLE;
5386 
5387 	c->phys_disk = dev->phys_disk[map_index];
5388 	if (!c->phys_disk)
5389 		return IO_ACCEL_INELIGIBLE;
5390 
5391 	disk_handle = dd[map_index].ioaccel_handle;
5392 	disk_block = le64_to_cpu(map->disk_starting_blk) +
5393 			first_row * le16_to_cpu(map->strip_size) +
5394 			(first_row_offset - first_column *
5395 			le16_to_cpu(map->strip_size));
5396 	disk_block_cnt = block_cnt;
5397 
5398 	/* handle differing logical/physical block sizes */
5399 	if (map->phys_blk_shift) {
5400 		disk_block <<= map->phys_blk_shift;
5401 		disk_block_cnt <<= map->phys_blk_shift;
5402 	}
5403 	BUG_ON(disk_block_cnt > 0xffff);
5404 
5405 	/* build the new CDB for the physical disk I/O */
5406 	if (disk_block > 0xffffffff) {
5407 		cdb[0] = is_write ? WRITE_16 : READ_16;
5408 		cdb[1] = 0;
5409 		cdb[2] = (u8) (disk_block >> 56);
5410 		cdb[3] = (u8) (disk_block >> 48);
5411 		cdb[4] = (u8) (disk_block >> 40);
5412 		cdb[5] = (u8) (disk_block >> 32);
5413 		cdb[6] = (u8) (disk_block >> 24);
5414 		cdb[7] = (u8) (disk_block >> 16);
5415 		cdb[8] = (u8) (disk_block >> 8);
5416 		cdb[9] = (u8) (disk_block);
5417 		cdb[10] = (u8) (disk_block_cnt >> 24);
5418 		cdb[11] = (u8) (disk_block_cnt >> 16);
5419 		cdb[12] = (u8) (disk_block_cnt >> 8);
5420 		cdb[13] = (u8) (disk_block_cnt);
5421 		cdb[14] = 0;
5422 		cdb[15] = 0;
5423 		cdb_len = 16;
5424 	} else {
5425 		cdb[0] = is_write ? WRITE_10 : READ_10;
5426 		cdb[1] = 0;
5427 		cdb[2] = (u8) (disk_block >> 24);
5428 		cdb[3] = (u8) (disk_block >> 16);
5429 		cdb[4] = (u8) (disk_block >> 8);
5430 		cdb[5] = (u8) (disk_block);
5431 		cdb[6] = 0;
5432 		cdb[7] = (u8) (disk_block_cnt >> 8);
5433 		cdb[8] = (u8) (disk_block_cnt);
5434 		cdb[9] = 0;
5435 		cdb_len = 10;
5436 	}
5437 	return hpsa_scsi_ioaccel_queue_command(h, c, disk_handle, cdb, cdb_len,
5438 						dev->scsi3addr,
5439 						dev->phys_disk[map_index]);
5440 }
5441 
5442 /*
5443  * Submit commands down the "normal" RAID stack path
5444  * All callers to hpsa_ciss_submit must check lockup_detected
5445  * beforehand, before (opt.) and after calling cmd_alloc
5446  */
5447 static int hpsa_ciss_submit(struct ctlr_info *h,
5448 	struct CommandList *c, struct scsi_cmnd *cmd,
5449 	struct hpsa_scsi_dev_t *dev)
5450 {
5451 	cmd->host_scribble = (unsigned char *) c;
5452 	c->cmd_type = CMD_SCSI;
5453 	c->scsi_cmd = cmd;
5454 	c->Header.ReplyQueue = 0;  /* unused in simple mode */
5455 	memcpy(&c->Header.LUN.LunAddrBytes[0], &dev->scsi3addr[0], 8);
5456 	c->Header.tag = cpu_to_le64((c->cmdindex << DIRECT_LOOKUP_SHIFT));
5457 
5458 	/* Fill in the request block... */
5459 
5460 	c->Request.Timeout = 0;
5461 	BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
5462 	c->Request.CDBLen = cmd->cmd_len;
5463 	memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
5464 	switch (cmd->sc_data_direction) {
5465 	case DMA_TO_DEVICE:
5466 		c->Request.type_attr_dir =
5467 			TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_WRITE);
5468 		break;
5469 	case DMA_FROM_DEVICE:
5470 		c->Request.type_attr_dir =
5471 			TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_READ);
5472 		break;
5473 	case DMA_NONE:
5474 		c->Request.type_attr_dir =
5475 			TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_NONE);
5476 		break;
5477 	case DMA_BIDIRECTIONAL:
5478 		/* This can happen if a buggy application does a scsi passthru
5479 		 * and sets both inlen and outlen to non-zero. ( see
5480 		 * ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
5481 		 */
5482 
5483 		c->Request.type_attr_dir =
5484 			TYPE_ATTR_DIR(TYPE_CMD, ATTR_SIMPLE, XFER_RSVD);
5485 		/* This is technically wrong, and hpsa controllers should
5486 		 * reject it with CMD_INVALID, which is the most correct
5487 		 * response, but non-fibre backends appear to let it
5488 		 * slide by, and give the same results as if this field
5489 		 * were set correctly.  Either way is acceptable for
5490 		 * our purposes here.
5491 		 */
5492 
5493 		break;
5494 
5495 	default:
5496 		dev_err(&h->pdev->dev, "unknown data direction: %d\n",
5497 			cmd->sc_data_direction);
5498 		BUG();
5499 		break;
5500 	}
5501 
5502 	if (hpsa_scatter_gather(h, c, cmd) < 0) { /* Fill SG list */
5503 		hpsa_cmd_resolve_and_free(h, c);
5504 		return SCSI_MLQUEUE_HOST_BUSY;
5505 	}
5506 
5507 	if (dev->in_reset) {
5508 		hpsa_cmd_resolve_and_free(h, c);
5509 		return SCSI_MLQUEUE_HOST_BUSY;
5510 	}
5511 
5512 	c->device = dev;
5513 
5514 	enqueue_cmd_and_start_io(h, c);
5515 	/* the cmd'll come back via intr handler in complete_scsi_command()  */
5516 	return 0;
5517 }
5518 
5519 static void hpsa_cmd_init(struct ctlr_info *h, int index,
5520 				struct CommandList *c)
5521 {
5522 	dma_addr_t cmd_dma_handle, err_dma_handle;
5523 
5524 	/* Zero out all of commandlist except the last field, refcount */
5525 	memset(c, 0, offsetof(struct CommandList, refcount));
5526 	c->Header.tag = cpu_to_le64((u64) (index << DIRECT_LOOKUP_SHIFT));
5527 	cmd_dma_handle = h->cmd_pool_dhandle + index * sizeof(*c);
5528 	c->err_info = h->errinfo_pool + index;
5529 	memset(c->err_info, 0, sizeof(*c->err_info));
5530 	err_dma_handle = h->errinfo_pool_dhandle
5531 	    + index * sizeof(*c->err_info);
5532 	c->cmdindex = index;
5533 	c->busaddr = (u32) cmd_dma_handle;
5534 	c->ErrDesc.Addr = cpu_to_le64((u64) err_dma_handle);
5535 	c->ErrDesc.Len = cpu_to_le32((u32) sizeof(*c->err_info));
5536 	c->h = h;
5537 	c->scsi_cmd = SCSI_CMD_IDLE;
5538 }
5539 
5540 static void hpsa_preinitialize_commands(struct ctlr_info *h)
5541 {
5542 	int i;
5543 
5544 	for (i = 0; i < h->nr_cmds; i++) {
5545 		struct CommandList *c = h->cmd_pool + i;
5546 
5547 		hpsa_cmd_init(h, i, c);
5548 		atomic_set(&c->refcount, 0);
5549 	}
5550 }
5551 
5552 static inline void hpsa_cmd_partial_init(struct ctlr_info *h, int index,
5553 				struct CommandList *c)
5554 {
5555 	dma_addr_t cmd_dma_handle = h->cmd_pool_dhandle + index * sizeof(*c);
5556 
5557 	BUG_ON(c->cmdindex != index);
5558 
5559 	memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
5560 	memset(c->err_info, 0, sizeof(*c->err_info));
5561 	c->busaddr = (u32) cmd_dma_handle;
5562 }
5563 
5564 static int hpsa_ioaccel_submit(struct ctlr_info *h,
5565 		struct CommandList *c, struct scsi_cmnd *cmd,
5566 		bool retry)
5567 {
5568 	struct hpsa_scsi_dev_t *dev = cmd->device->hostdata;
5569 	int rc = IO_ACCEL_INELIGIBLE;
5570 
5571 	if (!dev)
5572 		return SCSI_MLQUEUE_HOST_BUSY;
5573 
5574 	if (dev->in_reset)
5575 		return SCSI_MLQUEUE_HOST_BUSY;
5576 
5577 	if (hpsa_simple_mode)
5578 		return IO_ACCEL_INELIGIBLE;
5579 
5580 	cmd->host_scribble = (unsigned char *) c;
5581 
5582 	if (dev->offload_enabled) {
5583 		hpsa_cmd_init(h, c->cmdindex, c); /* Zeroes out all fields */
5584 		c->cmd_type = CMD_SCSI;
5585 		c->scsi_cmd = cmd;
5586 		c->device = dev;
5587 		if (retry) /* Resubmit but do not increment device->commands_outstanding. */
5588 			c->retry_pending = true;
5589 		rc = hpsa_scsi_ioaccel_raid_map(h, c);
5590 		if (rc < 0)     /* scsi_dma_map failed. */
5591 			rc = SCSI_MLQUEUE_HOST_BUSY;
5592 	} else if (dev->hba_ioaccel_enabled) {
5593 		hpsa_cmd_init(h, c->cmdindex, c); /* Zeroes out all fields */
5594 		c->cmd_type = CMD_SCSI;
5595 		c->scsi_cmd = cmd;
5596 		c->device = dev;
5597 		if (retry) /* Resubmit but do not increment device->commands_outstanding. */
5598 			c->retry_pending = true;
5599 		rc = hpsa_scsi_ioaccel_direct_map(h, c);
5600 		if (rc < 0)     /* scsi_dma_map failed. */
5601 			rc = SCSI_MLQUEUE_HOST_BUSY;
5602 	}
5603 	return rc;
5604 }
5605 
5606 static void hpsa_command_resubmit_worker(struct work_struct *work)
5607 {
5608 	struct scsi_cmnd *cmd;
5609 	struct hpsa_scsi_dev_t *dev;
5610 	struct CommandList *c = container_of(work, struct CommandList, work);
5611 
5612 	cmd = c->scsi_cmd;
5613 	dev = cmd->device->hostdata;
5614 	if (!dev) {
5615 		cmd->result = DID_NO_CONNECT << 16;
5616 		return hpsa_cmd_free_and_done(c->h, c, cmd);
5617 	}
5618 
5619 	if (dev->in_reset) {
5620 		cmd->result = DID_RESET << 16;
5621 		return hpsa_cmd_free_and_done(c->h, c, cmd);
5622 	}
5623 
5624 	if (c->cmd_type == CMD_IOACCEL2) {
5625 		struct ctlr_info *h = c->h;
5626 		struct io_accel2_cmd *c2 = &h->ioaccel2_cmd_pool[c->cmdindex];
5627 		int rc;
5628 
5629 		if (c2->error_data.serv_response ==
5630 				IOACCEL2_STATUS_SR_TASK_COMP_SET_FULL) {
5631 			/* Resubmit with the retry_pending flag set. */
5632 			rc = hpsa_ioaccel_submit(h, c, cmd, true);
5633 			if (rc == 0)
5634 				return;
5635 			if (rc == SCSI_MLQUEUE_HOST_BUSY) {
5636 				/*
5637 				 * If we get here, it means dma mapping failed.
5638 				 * Try again via scsi mid layer, which will
5639 				 * then get SCSI_MLQUEUE_HOST_BUSY.
5640 				 */
5641 				cmd->result = DID_IMM_RETRY << 16;
5642 				return hpsa_cmd_free_and_done(h, c, cmd);
5643 			}
5644 			/* else, fall thru and resubmit down CISS path */
5645 		}
5646 	}
5647 	hpsa_cmd_partial_init(c->h, c->cmdindex, c);
5648 	/*
5649 	 * Here we have not come in though queue_command, so we
5650 	 * can set the retry_pending flag to true for a driver initiated
5651 	 * retry attempt (I.E. not a SML retry).
5652 	 * I.E. We are submitting a driver initiated retry.
5653 	 * Note: hpsa_ciss_submit does not zero out the command fields like
5654 	 *       ioaccel submit does.
5655 	 */
5656 	c->retry_pending = true;
5657 	if (hpsa_ciss_submit(c->h, c, cmd, dev)) {
5658 		/*
5659 		 * If we get here, it means dma mapping failed. Try
5660 		 * again via scsi mid layer, which will then get
5661 		 * SCSI_MLQUEUE_HOST_BUSY.
5662 		 *
5663 		 * hpsa_ciss_submit will have already freed c
5664 		 * if it encountered a dma mapping failure.
5665 		 */
5666 		cmd->result = DID_IMM_RETRY << 16;
5667 		scsi_done(cmd);
5668 	}
5669 }
5670 
5671 /* Running in struct Scsi_Host->host_lock less mode */
5672 static enum scsi_qc_status hpsa_scsi_queue_command(struct Scsi_Host *sh,
5673 						   struct scsi_cmnd *cmd)
5674 {
5675 	struct ctlr_info *h;
5676 	struct hpsa_scsi_dev_t *dev;
5677 	struct CommandList *c;
5678 	int rc = 0;
5679 
5680 	/* Get the ptr to our adapter structure out of cmd->host. */
5681 	h = sdev_to_hba(cmd->device);
5682 
5683 	BUG_ON(scsi_cmd_to_rq(cmd)->tag < 0);
5684 
5685 	dev = cmd->device->hostdata;
5686 	if (!dev) {
5687 		cmd->result = DID_NO_CONNECT << 16;
5688 		scsi_done(cmd);
5689 		return 0;
5690 	}
5691 
5692 	if (dev->removed) {
5693 		cmd->result = DID_NO_CONNECT << 16;
5694 		scsi_done(cmd);
5695 		return 0;
5696 	}
5697 
5698 	if (unlikely(lockup_detected(h))) {
5699 		cmd->result = DID_NO_CONNECT << 16;
5700 		scsi_done(cmd);
5701 		return 0;
5702 	}
5703 
5704 	if (dev->in_reset)
5705 		return SCSI_MLQUEUE_DEVICE_BUSY;
5706 
5707 	c = cmd_tagged_alloc(h, cmd);
5708 	if (c == NULL)
5709 		return SCSI_MLQUEUE_DEVICE_BUSY;
5710 
5711 	/*
5712 	 * This is necessary because the SML doesn't zero out this field during
5713 	 * error recovery.
5714 	 */
5715 	cmd->result = 0;
5716 
5717 	/*
5718 	 * Call alternate submit routine for I/O accelerated commands.
5719 	 * Retries always go down the normal I/O path.
5720 	 * Note: If cmd->retries is non-zero, then this is a SML
5721 	 *       initiated retry and not a driver initiated retry.
5722 	 *       This command has been obtained from cmd_tagged_alloc
5723 	 *       and is therefore a brand-new command.
5724 	 */
5725 	if (likely(cmd->retries == 0 &&
5726 			!blk_rq_is_passthrough(scsi_cmd_to_rq(cmd)) &&
5727 			h->acciopath_status)) {
5728 		/* Submit with the retry_pending flag unset. */
5729 		rc = hpsa_ioaccel_submit(h, c, cmd, false);
5730 		if (rc == 0)
5731 			return 0;
5732 		if (rc == SCSI_MLQUEUE_HOST_BUSY) {
5733 			hpsa_cmd_resolve_and_free(h, c);
5734 			return SCSI_MLQUEUE_HOST_BUSY;
5735 		}
5736 	}
5737 	return hpsa_ciss_submit(h, c, cmd, dev);
5738 }
5739 
5740 static void hpsa_scan_complete(struct ctlr_info *h)
5741 {
5742 	unsigned long flags;
5743 
5744 	spin_lock_irqsave(&h->scan_lock, flags);
5745 	h->scan_finished = 1;
5746 	wake_up(&h->scan_wait_queue);
5747 	spin_unlock_irqrestore(&h->scan_lock, flags);
5748 }
5749 
5750 static void hpsa_scan_start(struct Scsi_Host *sh)
5751 {
5752 	struct ctlr_info *h = shost_to_hba(sh);
5753 	unsigned long flags;
5754 
5755 	/*
5756 	 * Don't let rescans be initiated on a controller known to be locked
5757 	 * up.  If the controller locks up *during* a rescan, that thread is
5758 	 * probably hosed, but at least we can prevent new rescan threads from
5759 	 * piling up on a locked up controller.
5760 	 */
5761 	if (unlikely(lockup_detected(h)))
5762 		return hpsa_scan_complete(h);
5763 
5764 	/*
5765 	 * If a scan is already waiting to run, no need to add another
5766 	 */
5767 	spin_lock_irqsave(&h->scan_lock, flags);
5768 	if (h->scan_waiting) {
5769 		spin_unlock_irqrestore(&h->scan_lock, flags);
5770 		return;
5771 	}
5772 
5773 	spin_unlock_irqrestore(&h->scan_lock, flags);
5774 
5775 	/* wait until any scan already in progress is finished. */
5776 	while (1) {
5777 		spin_lock_irqsave(&h->scan_lock, flags);
5778 		if (h->scan_finished)
5779 			break;
5780 		h->scan_waiting = 1;
5781 		spin_unlock_irqrestore(&h->scan_lock, flags);
5782 		wait_event(h->scan_wait_queue, h->scan_finished);
5783 		/* Note: We don't need to worry about a race between this
5784 		 * thread and driver unload because the midlayer will
5785 		 * have incremented the reference count, so unload won't
5786 		 * happen if we're in here.
5787 		 */
5788 	}
5789 	h->scan_finished = 0; /* mark scan as in progress */
5790 	h->scan_waiting = 0;
5791 	spin_unlock_irqrestore(&h->scan_lock, flags);
5792 
5793 	if (unlikely(lockup_detected(h)))
5794 		return hpsa_scan_complete(h);
5795 
5796 	/*
5797 	 * Do the scan after a reset completion
5798 	 */
5799 	spin_lock_irqsave(&h->reset_lock, flags);
5800 	if (h->reset_in_progress) {
5801 		h->drv_req_rescan = 1;
5802 		spin_unlock_irqrestore(&h->reset_lock, flags);
5803 		hpsa_scan_complete(h);
5804 		return;
5805 	}
5806 	spin_unlock_irqrestore(&h->reset_lock, flags);
5807 
5808 	hpsa_update_scsi_devices(h);
5809 
5810 	hpsa_scan_complete(h);
5811 }
5812 
5813 static int hpsa_change_queue_depth(struct scsi_device *sdev, int qdepth)
5814 {
5815 	struct hpsa_scsi_dev_t *logical_drive = sdev->hostdata;
5816 
5817 	if (!logical_drive)
5818 		return -ENODEV;
5819 
5820 	if (qdepth < 1)
5821 		qdepth = 1;
5822 	else if (qdepth > logical_drive->queue_depth)
5823 		qdepth = logical_drive->queue_depth;
5824 
5825 	return scsi_change_queue_depth(sdev, qdepth);
5826 }
5827 
5828 static int hpsa_scan_finished(struct Scsi_Host *sh,
5829 	unsigned long elapsed_time)
5830 {
5831 	struct ctlr_info *h = shost_to_hba(sh);
5832 	unsigned long flags;
5833 	int finished;
5834 
5835 	spin_lock_irqsave(&h->scan_lock, flags);
5836 	finished = h->scan_finished;
5837 	spin_unlock_irqrestore(&h->scan_lock, flags);
5838 	return finished;
5839 }
5840 
5841 static int hpsa_scsi_host_alloc(struct ctlr_info *h)
5842 {
5843 	struct Scsi_Host *sh;
5844 
5845 	sh = scsi_host_alloc(&hpsa_driver_template, sizeof(struct ctlr_info *));
5846 	if (sh == NULL) {
5847 		dev_err(&h->pdev->dev, "scsi_host_alloc failed\n");
5848 		return -ENOMEM;
5849 	}
5850 
5851 	sh->io_port = 0;
5852 	sh->n_io_port = 0;
5853 	sh->this_id = -1;
5854 	sh->max_channel = 3;
5855 	sh->max_cmd_len = MAX_COMMAND_SIZE;
5856 	sh->max_lun = HPSA_MAX_LUN;
5857 	sh->max_id = HPSA_MAX_LUN;
5858 	sh->can_queue = h->nr_cmds - HPSA_NRESERVED_CMDS;
5859 	sh->cmd_per_lun = sh->can_queue;
5860 	sh->sg_tablesize = h->maxsgentries;
5861 	sh->transportt = hpsa_sas_transport_template;
5862 	sh->hostdata[0] = (unsigned long) h;
5863 	sh->irq = pci_irq_vector(h->pdev, 0);
5864 	sh->unique_id = sh->irq;
5865 
5866 	h->scsi_host = sh;
5867 	return 0;
5868 }
5869 
5870 static int hpsa_scsi_add_host(struct ctlr_info *h)
5871 {
5872 	int rv;
5873 
5874 	rv = scsi_add_host(h->scsi_host, &h->pdev->dev);
5875 	if (rv) {
5876 		dev_err(&h->pdev->dev, "scsi_add_host failed\n");
5877 		return rv;
5878 	}
5879 	scsi_scan_host(h->scsi_host);
5880 	return 0;
5881 }
5882 
5883 /*
5884  * The block layer has already gone to the trouble of picking out a unique,
5885  * small-integer tag for this request.  We use an offset from that value as
5886  * an index to select our command block.  (The offset allows us to reserve the
5887  * low-numbered entries for our own uses.)
5888  */
5889 static int hpsa_get_cmd_index(struct scsi_cmnd *scmd)
5890 {
5891 	int idx = scsi_cmd_to_rq(scmd)->tag;
5892 
5893 	if (idx < 0)
5894 		return idx;
5895 
5896 	/* Offset to leave space for internal cmds. */
5897 	return idx += HPSA_NRESERVED_CMDS;
5898 }
5899 
5900 /*
5901  * Send a TEST_UNIT_READY command to the specified LUN using the specified
5902  * reply queue; returns zero if the unit is ready, and non-zero otherwise.
5903  */
5904 static int hpsa_send_test_unit_ready(struct ctlr_info *h,
5905 				struct CommandList *c, unsigned char lunaddr[],
5906 				int reply_queue)
5907 {
5908 	int rc;
5909 
5910 	/* Send the Test Unit Ready, fill_cmd can't fail, no mapping */
5911 	(void) fill_cmd(c, TEST_UNIT_READY, h,
5912 			NULL, 0, 0, lunaddr, TYPE_CMD);
5913 	rc = hpsa_scsi_do_simple_cmd(h, c, reply_queue, NO_TIMEOUT);
5914 	if (rc)
5915 		return rc;
5916 	/* no unmap needed here because no data xfer. */
5917 
5918 	/* Check if the unit is already ready. */
5919 	if (c->err_info->CommandStatus == CMD_SUCCESS)
5920 		return 0;
5921 
5922 	/*
5923 	 * The first command sent after reset will receive "unit attention" to
5924 	 * indicate that the LUN has been reset...this is actually what we're
5925 	 * looking for (but, success is good too).
5926 	 */
5927 	if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
5928 		c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION &&
5929 			(c->err_info->SenseInfo[2] == NO_SENSE ||
5930 			 c->err_info->SenseInfo[2] == UNIT_ATTENTION))
5931 		return 0;
5932 
5933 	return 1;
5934 }
5935 
5936 /*
5937  * Wait for a TEST_UNIT_READY command to complete, retrying as necessary;
5938  * returns zero when the unit is ready, and non-zero when giving up.
5939  */
5940 static int hpsa_wait_for_test_unit_ready(struct ctlr_info *h,
5941 				struct CommandList *c,
5942 				unsigned char lunaddr[], int reply_queue)
5943 {
5944 	int rc;
5945 	int count = 0;
5946 	int waittime = 1; /* seconds */
5947 
5948 	/* Send test unit ready until device ready, or give up. */
5949 	for (count = 0; count < HPSA_TUR_RETRY_LIMIT; count++) {
5950 
5951 		/*
5952 		 * Wait for a bit.  do this first, because if we send
5953 		 * the TUR right away, the reset will just abort it.
5954 		 */
5955 		msleep(1000 * waittime);
5956 
5957 		rc = hpsa_send_test_unit_ready(h, c, lunaddr, reply_queue);
5958 		if (!rc)
5959 			break;
5960 
5961 		/* Increase wait time with each try, up to a point. */
5962 		if (waittime < HPSA_MAX_WAIT_INTERVAL_SECS)
5963 			waittime *= 2;
5964 
5965 		dev_warn(&h->pdev->dev,
5966 			 "waiting %d secs for device to become ready.\n",
5967 			 waittime);
5968 	}
5969 
5970 	return rc;
5971 }
5972 
5973 static int wait_for_device_to_become_ready(struct ctlr_info *h,
5974 					   unsigned char lunaddr[],
5975 					   int reply_queue)
5976 {
5977 	int first_queue;
5978 	int last_queue;
5979 	int rq;
5980 	int rc = 0;
5981 	struct CommandList *c;
5982 
5983 	c = cmd_alloc(h);
5984 
5985 	/*
5986 	 * If no specific reply queue was requested, then send the TUR
5987 	 * repeatedly, requesting a reply on each reply queue; otherwise execute
5988 	 * the loop exactly once using only the specified queue.
5989 	 */
5990 	if (reply_queue == DEFAULT_REPLY_QUEUE) {
5991 		first_queue = 0;
5992 		last_queue = h->nreply_queues - 1;
5993 	} else {
5994 		first_queue = reply_queue;
5995 		last_queue = reply_queue;
5996 	}
5997 
5998 	for (rq = first_queue; rq <= last_queue; rq++) {
5999 		rc = hpsa_wait_for_test_unit_ready(h, c, lunaddr, rq);
6000 		if (rc)
6001 			break;
6002 	}
6003 
6004 	if (rc)
6005 		dev_warn(&h->pdev->dev, "giving up on device.\n");
6006 	else
6007 		dev_warn(&h->pdev->dev, "device is ready.\n");
6008 
6009 	cmd_free(h, c);
6010 	return rc;
6011 }
6012 
6013 /* Need at least one of these error handlers to keep ../scsi/hosts.c from
6014  * complaining.  Doing a host- or bus-reset can't do anything good here.
6015  */
6016 static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
6017 {
6018 	int rc = SUCCESS;
6019 	int i;
6020 	struct ctlr_info *h;
6021 	struct hpsa_scsi_dev_t *dev = NULL;
6022 	u8 reset_type;
6023 	char msg[48];
6024 	unsigned long flags;
6025 
6026 	/* find the controller to which the command to be aborted was sent */
6027 	h = sdev_to_hba(scsicmd->device);
6028 	if (h == NULL) /* paranoia */
6029 		return FAILED;
6030 
6031 	spin_lock_irqsave(&h->reset_lock, flags);
6032 	h->reset_in_progress = 1;
6033 	spin_unlock_irqrestore(&h->reset_lock, flags);
6034 
6035 	if (lockup_detected(h)) {
6036 		rc = FAILED;
6037 		goto return_reset_status;
6038 	}
6039 
6040 	dev = scsicmd->device->hostdata;
6041 	if (!dev) {
6042 		dev_err(&h->pdev->dev, "%s: device lookup failed\n", __func__);
6043 		rc = FAILED;
6044 		goto return_reset_status;
6045 	}
6046 
6047 	if (dev->devtype == TYPE_ENCLOSURE) {
6048 		rc = SUCCESS;
6049 		goto return_reset_status;
6050 	}
6051 
6052 	/* if controller locked up, we can guarantee command won't complete */
6053 	if (lockup_detected(h)) {
6054 		snprintf(msg, sizeof(msg),
6055 			 "cmd %d RESET FAILED, lockup detected",
6056 			 hpsa_get_cmd_index(scsicmd));
6057 		hpsa_show_dev_msg(KERN_WARNING, h, dev, msg);
6058 		rc = FAILED;
6059 		goto return_reset_status;
6060 	}
6061 
6062 	/* this reset request might be the result of a lockup; check */
6063 	if (detect_controller_lockup(h)) {
6064 		snprintf(msg, sizeof(msg),
6065 			 "cmd %d RESET FAILED, new lockup detected",
6066 			 hpsa_get_cmd_index(scsicmd));
6067 		hpsa_show_dev_msg(KERN_WARNING, h, dev, msg);
6068 		rc = FAILED;
6069 		goto return_reset_status;
6070 	}
6071 
6072 	/* Do not attempt on controller */
6073 	if (is_hba_lunid(dev->scsi3addr)) {
6074 		rc = SUCCESS;
6075 		goto return_reset_status;
6076 	}
6077 
6078 	if (is_logical_dev_addr_mode(dev->scsi3addr))
6079 		reset_type = HPSA_DEVICE_RESET_MSG;
6080 	else
6081 		reset_type = HPSA_PHYS_TARGET_RESET;
6082 
6083 	sprintf(msg, "resetting %s",
6084 		reset_type == HPSA_DEVICE_RESET_MSG ? "logical " : "physical ");
6085 	hpsa_show_dev_msg(KERN_WARNING, h, dev, msg);
6086 
6087 	/*
6088 	 * wait to see if any commands will complete before sending reset
6089 	 */
6090 	dev->in_reset = true; /* block any new cmds from OS for this device */
6091 	for (i = 0; i < 10; i++) {
6092 		if (atomic_read(&dev->commands_outstanding) > 0)
6093 			msleep(1000);
6094 		else
6095 			break;
6096 	}
6097 
6098 	/* send a reset to the SCSI LUN which the command was sent to */
6099 	rc = hpsa_do_reset(h, dev, reset_type, DEFAULT_REPLY_QUEUE);
6100 	if (rc == 0)
6101 		rc = SUCCESS;
6102 	else
6103 		rc = FAILED;
6104 
6105 	sprintf(msg, "reset %s %s",
6106 		reset_type == HPSA_DEVICE_RESET_MSG ? "logical " : "physical ",
6107 		rc == SUCCESS ? "completed successfully" : "failed");
6108 	hpsa_show_dev_msg(KERN_WARNING, h, dev, msg);
6109 
6110 return_reset_status:
6111 	spin_lock_irqsave(&h->reset_lock, flags);
6112 	h->reset_in_progress = 0;
6113 	if (dev)
6114 		dev->in_reset = false;
6115 	spin_unlock_irqrestore(&h->reset_lock, flags);
6116 	return rc;
6117 }
6118 
6119 /*
6120  * For operations with an associated SCSI command, a command block is allocated
6121  * at init, and managed by cmd_tagged_alloc() and cmd_tagged_free() using the
6122  * block request tag as an index into a table of entries.  cmd_tagged_free() is
6123  * the complement, although cmd_free() may be called instead.
6124  * This function is only called for new requests from queue_command.
6125  */
6126 static struct CommandList *cmd_tagged_alloc(struct ctlr_info *h,
6127 					    struct scsi_cmnd *scmd)
6128 {
6129 	int idx = hpsa_get_cmd_index(scmd);
6130 	struct CommandList *c = h->cmd_pool + idx;
6131 
6132 	if (idx < HPSA_NRESERVED_CMDS || idx >= h->nr_cmds) {
6133 		dev_err(&h->pdev->dev, "Bad block tag: %d not in [%d..%d]\n",
6134 			idx, HPSA_NRESERVED_CMDS, h->nr_cmds - 1);
6135 		/* The index value comes from the block layer, so if it's out of
6136 		 * bounds, it's probably not our bug.
6137 		 */
6138 		BUG();
6139 	}
6140 
6141 	if (unlikely(!hpsa_is_cmd_idle(c))) {
6142 		/*
6143 		 * We expect that the SCSI layer will hand us a unique tag
6144 		 * value.  Thus, there should never be a collision here between
6145 		 * two requests...because if the selected command isn't idle
6146 		 * then someone is going to be very disappointed.
6147 		 */
6148 		if (idx != h->last_collision_tag) { /* Print once per tag */
6149 			dev_warn(&h->pdev->dev,
6150 				"%s: tag collision (tag=%d)\n", __func__, idx);
6151 			if (scmd)
6152 				scsi_print_command(scmd);
6153 			h->last_collision_tag = idx;
6154 		}
6155 		return NULL;
6156 	}
6157 
6158 	atomic_inc(&c->refcount);
6159 	hpsa_cmd_partial_init(h, idx, c);
6160 
6161 	/*
6162 	 * This is a new command obtained from queue_command so
6163 	 * there have not been any driver initiated retry attempts.
6164 	 */
6165 	c->retry_pending = false;
6166 
6167 	return c;
6168 }
6169 
6170 static void cmd_tagged_free(struct ctlr_info *h, struct CommandList *c)
6171 {
6172 	/*
6173 	 * Release our reference to the block.  We don't need to do anything
6174 	 * else to free it, because it is accessed by index.
6175 	 */
6176 	(void)atomic_dec(&c->refcount);
6177 }
6178 
6179 /*
6180  * For operations that cannot sleep, a command block is allocated at init,
6181  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
6182  * which ones are free or in use.  Lock must be held when calling this.
6183  * cmd_free() is the complement.
6184  * This function never gives up and returns NULL.  If it hangs,
6185  * another thread must call cmd_free() to free some tags.
6186  */
6187 
6188 static struct CommandList *cmd_alloc(struct ctlr_info *h)
6189 {
6190 	struct CommandList *c;
6191 	int refcount, i;
6192 	int offset = 0;
6193 
6194 	/*
6195 	 * There is some *extremely* small but non-zero chance that that
6196 	 * multiple threads could get in here, and one thread could
6197 	 * be scanning through the list of bits looking for a free
6198 	 * one, but the free ones are always behind him, and other
6199 	 * threads sneak in behind him and eat them before he can
6200 	 * get to them, so that while there is always a free one, a
6201 	 * very unlucky thread might be starved anyway, never able to
6202 	 * beat the other threads.  In reality, this happens so
6203 	 * infrequently as to be indistinguishable from never.
6204 	 *
6205 	 * Note that we start allocating commands before the SCSI host structure
6206 	 * is initialized.  Since the search starts at bit zero, this
6207 	 * all works, since we have at least one command structure available;
6208 	 * however, it means that the structures with the low indexes have to be
6209 	 * reserved for driver-initiated requests, while requests from the block
6210 	 * layer will use the higher indexes.
6211 	 */
6212 
6213 	for (;;) {
6214 		i = find_next_zero_bit(h->cmd_pool_bits,
6215 					HPSA_NRESERVED_CMDS,
6216 					offset);
6217 		if (unlikely(i >= HPSA_NRESERVED_CMDS)) {
6218 			offset = 0;
6219 			continue;
6220 		}
6221 		c = h->cmd_pool + i;
6222 		refcount = atomic_inc_return(&c->refcount);
6223 		if (unlikely(refcount > 1)) {
6224 			cmd_free(h, c); /* already in use */
6225 			offset = (i + 1) % HPSA_NRESERVED_CMDS;
6226 			continue;
6227 		}
6228 		set_bit(i, h->cmd_pool_bits);
6229 		break; /* it's ours now. */
6230 	}
6231 	hpsa_cmd_partial_init(h, i, c);
6232 	c->device = NULL;
6233 
6234 	/*
6235 	 * cmd_alloc is for "internal" commands and they are never
6236 	 * retried.
6237 	 */
6238 	c->retry_pending = false;
6239 
6240 	return c;
6241 }
6242 
6243 /*
6244  * This is the complementary operation to cmd_alloc().  Note, however, in some
6245  * corner cases it may also be used to free blocks allocated by
6246  * cmd_tagged_alloc() in which case the ref-count decrement does the trick and
6247  * the clear-bit is harmless.
6248  */
6249 static void cmd_free(struct ctlr_info *h, struct CommandList *c)
6250 {
6251 	if (atomic_dec_and_test(&c->refcount)) {
6252 		int i;
6253 
6254 		i = c - h->cmd_pool;
6255 		clear_bit(i, h->cmd_pool_bits);
6256 	}
6257 }
6258 
6259 #ifdef CONFIG_COMPAT
6260 
6261 static int hpsa_ioctl32_passthru(struct scsi_device *dev, unsigned int cmd,
6262 	void __user *arg)
6263 {
6264 	struct ctlr_info *h = sdev_to_hba(dev);
6265 	IOCTL32_Command_struct __user *arg32 = arg;
6266 	IOCTL_Command_struct arg64;
6267 	int err;
6268 	u32 cp;
6269 
6270 	if (!arg)
6271 		return -EINVAL;
6272 
6273 	memset(&arg64, 0, sizeof(arg64));
6274 	if (copy_from_user(&arg64, arg32, offsetof(IOCTL_Command_struct, buf)))
6275 		return -EFAULT;
6276 	if (get_user(cp, &arg32->buf))
6277 		return -EFAULT;
6278 	arg64.buf = compat_ptr(cp);
6279 
6280 	if (atomic_dec_if_positive(&h->passthru_cmds_avail) < 0)
6281 		return -EAGAIN;
6282 	err = hpsa_passthru_ioctl(h, &arg64);
6283 	atomic_inc(&h->passthru_cmds_avail);
6284 	if (err)
6285 		return err;
6286 	if (copy_to_user(&arg32->error_info, &arg64.error_info,
6287 			 sizeof(arg32->error_info)))
6288 		return -EFAULT;
6289 	return 0;
6290 }
6291 
6292 static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
6293 	unsigned int cmd, void __user *arg)
6294 {
6295 	struct ctlr_info *h = sdev_to_hba(dev);
6296 	BIG_IOCTL32_Command_struct __user *arg32 = arg;
6297 	BIG_IOCTL_Command_struct arg64;
6298 	int err;
6299 	u32 cp;
6300 
6301 	if (!arg)
6302 		return -EINVAL;
6303 	memset(&arg64, 0, sizeof(arg64));
6304 	if (copy_from_user(&arg64, arg32,
6305 			   offsetof(BIG_IOCTL32_Command_struct, buf)))
6306 		return -EFAULT;
6307 	if (get_user(cp, &arg32->buf))
6308 		return -EFAULT;
6309 	arg64.buf = compat_ptr(cp);
6310 
6311 	if (atomic_dec_if_positive(&h->passthru_cmds_avail) < 0)
6312 		return -EAGAIN;
6313 	err = hpsa_big_passthru_ioctl(h, &arg64);
6314 	atomic_inc(&h->passthru_cmds_avail);
6315 	if (err)
6316 		return err;
6317 	if (copy_to_user(&arg32->error_info, &arg64.error_info,
6318 			 sizeof(arg32->error_info)))
6319 		return -EFAULT;
6320 	return 0;
6321 }
6322 
6323 static int hpsa_compat_ioctl(struct scsi_device *dev, unsigned int cmd,
6324 			     void __user *arg)
6325 {
6326 	switch (cmd) {
6327 	case CCISS_GETPCIINFO:
6328 	case CCISS_GETINTINFO:
6329 	case CCISS_SETINTINFO:
6330 	case CCISS_GETNODENAME:
6331 	case CCISS_SETNODENAME:
6332 	case CCISS_GETHEARTBEAT:
6333 	case CCISS_GETBUSTYPES:
6334 	case CCISS_GETFIRMVER:
6335 	case CCISS_GETDRIVVER:
6336 	case CCISS_REVALIDVOLS:
6337 	case CCISS_DEREGDISK:
6338 	case CCISS_REGNEWDISK:
6339 	case CCISS_REGNEWD:
6340 	case CCISS_RESCANDISK:
6341 	case CCISS_GETLUNINFO:
6342 		return hpsa_ioctl(dev, cmd, arg);
6343 
6344 	case CCISS_PASSTHRU32:
6345 		return hpsa_ioctl32_passthru(dev, cmd, arg);
6346 	case CCISS_BIG_PASSTHRU32:
6347 		return hpsa_ioctl32_big_passthru(dev, cmd, arg);
6348 
6349 	default:
6350 		return -ENOIOCTLCMD;
6351 	}
6352 }
6353 #endif
6354 
6355 static int hpsa_getpciinfo_ioctl(struct ctlr_info *h, void __user *argp)
6356 {
6357 	struct hpsa_pci_info pciinfo;
6358 
6359 	if (!argp)
6360 		return -EINVAL;
6361 	pciinfo.domain = pci_domain_nr(h->pdev->bus);
6362 	pciinfo.bus = h->pdev->bus->number;
6363 	pciinfo.dev_fn = h->pdev->devfn;
6364 	pciinfo.board_id = h->board_id;
6365 	if (copy_to_user(argp, &pciinfo, sizeof(pciinfo)))
6366 		return -EFAULT;
6367 	return 0;
6368 }
6369 
6370 static int hpsa_getdrivver_ioctl(struct ctlr_info *h, void __user *argp)
6371 {
6372 	DriverVer_type DriverVer;
6373 	unsigned char vmaj, vmin, vsubmin;
6374 	int rc;
6375 
6376 	rc = sscanf(HPSA_DRIVER_VERSION, "%hhu.%hhu.%hhu",
6377 		&vmaj, &vmin, &vsubmin);
6378 	if (rc != 3) {
6379 		dev_info(&h->pdev->dev, "driver version string '%s' "
6380 			"unrecognized.", HPSA_DRIVER_VERSION);
6381 		vmaj = 0;
6382 		vmin = 0;
6383 		vsubmin = 0;
6384 	}
6385 	DriverVer = (vmaj << 16) | (vmin << 8) | vsubmin;
6386 	if (!argp)
6387 		return -EINVAL;
6388 	if (copy_to_user(argp, &DriverVer, sizeof(DriverVer_type)))
6389 		return -EFAULT;
6390 	return 0;
6391 }
6392 
6393 static int hpsa_passthru_ioctl(struct ctlr_info *h,
6394 			       IOCTL_Command_struct *iocommand)
6395 {
6396 	struct CommandList *c;
6397 	char *buff = NULL;
6398 	u64 temp64;
6399 	int rc = 0;
6400 
6401 	if (!capable(CAP_SYS_RAWIO))
6402 		return -EPERM;
6403 	if ((iocommand->buf_size < 1) &&
6404 	    (iocommand->Request.Type.Direction != XFER_NONE)) {
6405 		return -EINVAL;
6406 	}
6407 	if (iocommand->buf_size > 0) {
6408 		if (iocommand->Request.Type.Direction & XFER_WRITE) {
6409 			buff = memdup_user(iocommand->buf, iocommand->buf_size);
6410 			if (IS_ERR(buff))
6411 				return PTR_ERR(buff);
6412 		} else {
6413 			buff = kzalloc(iocommand->buf_size, GFP_KERNEL);
6414 			if (!buff)
6415 				return -ENOMEM;
6416 		}
6417 	}
6418 	c = cmd_alloc(h);
6419 
6420 	/* Fill in the command type */
6421 	c->cmd_type = CMD_IOCTL_PEND;
6422 	c->scsi_cmd = SCSI_CMD_BUSY;
6423 	/* Fill in Command Header */
6424 	c->Header.ReplyQueue = 0; /* unused in simple mode */
6425 	if (iocommand->buf_size > 0) {	/* buffer to fill */
6426 		c->Header.SGList = 1;
6427 		c->Header.SGTotal = cpu_to_le16(1);
6428 	} else	{ /* no buffers to fill */
6429 		c->Header.SGList = 0;
6430 		c->Header.SGTotal = cpu_to_le16(0);
6431 	}
6432 	memcpy(&c->Header.LUN, &iocommand->LUN_info, sizeof(c->Header.LUN));
6433 
6434 	/* Fill in Request block */
6435 	memcpy(&c->Request, &iocommand->Request,
6436 		sizeof(c->Request));
6437 
6438 	/* Fill in the scatter gather information */
6439 	if (iocommand->buf_size > 0) {
6440 		temp64 = dma_map_single(&h->pdev->dev, buff,
6441 			iocommand->buf_size, DMA_BIDIRECTIONAL);
6442 		if (dma_mapping_error(&h->pdev->dev, (dma_addr_t) temp64)) {
6443 			c->SG[0].Addr = cpu_to_le64(0);
6444 			c->SG[0].Len = cpu_to_le32(0);
6445 			rc = -ENOMEM;
6446 			goto out;
6447 		}
6448 		c->SG[0].Addr = cpu_to_le64(temp64);
6449 		c->SG[0].Len = cpu_to_le32(iocommand->buf_size);
6450 		c->SG[0].Ext = cpu_to_le32(HPSA_SG_LAST); /* not chaining */
6451 	}
6452 	rc = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE,
6453 					NO_TIMEOUT);
6454 	if (iocommand->buf_size > 0)
6455 		hpsa_pci_unmap(h->pdev, c, 1, DMA_BIDIRECTIONAL);
6456 	check_ioctl_unit_attention(h, c);
6457 	if (rc) {
6458 		rc = -EIO;
6459 		goto out;
6460 	}
6461 
6462 	/* Copy the error information out */
6463 	memcpy(&iocommand->error_info, c->err_info,
6464 		sizeof(iocommand->error_info));
6465 	if ((iocommand->Request.Type.Direction & XFER_READ) &&
6466 		iocommand->buf_size > 0) {
6467 		/* Copy the data out of the buffer we created */
6468 		if (copy_to_user(iocommand->buf, buff, iocommand->buf_size)) {
6469 			rc = -EFAULT;
6470 			goto out;
6471 		}
6472 	}
6473 out:
6474 	cmd_free(h, c);
6475 	kfree(buff);
6476 	return rc;
6477 }
6478 
6479 static int hpsa_big_passthru_ioctl(struct ctlr_info *h,
6480 				   BIG_IOCTL_Command_struct *ioc)
6481 {
6482 	struct CommandList *c;
6483 	unsigned char **buff = NULL;
6484 	int *buff_size = NULL;
6485 	u64 temp64;
6486 	BYTE sg_used = 0;
6487 	int status = 0;
6488 	u32 left;
6489 	u32 sz;
6490 	BYTE __user *data_ptr;
6491 
6492 	if (!capable(CAP_SYS_RAWIO))
6493 		return -EPERM;
6494 
6495 	if ((ioc->buf_size < 1) &&
6496 	    (ioc->Request.Type.Direction != XFER_NONE))
6497 		return -EINVAL;
6498 	/* Check kmalloc limits  using all SGs */
6499 	if (ioc->malloc_size > MAX_KMALLOC_SIZE)
6500 		return -EINVAL;
6501 	if (ioc->buf_size > ioc->malloc_size * SG_ENTRIES_IN_CMD)
6502 		return -EINVAL;
6503 	buff = kcalloc(SG_ENTRIES_IN_CMD, sizeof(*buff), GFP_KERNEL);
6504 	if (!buff) {
6505 		status = -ENOMEM;
6506 		goto cleanup1;
6507 	}
6508 	buff_size = kmalloc_objs(int, SG_ENTRIES_IN_CMD);
6509 	if (!buff_size) {
6510 		status = -ENOMEM;
6511 		goto cleanup1;
6512 	}
6513 	left = ioc->buf_size;
6514 	data_ptr = ioc->buf;
6515 	while (left) {
6516 		sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
6517 		buff_size[sg_used] = sz;
6518 
6519 		if (ioc->Request.Type.Direction & XFER_WRITE) {
6520 			buff[sg_used] = memdup_user(data_ptr, sz);
6521 			if (IS_ERR(buff[sg_used])) {
6522 				status = PTR_ERR(buff[sg_used]);
6523 				goto cleanup1;
6524 			}
6525 		} else {
6526 			buff[sg_used] = kzalloc(sz, GFP_KERNEL);
6527 			if (!buff[sg_used]) {
6528 				status = -ENOMEM;
6529 				goto cleanup1;
6530 			}
6531 		}
6532 
6533 		left -= sz;
6534 		data_ptr += sz;
6535 		sg_used++;
6536 	}
6537 	c = cmd_alloc(h);
6538 
6539 	c->cmd_type = CMD_IOCTL_PEND;
6540 	c->scsi_cmd = SCSI_CMD_BUSY;
6541 	c->Header.ReplyQueue = 0;
6542 	c->Header.SGList = (u8) sg_used;
6543 	c->Header.SGTotal = cpu_to_le16(sg_used);
6544 	memcpy(&c->Header.LUN, &ioc->LUN_info, sizeof(c->Header.LUN));
6545 	memcpy(&c->Request, &ioc->Request, sizeof(c->Request));
6546 	if (ioc->buf_size > 0) {
6547 		int i;
6548 		for (i = 0; i < sg_used; i++) {
6549 			temp64 = dma_map_single(&h->pdev->dev, buff[i],
6550 				    buff_size[i], DMA_BIDIRECTIONAL);
6551 			if (dma_mapping_error(&h->pdev->dev,
6552 							(dma_addr_t) temp64)) {
6553 				c->SG[i].Addr = cpu_to_le64(0);
6554 				c->SG[i].Len = cpu_to_le32(0);
6555 				hpsa_pci_unmap(h->pdev, c, i,
6556 					DMA_BIDIRECTIONAL);
6557 				status = -ENOMEM;
6558 				goto cleanup0;
6559 			}
6560 			c->SG[i].Addr = cpu_to_le64(temp64);
6561 			c->SG[i].Len = cpu_to_le32(buff_size[i]);
6562 			c->SG[i].Ext = cpu_to_le32(0);
6563 		}
6564 		c->SG[--i].Ext = cpu_to_le32(HPSA_SG_LAST);
6565 	}
6566 	status = hpsa_scsi_do_simple_cmd(h, c, DEFAULT_REPLY_QUEUE,
6567 						NO_TIMEOUT);
6568 	if (sg_used)
6569 		hpsa_pci_unmap(h->pdev, c, sg_used, DMA_BIDIRECTIONAL);
6570 	check_ioctl_unit_attention(h, c);
6571 	if (status) {
6572 		status = -EIO;
6573 		goto cleanup0;
6574 	}
6575 
6576 	/* Copy the error information out */
6577 	memcpy(&ioc->error_info, c->err_info, sizeof(ioc->error_info));
6578 	if ((ioc->Request.Type.Direction & XFER_READ) && ioc->buf_size > 0) {
6579 		int i;
6580 
6581 		/* Copy the data out of the buffer we created */
6582 		BYTE __user *ptr = ioc->buf;
6583 		for (i = 0; i < sg_used; i++) {
6584 			if (copy_to_user(ptr, buff[i], buff_size[i])) {
6585 				status = -EFAULT;
6586 				goto cleanup0;
6587 			}
6588 			ptr += buff_size[i];
6589 		}
6590 	}
6591 	status = 0;
6592 cleanup0:
6593 	cmd_free(h, c);
6594 cleanup1:
6595 	if (buff) {
6596 		int i;
6597 
6598 		for (i = 0; i < sg_used; i++)
6599 			kfree(buff[i]);
6600 		kfree(buff);
6601 	}
6602 	kfree(buff_size);
6603 	return status;
6604 }
6605 
6606 static void check_ioctl_unit_attention(struct ctlr_info *h,
6607 	struct CommandList *c)
6608 {
6609 	if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
6610 			c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
6611 		(void) check_for_unit_attention(h, c);
6612 }
6613 
6614 /*
6615  * ioctl
6616  */
6617 static int hpsa_ioctl(struct scsi_device *dev, unsigned int cmd,
6618 		      void __user *argp)
6619 {
6620 	struct ctlr_info *h = sdev_to_hba(dev);
6621 	int rc;
6622 
6623 	switch (cmd) {
6624 	case CCISS_DEREGDISK:
6625 	case CCISS_REGNEWDISK:
6626 	case CCISS_REGNEWD:
6627 		hpsa_scan_start(h->scsi_host);
6628 		return 0;
6629 	case CCISS_GETPCIINFO:
6630 		return hpsa_getpciinfo_ioctl(h, argp);
6631 	case CCISS_GETDRIVVER:
6632 		return hpsa_getdrivver_ioctl(h, argp);
6633 	case CCISS_PASSTHRU: {
6634 		IOCTL_Command_struct iocommand;
6635 
6636 		if (!argp)
6637 			return -EINVAL;
6638 		if (copy_from_user(&iocommand, argp, sizeof(iocommand)))
6639 			return -EFAULT;
6640 		if (atomic_dec_if_positive(&h->passthru_cmds_avail) < 0)
6641 			return -EAGAIN;
6642 		rc = hpsa_passthru_ioctl(h, &iocommand);
6643 		atomic_inc(&h->passthru_cmds_avail);
6644 		if (!rc && copy_to_user(argp, &iocommand, sizeof(iocommand)))
6645 			rc = -EFAULT;
6646 		return rc;
6647 	}
6648 	case CCISS_BIG_PASSTHRU: {
6649 		BIG_IOCTL_Command_struct ioc;
6650 		if (!argp)
6651 			return -EINVAL;
6652 		if (copy_from_user(&ioc, argp, sizeof(ioc)))
6653 			return -EFAULT;
6654 		if (atomic_dec_if_positive(&h->passthru_cmds_avail) < 0)
6655 			return -EAGAIN;
6656 		rc = hpsa_big_passthru_ioctl(h, &ioc);
6657 		atomic_inc(&h->passthru_cmds_avail);
6658 		if (!rc && copy_to_user(argp, &ioc, sizeof(ioc)))
6659 			rc = -EFAULT;
6660 		return rc;
6661 	}
6662 	default:
6663 		return -ENOTTY;
6664 	}
6665 }
6666 
6667 static void hpsa_send_host_reset(struct ctlr_info *h, u8 reset_type)
6668 {
6669 	struct CommandList *c;
6670 
6671 	c = cmd_alloc(h);
6672 
6673 	/* fill_cmd can't fail here, no data buffer to map */
6674 	(void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0,
6675 		RAID_CTLR_LUNID, TYPE_MSG);
6676 	c->Request.CDB[1] = reset_type; /* fill_cmd defaults to target reset */
6677 	c->waiting = NULL;
6678 	enqueue_cmd_and_start_io(h, c);
6679 	/* Don't wait for completion, the reset won't complete.  Don't free
6680 	 * the command either.  This is the last command we will send before
6681 	 * re-initializing everything, so it doesn't matter and won't leak.
6682 	 */
6683 	return;
6684 }
6685 
6686 static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
6687 	void *buff, size_t size, u16 page_code, unsigned char *scsi3addr,
6688 	int cmd_type)
6689 {
6690 	enum dma_data_direction dir = DMA_NONE;
6691 
6692 	c->cmd_type = CMD_IOCTL_PEND;
6693 	c->scsi_cmd = SCSI_CMD_BUSY;
6694 	c->Header.ReplyQueue = 0;
6695 	if (buff != NULL && size > 0) {
6696 		c->Header.SGList = 1;
6697 		c->Header.SGTotal = cpu_to_le16(1);
6698 	} else {
6699 		c->Header.SGList = 0;
6700 		c->Header.SGTotal = cpu_to_le16(0);
6701 	}
6702 	memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
6703 
6704 	if (cmd_type == TYPE_CMD) {
6705 		switch (cmd) {
6706 		case HPSA_INQUIRY:
6707 			/* are we trying to read a vital product page */
6708 			if (page_code & VPD_PAGE) {
6709 				c->Request.CDB[1] = 0x01;
6710 				c->Request.CDB[2] = (page_code & 0xff);
6711 			}
6712 			c->Request.CDBLen = 6;
6713 			c->Request.type_attr_dir =
6714 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6715 			c->Request.Timeout = 0;
6716 			c->Request.CDB[0] = HPSA_INQUIRY;
6717 			c->Request.CDB[4] = size & 0xFF;
6718 			break;
6719 		case RECEIVE_DIAGNOSTIC:
6720 			c->Request.CDBLen = 6;
6721 			c->Request.type_attr_dir =
6722 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6723 			c->Request.Timeout = 0;
6724 			c->Request.CDB[0] = cmd;
6725 			c->Request.CDB[1] = 1;
6726 			c->Request.CDB[2] = 1;
6727 			c->Request.CDB[3] = (size >> 8) & 0xFF;
6728 			c->Request.CDB[4] = size & 0xFF;
6729 			break;
6730 		case HPSA_REPORT_LOG:
6731 		case HPSA_REPORT_PHYS:
6732 			/* Talking to controller so It's a physical command
6733 			   mode = 00 target = 0.  Nothing to write.
6734 			 */
6735 			c->Request.CDBLen = 12;
6736 			c->Request.type_attr_dir =
6737 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6738 			c->Request.Timeout = 0;
6739 			c->Request.CDB[0] = cmd;
6740 			c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
6741 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6742 			c->Request.CDB[8] = (size >> 8) & 0xFF;
6743 			c->Request.CDB[9] = size & 0xFF;
6744 			break;
6745 		case BMIC_SENSE_DIAG_OPTIONS:
6746 			c->Request.CDBLen = 16;
6747 			c->Request.type_attr_dir =
6748 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6749 			c->Request.Timeout = 0;
6750 			/* Spec says this should be BMIC_WRITE */
6751 			c->Request.CDB[0] = BMIC_READ;
6752 			c->Request.CDB[6] = BMIC_SENSE_DIAG_OPTIONS;
6753 			break;
6754 		case BMIC_SET_DIAG_OPTIONS:
6755 			c->Request.CDBLen = 16;
6756 			c->Request.type_attr_dir =
6757 					TYPE_ATTR_DIR(cmd_type,
6758 						ATTR_SIMPLE, XFER_WRITE);
6759 			c->Request.Timeout = 0;
6760 			c->Request.CDB[0] = BMIC_WRITE;
6761 			c->Request.CDB[6] = BMIC_SET_DIAG_OPTIONS;
6762 			break;
6763 		case HPSA_CACHE_FLUSH:
6764 			c->Request.CDBLen = 12;
6765 			c->Request.type_attr_dir =
6766 					TYPE_ATTR_DIR(cmd_type,
6767 						ATTR_SIMPLE, XFER_WRITE);
6768 			c->Request.Timeout = 0;
6769 			c->Request.CDB[0] = BMIC_WRITE;
6770 			c->Request.CDB[6] = BMIC_CACHE_FLUSH;
6771 			c->Request.CDB[7] = (size >> 8) & 0xFF;
6772 			c->Request.CDB[8] = size & 0xFF;
6773 			break;
6774 		case TEST_UNIT_READY:
6775 			c->Request.CDBLen = 6;
6776 			c->Request.type_attr_dir =
6777 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_NONE);
6778 			c->Request.Timeout = 0;
6779 			break;
6780 		case HPSA_GET_RAID_MAP:
6781 			c->Request.CDBLen = 12;
6782 			c->Request.type_attr_dir =
6783 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6784 			c->Request.Timeout = 0;
6785 			c->Request.CDB[0] = HPSA_CISS_READ;
6786 			c->Request.CDB[1] = cmd;
6787 			c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
6788 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6789 			c->Request.CDB[8] = (size >> 8) & 0xFF;
6790 			c->Request.CDB[9] = size & 0xFF;
6791 			break;
6792 		case BMIC_SENSE_CONTROLLER_PARAMETERS:
6793 			c->Request.CDBLen = 10;
6794 			c->Request.type_attr_dir =
6795 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6796 			c->Request.Timeout = 0;
6797 			c->Request.CDB[0] = BMIC_READ;
6798 			c->Request.CDB[6] = BMIC_SENSE_CONTROLLER_PARAMETERS;
6799 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6800 			c->Request.CDB[8] = (size >> 8) & 0xFF;
6801 			break;
6802 		case BMIC_IDENTIFY_PHYSICAL_DEVICE:
6803 			c->Request.CDBLen = 10;
6804 			c->Request.type_attr_dir =
6805 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6806 			c->Request.Timeout = 0;
6807 			c->Request.CDB[0] = BMIC_READ;
6808 			c->Request.CDB[6] = BMIC_IDENTIFY_PHYSICAL_DEVICE;
6809 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6810 			c->Request.CDB[8] = (size >> 8) & 0XFF;
6811 			break;
6812 		case BMIC_SENSE_SUBSYSTEM_INFORMATION:
6813 			c->Request.CDBLen = 10;
6814 			c->Request.type_attr_dir =
6815 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6816 			c->Request.Timeout = 0;
6817 			c->Request.CDB[0] = BMIC_READ;
6818 			c->Request.CDB[6] = BMIC_SENSE_SUBSYSTEM_INFORMATION;
6819 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6820 			c->Request.CDB[8] = (size >> 8) & 0XFF;
6821 			break;
6822 		case BMIC_SENSE_STORAGE_BOX_PARAMS:
6823 			c->Request.CDBLen = 10;
6824 			c->Request.type_attr_dir =
6825 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6826 			c->Request.Timeout = 0;
6827 			c->Request.CDB[0] = BMIC_READ;
6828 			c->Request.CDB[6] = BMIC_SENSE_STORAGE_BOX_PARAMS;
6829 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6830 			c->Request.CDB[8] = (size >> 8) & 0XFF;
6831 			break;
6832 		case BMIC_IDENTIFY_CONTROLLER:
6833 			c->Request.CDBLen = 10;
6834 			c->Request.type_attr_dir =
6835 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_READ);
6836 			c->Request.Timeout = 0;
6837 			c->Request.CDB[0] = BMIC_READ;
6838 			c->Request.CDB[1] = 0;
6839 			c->Request.CDB[2] = 0;
6840 			c->Request.CDB[3] = 0;
6841 			c->Request.CDB[4] = 0;
6842 			c->Request.CDB[5] = 0;
6843 			c->Request.CDB[6] = BMIC_IDENTIFY_CONTROLLER;
6844 			c->Request.CDB[7] = (size >> 16) & 0xFF;
6845 			c->Request.CDB[8] = (size >> 8) & 0XFF;
6846 			c->Request.CDB[9] = 0;
6847 			break;
6848 		default:
6849 			dev_warn(&h->pdev->dev, "unknown command 0x%c\n", cmd);
6850 			BUG();
6851 		}
6852 	} else if (cmd_type == TYPE_MSG) {
6853 		switch (cmd) {
6854 
6855 		case  HPSA_PHYS_TARGET_RESET:
6856 			c->Request.CDBLen = 16;
6857 			c->Request.type_attr_dir =
6858 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_NONE);
6859 			c->Request.Timeout = 0; /* Don't time out */
6860 			memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
6861 			c->Request.CDB[0] = HPSA_RESET;
6862 			c->Request.CDB[1] = HPSA_TARGET_RESET_TYPE;
6863 			/* Physical target reset needs no control bytes 4-7*/
6864 			c->Request.CDB[4] = 0x00;
6865 			c->Request.CDB[5] = 0x00;
6866 			c->Request.CDB[6] = 0x00;
6867 			c->Request.CDB[7] = 0x00;
6868 			break;
6869 		case  HPSA_DEVICE_RESET_MSG:
6870 			c->Request.CDBLen = 16;
6871 			c->Request.type_attr_dir =
6872 				TYPE_ATTR_DIR(cmd_type, ATTR_SIMPLE, XFER_NONE);
6873 			c->Request.Timeout = 0; /* Don't time out */
6874 			memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
6875 			c->Request.CDB[0] =  cmd;
6876 			c->Request.CDB[1] = HPSA_RESET_TYPE_LUN;
6877 			/* If bytes 4-7 are zero, it means reset the */
6878 			/* LunID device */
6879 			c->Request.CDB[4] = 0x00;
6880 			c->Request.CDB[5] = 0x00;
6881 			c->Request.CDB[6] = 0x00;
6882 			c->Request.CDB[7] = 0x00;
6883 			break;
6884 		default:
6885 			dev_warn(&h->pdev->dev, "unknown message type %d\n",
6886 				cmd);
6887 			BUG();
6888 		}
6889 	} else {
6890 		dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
6891 		BUG();
6892 	}
6893 
6894 	switch (GET_DIR(c->Request.type_attr_dir)) {
6895 	case XFER_READ:
6896 		dir = DMA_FROM_DEVICE;
6897 		break;
6898 	case XFER_WRITE:
6899 		dir = DMA_TO_DEVICE;
6900 		break;
6901 	case XFER_NONE:
6902 		dir = DMA_NONE;
6903 		break;
6904 	default:
6905 		dir = DMA_BIDIRECTIONAL;
6906 	}
6907 	if (hpsa_map_one(h->pdev, c, buff, size, dir))
6908 		return -1;
6909 	return 0;
6910 }
6911 
6912 /*
6913  * Map (physical) PCI mem into (virtual) kernel space
6914  */
6915 static void __iomem *remap_pci_mem(ulong base, ulong size)
6916 {
6917 	ulong page_base = ((ulong) base) & PAGE_MASK;
6918 	ulong page_offs = ((ulong) base) - page_base;
6919 	void __iomem *page_remapped = ioremap(page_base,
6920 		page_offs + size);
6921 
6922 	return page_remapped ? (page_remapped + page_offs) : NULL;
6923 }
6924 
6925 static inline unsigned long get_next_completion(struct ctlr_info *h, u8 q)
6926 {
6927 	return h->access.command_completed(h, q);
6928 }
6929 
6930 static inline bool interrupt_pending(struct ctlr_info *h)
6931 {
6932 	return h->access.intr_pending(h);
6933 }
6934 
6935 static inline long interrupt_not_for_us(struct ctlr_info *h)
6936 {
6937 	return (h->access.intr_pending(h) == 0) ||
6938 		(h->interrupts_enabled == 0);
6939 }
6940 
6941 static inline int bad_tag(struct ctlr_info *h, u32 tag_index,
6942 	u32 raw_tag)
6943 {
6944 	if (unlikely(tag_index >= h->nr_cmds)) {
6945 		dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
6946 		return 1;
6947 	}
6948 	return 0;
6949 }
6950 
6951 static inline void finish_cmd(struct CommandList *c)
6952 {
6953 	dial_up_lockup_detection_on_fw_flash_complete(c->h, c);
6954 	if (likely(c->cmd_type == CMD_IOACCEL1 || c->cmd_type == CMD_SCSI
6955 			|| c->cmd_type == CMD_IOACCEL2))
6956 		complete_scsi_command(c);
6957 	else if (c->cmd_type == CMD_IOCTL_PEND || c->cmd_type == IOACCEL2_TMF)
6958 		complete(c->waiting);
6959 }
6960 
6961 /* process completion of an indexed ("direct lookup") command */
6962 static inline void process_indexed_cmd(struct ctlr_info *h,
6963 	u32 raw_tag)
6964 {
6965 	u32 tag_index;
6966 	struct CommandList *c;
6967 
6968 	tag_index = raw_tag >> DIRECT_LOOKUP_SHIFT;
6969 	if (!bad_tag(h, tag_index, raw_tag)) {
6970 		c = h->cmd_pool + tag_index;
6971 		finish_cmd(c);
6972 	}
6973 }
6974 
6975 /* Some controllers, like p400, will give us one interrupt
6976  * after a soft reset, even if we turned interrupts off.
6977  * Only need to check for this in the hpsa_xxx_discard_completions
6978  * functions.
6979  */
6980 static int ignore_bogus_interrupt(struct ctlr_info *h)
6981 {
6982 	if (likely(!reset_devices))
6983 		return 0;
6984 
6985 	if (likely(h->interrupts_enabled))
6986 		return 0;
6987 
6988 	dev_info(&h->pdev->dev, "Received interrupt while interrupts disabled "
6989 		"(known firmware bug.)  Ignoring.\n");
6990 
6991 	return 1;
6992 }
6993 
6994 /*
6995  * Convert &h->q[x] (passed to interrupt handlers) back to h.
6996  * Relies on (h-q[x] == x) being true for x such that
6997  * 0 <= x < MAX_REPLY_QUEUES.
6998  */
6999 static struct ctlr_info *queue_to_hba(u8 *queue)
7000 {
7001 	return container_of((queue - *queue), struct ctlr_info, q[0]);
7002 }
7003 
7004 static irqreturn_t hpsa_intx_discard_completions(int irq, void *queue)
7005 {
7006 	struct ctlr_info *h = queue_to_hba(queue);
7007 	u8 q = *(u8 *) queue;
7008 	u32 raw_tag;
7009 
7010 	if (ignore_bogus_interrupt(h))
7011 		return IRQ_NONE;
7012 
7013 	if (interrupt_not_for_us(h))
7014 		return IRQ_NONE;
7015 	h->last_intr_timestamp = get_jiffies_64();
7016 	while (interrupt_pending(h)) {
7017 		raw_tag = get_next_completion(h, q);
7018 		while (raw_tag != FIFO_EMPTY)
7019 			raw_tag = next_command(h, q);
7020 	}
7021 	return IRQ_HANDLED;
7022 }
7023 
7024 static irqreturn_t hpsa_msix_discard_completions(int irq, void *queue)
7025 {
7026 	struct ctlr_info *h = queue_to_hba(queue);
7027 	u32 raw_tag;
7028 	u8 q = *(u8 *) queue;
7029 
7030 	if (ignore_bogus_interrupt(h))
7031 		return IRQ_NONE;
7032 
7033 	h->last_intr_timestamp = get_jiffies_64();
7034 	raw_tag = get_next_completion(h, q);
7035 	while (raw_tag != FIFO_EMPTY)
7036 		raw_tag = next_command(h, q);
7037 	return IRQ_HANDLED;
7038 }
7039 
7040 static irqreturn_t do_hpsa_intr_intx(int irq, void *queue)
7041 {
7042 	struct ctlr_info *h = queue_to_hba((u8 *) queue);
7043 	u32 raw_tag;
7044 	u8 q = *(u8 *) queue;
7045 
7046 	if (interrupt_not_for_us(h))
7047 		return IRQ_NONE;
7048 	h->last_intr_timestamp = get_jiffies_64();
7049 	while (interrupt_pending(h)) {
7050 		raw_tag = get_next_completion(h, q);
7051 		while (raw_tag != FIFO_EMPTY) {
7052 			process_indexed_cmd(h, raw_tag);
7053 			raw_tag = next_command(h, q);
7054 		}
7055 	}
7056 	return IRQ_HANDLED;
7057 }
7058 
7059 static irqreturn_t do_hpsa_intr_msi(int irq, void *queue)
7060 {
7061 	struct ctlr_info *h = queue_to_hba(queue);
7062 	u32 raw_tag;
7063 	u8 q = *(u8 *) queue;
7064 
7065 	h->last_intr_timestamp = get_jiffies_64();
7066 	raw_tag = get_next_completion(h, q);
7067 	while (raw_tag != FIFO_EMPTY) {
7068 		process_indexed_cmd(h, raw_tag);
7069 		raw_tag = next_command(h, q);
7070 	}
7071 	return IRQ_HANDLED;
7072 }
7073 
7074 /* Send a message CDB to the firmware. Careful, this only works
7075  * in simple mode, not performant mode due to the tag lookup.
7076  * We only ever use this immediately after a controller reset.
7077  */
7078 static int hpsa_message(struct pci_dev *pdev, unsigned char opcode,
7079 			unsigned char type)
7080 {
7081 	struct Command {
7082 		struct CommandListHeader CommandHeader;
7083 		struct RequestBlock Request;
7084 		struct ErrDescriptor ErrorDescriptor;
7085 	};
7086 	struct Command *cmd;
7087 	static const size_t cmd_sz = sizeof(*cmd) +
7088 					sizeof(cmd->ErrorDescriptor);
7089 	dma_addr_t paddr64;
7090 	__le32 paddr32;
7091 	u32 tag;
7092 	void __iomem *vaddr;
7093 	int i, err;
7094 
7095 	vaddr = pci_ioremap_bar(pdev, 0);
7096 	if (vaddr == NULL)
7097 		return -ENOMEM;
7098 
7099 	/* The Inbound Post Queue only accepts 32-bit physical addresses for the
7100 	 * CCISS commands, so they must be allocated from the lower 4GiB of
7101 	 * memory.
7102 	 */
7103 	err = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
7104 	if (err) {
7105 		iounmap(vaddr);
7106 		return err;
7107 	}
7108 
7109 	cmd = dma_alloc_coherent(&pdev->dev, cmd_sz, &paddr64, GFP_KERNEL);
7110 	if (cmd == NULL) {
7111 		iounmap(vaddr);
7112 		return -ENOMEM;
7113 	}
7114 
7115 	/* This must fit, because of the 32-bit consistent DMA mask.  Also,
7116 	 * although there's no guarantee, we assume that the address is at
7117 	 * least 4-byte aligned (most likely, it's page-aligned).
7118 	 */
7119 	paddr32 = cpu_to_le32(paddr64);
7120 
7121 	cmd->CommandHeader.ReplyQueue = 0;
7122 	cmd->CommandHeader.SGList = 0;
7123 	cmd->CommandHeader.SGTotal = cpu_to_le16(0);
7124 	cmd->CommandHeader.tag = cpu_to_le64(paddr64);
7125 	memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
7126 
7127 	cmd->Request.CDBLen = 16;
7128 	cmd->Request.type_attr_dir =
7129 			TYPE_ATTR_DIR(TYPE_MSG, ATTR_HEADOFQUEUE, XFER_NONE);
7130 	cmd->Request.Timeout = 0; /* Don't time out */
7131 	cmd->Request.CDB[0] = opcode;
7132 	cmd->Request.CDB[1] = type;
7133 	memset(&cmd->Request.CDB[2], 0, 14); /* rest of the CDB is reserved */
7134 	cmd->ErrorDescriptor.Addr =
7135 			cpu_to_le64((le32_to_cpu(paddr32) + sizeof(*cmd)));
7136 	cmd->ErrorDescriptor.Len = cpu_to_le32(sizeof(struct ErrorInfo));
7137 
7138 	writel(le32_to_cpu(paddr32), vaddr + SA5_REQUEST_PORT_OFFSET);
7139 
7140 	for (i = 0; i < HPSA_MSG_SEND_RETRY_LIMIT; i++) {
7141 		tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
7142 		if ((tag & ~HPSA_SIMPLE_ERROR_BITS) == paddr64)
7143 			break;
7144 		msleep(HPSA_MSG_SEND_RETRY_INTERVAL_MSECS);
7145 	}
7146 
7147 	iounmap(vaddr);
7148 
7149 	/* we leak the DMA buffer here ... no choice since the controller could
7150 	 *  still complete the command.
7151 	 */
7152 	if (i == HPSA_MSG_SEND_RETRY_LIMIT) {
7153 		dev_err(&pdev->dev, "controller message %02x:%02x timed out\n",
7154 			opcode, type);
7155 		return -ETIMEDOUT;
7156 	}
7157 
7158 	dma_free_coherent(&pdev->dev, cmd_sz, cmd, paddr64);
7159 
7160 	if (tag & HPSA_ERROR_BIT) {
7161 		dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
7162 			opcode, type);
7163 		return -EIO;
7164 	}
7165 
7166 	dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
7167 		opcode, type);
7168 	return 0;
7169 }
7170 
7171 #define hpsa_noop(p) hpsa_message(p, 3, 0)
7172 
7173 static int hpsa_controller_hard_reset(struct pci_dev *pdev,
7174 	void __iomem *vaddr, u32 use_doorbell)
7175 {
7176 
7177 	if (use_doorbell) {
7178 		/* For everything after the P600, the PCI power state method
7179 		 * of resetting the controller doesn't work, so we have this
7180 		 * other way using the doorbell register.
7181 		 */
7182 		dev_info(&pdev->dev, "using doorbell to reset controller\n");
7183 		writel(use_doorbell, vaddr + SA5_DOORBELL);
7184 
7185 		/* PMC hardware guys tell us we need a 10 second delay after
7186 		 * doorbell reset and before any attempt to talk to the board
7187 		 * at all to ensure that this actually works and doesn't fall
7188 		 * over in some weird corner cases.
7189 		 */
7190 		msleep(10000);
7191 	} else { /* Try to do it the PCI power state way */
7192 
7193 		/* Quoting from the Open CISS Specification: "The Power
7194 		 * Management Control/Status Register (CSR) controls the power
7195 		 * state of the device.  The normal operating state is D0,
7196 		 * CSR=00h.  The software off state is D3, CSR=03h.  To reset
7197 		 * the controller, place the interface device in D3 then to D0,
7198 		 * this causes a secondary PCI reset which will reset the
7199 		 * controller." */
7200 
7201 		int rc = 0;
7202 
7203 		dev_info(&pdev->dev, "using PCI PM to reset controller\n");
7204 
7205 		/* enter the D3hot power management state */
7206 		rc = pci_set_power_state(pdev, PCI_D3hot);
7207 		if (rc)
7208 			return rc;
7209 
7210 		msleep(500);
7211 
7212 		/* enter the D0 power management state */
7213 		rc = pci_set_power_state(pdev, PCI_D0);
7214 		if (rc)
7215 			return rc;
7216 
7217 		/*
7218 		 * The P600 requires a small delay when changing states.
7219 		 * Otherwise we may think the board did not reset and we bail.
7220 		 * This for kdump only and is particular to the P600.
7221 		 */
7222 		msleep(500);
7223 	}
7224 	return 0;
7225 }
7226 
7227 static void init_driver_version(char *driver_version, int len)
7228 {
7229 	strscpy_pad(driver_version, HPSA " " HPSA_DRIVER_VERSION, len);
7230 }
7231 
7232 static int write_driver_ver_to_cfgtable(struct CfgTable __iomem *cfgtable)
7233 {
7234 	char *driver_version;
7235 	int i, size = sizeof(cfgtable->driver_version);
7236 
7237 	driver_version = kmalloc(size, GFP_KERNEL);
7238 	if (!driver_version)
7239 		return -ENOMEM;
7240 
7241 	init_driver_version(driver_version, size);
7242 	for (i = 0; i < size; i++)
7243 		writeb(driver_version[i], &cfgtable->driver_version[i]);
7244 	kfree(driver_version);
7245 	return 0;
7246 }
7247 
7248 static void read_driver_ver_from_cfgtable(struct CfgTable __iomem *cfgtable,
7249 					  unsigned char *driver_ver)
7250 {
7251 	int i;
7252 
7253 	for (i = 0; i < sizeof(cfgtable->driver_version); i++)
7254 		driver_ver[i] = readb(&cfgtable->driver_version[i]);
7255 }
7256 
7257 static int controller_reset_failed(struct CfgTable __iomem *cfgtable)
7258 {
7259 
7260 	char *driver_ver, *old_driver_ver;
7261 	int rc, size = sizeof(cfgtable->driver_version);
7262 
7263 	old_driver_ver = kmalloc_array(2, size, GFP_KERNEL);
7264 	if (!old_driver_ver)
7265 		return -ENOMEM;
7266 	driver_ver = old_driver_ver + size;
7267 
7268 	/* After a reset, the 32 bytes of "driver version" in the cfgtable
7269 	 * should have been changed, otherwise we know the reset failed.
7270 	 */
7271 	init_driver_version(old_driver_ver, size);
7272 	read_driver_ver_from_cfgtable(cfgtable, driver_ver);
7273 	rc = !memcmp(driver_ver, old_driver_ver, size);
7274 	kfree(old_driver_ver);
7275 	return rc;
7276 }
7277 /* This does a hard reset of the controller using PCI power management
7278  * states or the using the doorbell register.
7279  */
7280 static int hpsa_kdump_hard_reset_controller(struct pci_dev *pdev, u32 board_id)
7281 {
7282 	u64 cfg_offset;
7283 	u32 cfg_base_addr;
7284 	u64 cfg_base_addr_index;
7285 	void __iomem *vaddr;
7286 	unsigned long paddr;
7287 	u32 misc_fw_support;
7288 	int rc;
7289 	struct CfgTable __iomem *cfgtable;
7290 	u32 use_doorbell;
7291 	u16 command_register;
7292 
7293 	/* For controllers as old as the P600, this is very nearly
7294 	 * the same thing as
7295 	 *
7296 	 * pci_save_state(pci_dev);
7297 	 * pci_set_power_state(pci_dev, PCI_D3hot);
7298 	 * pci_set_power_state(pci_dev, PCI_D0);
7299 	 * pci_restore_state(pci_dev);
7300 	 *
7301 	 * For controllers newer than the P600, the pci power state
7302 	 * method of resetting doesn't work so we have another way
7303 	 * using the doorbell register.
7304 	 */
7305 
7306 	if (!ctlr_is_resettable(board_id)) {
7307 		dev_warn(&pdev->dev, "Controller not resettable\n");
7308 		return -ENODEV;
7309 	}
7310 
7311 	/* if controller is soft- but not hard resettable... */
7312 	if (!ctlr_is_hard_resettable(board_id))
7313 		return -ENOTSUPP; /* try soft reset later. */
7314 
7315 	/* Save the PCI command register */
7316 	pci_read_config_word(pdev, 4, &command_register);
7317 	pci_save_state(pdev);
7318 
7319 	/* find the first memory BAR, so we can find the cfg table */
7320 	rc = hpsa_pci_find_memory_BAR(pdev, &paddr);
7321 	if (rc)
7322 		return rc;
7323 	vaddr = remap_pci_mem(paddr, 0x250);
7324 	if (!vaddr)
7325 		return -ENOMEM;
7326 
7327 	/* find cfgtable in order to check if reset via doorbell is supported */
7328 	rc = hpsa_find_cfg_addrs(pdev, vaddr, &cfg_base_addr,
7329 					&cfg_base_addr_index, &cfg_offset);
7330 	if (rc)
7331 		goto unmap_vaddr;
7332 	cfgtable = remap_pci_mem(pci_resource_start(pdev,
7333 		       cfg_base_addr_index) + cfg_offset, sizeof(*cfgtable));
7334 	if (!cfgtable) {
7335 		rc = -ENOMEM;
7336 		goto unmap_vaddr;
7337 	}
7338 	rc = write_driver_ver_to_cfgtable(cfgtable);
7339 	if (rc)
7340 		goto unmap_cfgtable;
7341 
7342 	/* If reset via doorbell register is supported, use that.
7343 	 * There are two such methods.  Favor the newest method.
7344 	 */
7345 	misc_fw_support = readl(&cfgtable->misc_fw_support);
7346 	use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET2;
7347 	if (use_doorbell) {
7348 		use_doorbell = DOORBELL_CTLR_RESET2;
7349 	} else {
7350 		use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET;
7351 		if (use_doorbell) {
7352 			dev_warn(&pdev->dev,
7353 				"Soft reset not supported. Firmware update is required.\n");
7354 			rc = -ENOTSUPP; /* try soft reset */
7355 			goto unmap_cfgtable;
7356 		}
7357 	}
7358 
7359 	rc = hpsa_controller_hard_reset(pdev, vaddr, use_doorbell);
7360 	if (rc)
7361 		goto unmap_cfgtable;
7362 
7363 	pci_restore_state(pdev);
7364 	pci_write_config_word(pdev, 4, command_register);
7365 
7366 	/* Some devices (notably the HP Smart Array 5i Controller)
7367 	   need a little pause here */
7368 	msleep(HPSA_POST_RESET_PAUSE_MSECS);
7369 
7370 	rc = hpsa_wait_for_board_state(pdev, vaddr, BOARD_READY);
7371 	if (rc) {
7372 		dev_warn(&pdev->dev,
7373 			"Failed waiting for board to become ready after hard reset\n");
7374 		goto unmap_cfgtable;
7375 	}
7376 
7377 	rc = controller_reset_failed(vaddr);
7378 	if (rc < 0)
7379 		goto unmap_cfgtable;
7380 	if (rc) {
7381 		dev_warn(&pdev->dev, "Unable to successfully reset "
7382 			"controller. Will try soft reset.\n");
7383 		rc = -ENOTSUPP;
7384 	} else {
7385 		dev_info(&pdev->dev, "board ready after hard reset.\n");
7386 	}
7387 
7388 unmap_cfgtable:
7389 	iounmap(cfgtable);
7390 
7391 unmap_vaddr:
7392 	iounmap(vaddr);
7393 	return rc;
7394 }
7395 
7396 /*
7397  *  We cannot read the structure directly, for portability we must use
7398  *   the io functions.
7399  *   This is for debug only.
7400  */
7401 static void print_cfg_table(struct device *dev, struct CfgTable __iomem *tb)
7402 {
7403 #ifdef HPSA_DEBUG
7404 	int i;
7405 	char temp_name[17];
7406 
7407 	dev_info(dev, "Controller Configuration information\n");
7408 	dev_info(dev, "------------------------------------\n");
7409 	for (i = 0; i < 4; i++)
7410 		temp_name[i] = readb(&(tb->Signature[i]));
7411 	temp_name[4] = '\0';
7412 	dev_info(dev, "   Signature = %s\n", temp_name);
7413 	dev_info(dev, "   Spec Number = %d\n", readl(&(tb->SpecValence)));
7414 	dev_info(dev, "   Transport methods supported = 0x%x\n",
7415 	       readl(&(tb->TransportSupport)));
7416 	dev_info(dev, "   Transport methods active = 0x%x\n",
7417 	       readl(&(tb->TransportActive)));
7418 	dev_info(dev, "   Requested transport Method = 0x%x\n",
7419 	       readl(&(tb->HostWrite.TransportRequest)));
7420 	dev_info(dev, "   Coalesce Interrupt Delay = 0x%x\n",
7421 	       readl(&(tb->HostWrite.CoalIntDelay)));
7422 	dev_info(dev, "   Coalesce Interrupt Count = 0x%x\n",
7423 	       readl(&(tb->HostWrite.CoalIntCount)));
7424 	dev_info(dev, "   Max outstanding commands = %d\n",
7425 	       readl(&(tb->CmdsOutMax)));
7426 	dev_info(dev, "   Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
7427 	for (i = 0; i < 16; i++)
7428 		temp_name[i] = readb(&(tb->ServerName[i]));
7429 	temp_name[16] = '\0';
7430 	dev_info(dev, "   Server Name = %s\n", temp_name);
7431 	dev_info(dev, "   Heartbeat Counter = 0x%x\n\n\n",
7432 		readl(&(tb->HeartBeat)));
7433 #endif				/* HPSA_DEBUG */
7434 }
7435 
7436 static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
7437 {
7438 	int i, offset, mem_type, bar_type;
7439 
7440 	if (pci_bar_addr == PCI_BASE_ADDRESS_0)	/* looking for BAR zero? */
7441 		return 0;
7442 	offset = 0;
7443 	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
7444 		bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
7445 		if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
7446 			offset += 4;
7447 		else {
7448 			mem_type = pci_resource_flags(pdev, i) &
7449 			    PCI_BASE_ADDRESS_MEM_TYPE_MASK;
7450 			switch (mem_type) {
7451 			case PCI_BASE_ADDRESS_MEM_TYPE_32:
7452 			case PCI_BASE_ADDRESS_MEM_TYPE_1M:
7453 				offset += 4;	/* 32 bit */
7454 				break;
7455 			case PCI_BASE_ADDRESS_MEM_TYPE_64:
7456 				offset += 8;
7457 				break;
7458 			default:	/* reserved in PCI 2.2 */
7459 				dev_warn(&pdev->dev,
7460 				       "base address is invalid\n");
7461 				return -1;
7462 			}
7463 		}
7464 		if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
7465 			return i + 1;
7466 	}
7467 	return -1;
7468 }
7469 
7470 static void hpsa_disable_interrupt_mode(struct ctlr_info *h)
7471 {
7472 	pci_free_irq_vectors(h->pdev);
7473 	h->msix_vectors = 0;
7474 }
7475 
7476 static void hpsa_setup_reply_map(struct ctlr_info *h)
7477 {
7478 	const struct cpumask *mask;
7479 	unsigned int queue, cpu;
7480 
7481 	for (queue = 0; queue < h->msix_vectors; queue++) {
7482 		mask = pci_irq_get_affinity(h->pdev, queue);
7483 		if (!mask)
7484 			goto fallback;
7485 
7486 		for_each_cpu(cpu, mask)
7487 			h->reply_map[cpu] = queue;
7488 	}
7489 	return;
7490 
7491 fallback:
7492 	for_each_possible_cpu(cpu)
7493 		h->reply_map[cpu] = 0;
7494 }
7495 
7496 /* If MSI/MSI-X is supported by the kernel we will try to enable it on
7497  * controllers that are capable. If not, we use legacy INTx mode.
7498  */
7499 static int hpsa_interrupt_mode(struct ctlr_info *h)
7500 {
7501 	unsigned int flags = PCI_IRQ_INTX;
7502 	int ret;
7503 
7504 	/* Some boards advertise MSI but don't really support it */
7505 	switch (h->board_id) {
7506 	case 0x40700E11:
7507 	case 0x40800E11:
7508 	case 0x40820E11:
7509 	case 0x40830E11:
7510 		break;
7511 	default:
7512 		ret = pci_alloc_irq_vectors(h->pdev, 1, MAX_REPLY_QUEUES,
7513 				PCI_IRQ_MSIX | PCI_IRQ_AFFINITY);
7514 		if (ret > 0) {
7515 			h->msix_vectors = ret;
7516 			return 0;
7517 		}
7518 
7519 		flags |= PCI_IRQ_MSI;
7520 		break;
7521 	}
7522 
7523 	ret = pci_alloc_irq_vectors(h->pdev, 1, 1, flags);
7524 	if (ret < 0)
7525 		return ret;
7526 	return 0;
7527 }
7528 
7529 static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id,
7530 				bool *legacy_board)
7531 {
7532 	int i;
7533 	u32 subsystem_vendor_id, subsystem_device_id;
7534 
7535 	subsystem_vendor_id = pdev->subsystem_vendor;
7536 	subsystem_device_id = pdev->subsystem_device;
7537 	*board_id = ((subsystem_device_id << 16) & 0xffff0000) |
7538 		    subsystem_vendor_id;
7539 
7540 	if (legacy_board)
7541 		*legacy_board = false;
7542 	for (i = 0; i < ARRAY_SIZE(products); i++)
7543 		if (*board_id == products[i].board_id) {
7544 			if (products[i].access != &SA5A_access &&
7545 			    products[i].access != &SA5B_access)
7546 				return i;
7547 			dev_warn(&pdev->dev,
7548 				 "legacy board ID: 0x%08x\n",
7549 				 *board_id);
7550 			if (legacy_board)
7551 			    *legacy_board = true;
7552 			return i;
7553 		}
7554 
7555 	dev_warn(&pdev->dev, "unrecognized board ID: 0x%08x\n", *board_id);
7556 	if (legacy_board)
7557 		*legacy_board = true;
7558 	return ARRAY_SIZE(products) - 1; /* generic unknown smart array */
7559 }
7560 
7561 static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
7562 				    unsigned long *memory_bar)
7563 {
7564 	int i;
7565 
7566 	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
7567 		if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
7568 			/* addressing mode bits already removed */
7569 			*memory_bar = pci_resource_start(pdev, i);
7570 			dev_dbg(&pdev->dev, "memory BAR = %lx\n",
7571 				*memory_bar);
7572 			return 0;
7573 		}
7574 	dev_warn(&pdev->dev, "no memory BAR found\n");
7575 	return -ENODEV;
7576 }
7577 
7578 static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
7579 				     int wait_for_ready)
7580 {
7581 	int i, iterations;
7582 	u32 scratchpad;
7583 	if (wait_for_ready)
7584 		iterations = HPSA_BOARD_READY_ITERATIONS;
7585 	else
7586 		iterations = HPSA_BOARD_NOT_READY_ITERATIONS;
7587 
7588 	for (i = 0; i < iterations; i++) {
7589 		scratchpad = readl(vaddr + SA5_SCRATCHPAD_OFFSET);
7590 		if (wait_for_ready) {
7591 			if (scratchpad == HPSA_FIRMWARE_READY)
7592 				return 0;
7593 		} else {
7594 			if (scratchpad != HPSA_FIRMWARE_READY)
7595 				return 0;
7596 		}
7597 		msleep(HPSA_BOARD_READY_POLL_INTERVAL_MSECS);
7598 	}
7599 	dev_warn(&pdev->dev, "board not ready, timed out.\n");
7600 	return -ENODEV;
7601 }
7602 
7603 static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
7604 			       u32 *cfg_base_addr, u64 *cfg_base_addr_index,
7605 			       u64 *cfg_offset)
7606 {
7607 	*cfg_base_addr = readl(vaddr + SA5_CTCFG_OFFSET);
7608 	*cfg_offset = readl(vaddr + SA5_CTMEM_OFFSET);
7609 	*cfg_base_addr &= (u32) 0x0000ffff;
7610 	*cfg_base_addr_index = find_PCI_BAR_index(pdev, *cfg_base_addr);
7611 	if (*cfg_base_addr_index == -1) {
7612 		dev_warn(&pdev->dev, "cannot find cfg_base_addr_index\n");
7613 		return -ENODEV;
7614 	}
7615 	return 0;
7616 }
7617 
7618 static void hpsa_free_cfgtables(struct ctlr_info *h)
7619 {
7620 	if (h->transtable) {
7621 		iounmap(h->transtable);
7622 		h->transtable = NULL;
7623 	}
7624 	if (h->cfgtable) {
7625 		iounmap(h->cfgtable);
7626 		h->cfgtable = NULL;
7627 	}
7628 }
7629 
7630 /* Find and map CISS config table and transfer table
7631  * several items must be unmapped (freed) later
7632  */
7633 static int hpsa_find_cfgtables(struct ctlr_info *h)
7634 {
7635 	u64 cfg_offset;
7636 	u32 cfg_base_addr;
7637 	u64 cfg_base_addr_index;
7638 	u32 trans_offset;
7639 	int rc;
7640 
7641 	rc = hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
7642 		&cfg_base_addr_index, &cfg_offset);
7643 	if (rc)
7644 		return rc;
7645 	h->cfgtable = remap_pci_mem(pci_resource_start(h->pdev,
7646 		       cfg_base_addr_index) + cfg_offset, sizeof(*h->cfgtable));
7647 	if (!h->cfgtable) {
7648 		dev_err(&h->pdev->dev, "Failed mapping cfgtable\n");
7649 		return -ENOMEM;
7650 	}
7651 	rc = write_driver_ver_to_cfgtable(h->cfgtable);
7652 	if (rc)
7653 		return rc;
7654 	/* Find performant mode table. */
7655 	trans_offset = readl(&h->cfgtable->TransMethodOffset);
7656 	h->transtable = remap_pci_mem(pci_resource_start(h->pdev,
7657 				cfg_base_addr_index)+cfg_offset+trans_offset,
7658 				sizeof(*h->transtable));
7659 	if (!h->transtable) {
7660 		dev_err(&h->pdev->dev, "Failed mapping transfer table\n");
7661 		hpsa_free_cfgtables(h);
7662 		return -ENOMEM;
7663 	}
7664 	return 0;
7665 }
7666 
7667 static void hpsa_get_max_perf_mode_cmds(struct ctlr_info *h)
7668 {
7669 #define MIN_MAX_COMMANDS 16
7670 	BUILD_BUG_ON(MIN_MAX_COMMANDS <= HPSA_NRESERVED_CMDS);
7671 
7672 	h->max_commands = readl(&h->cfgtable->MaxPerformantModeCommands);
7673 
7674 	/* Limit commands in memory limited kdump scenario. */
7675 	if (reset_devices && h->max_commands > 32)
7676 		h->max_commands = 32;
7677 
7678 	if (h->max_commands < MIN_MAX_COMMANDS) {
7679 		dev_warn(&h->pdev->dev,
7680 			"Controller reports max supported commands of %d Using %d instead. Ensure that firmware is up to date.\n",
7681 			h->max_commands,
7682 			MIN_MAX_COMMANDS);
7683 		h->max_commands = MIN_MAX_COMMANDS;
7684 	}
7685 }
7686 
7687 /* If the controller reports that the total max sg entries is greater than 512,
7688  * then we know that chained SG blocks work.  (Original smart arrays did not
7689  * support chained SG blocks and would return zero for max sg entries.)
7690  */
7691 static int hpsa_supports_chained_sg_blocks(struct ctlr_info *h)
7692 {
7693 	return h->maxsgentries > 512;
7694 }
7695 
7696 /* Interrogate the hardware for some limits:
7697  * max commands, max SG elements without chaining, and with chaining,
7698  * SG chain block size, etc.
7699  */
7700 static void hpsa_find_board_params(struct ctlr_info *h)
7701 {
7702 	hpsa_get_max_perf_mode_cmds(h);
7703 	h->nr_cmds = h->max_commands;
7704 	h->maxsgentries = readl(&(h->cfgtable->MaxScatterGatherElements));
7705 	h->fw_support = readl(&(h->cfgtable->misc_fw_support));
7706 	if (hpsa_supports_chained_sg_blocks(h)) {
7707 		/* Limit in-command s/g elements to 32 save dma'able memory. */
7708 		h->max_cmd_sg_entries = 32;
7709 		h->chainsize = h->maxsgentries - h->max_cmd_sg_entries;
7710 		h->maxsgentries--; /* save one for chain pointer */
7711 	} else {
7712 		/*
7713 		 * Original smart arrays supported at most 31 s/g entries
7714 		 * embedded inline in the command (trying to use more
7715 		 * would lock up the controller)
7716 		 */
7717 		h->max_cmd_sg_entries = 31;
7718 		h->maxsgentries = 31; /* default to traditional values */
7719 		h->chainsize = 0;
7720 	}
7721 
7722 	/* Find out what task management functions are supported and cache */
7723 	h->TMFSupportFlags = readl(&(h->cfgtable->TMFSupportFlags));
7724 	if (!(HPSATMF_PHYS_TASK_ABORT & h->TMFSupportFlags))
7725 		dev_warn(&h->pdev->dev, "Physical aborts not supported\n");
7726 	if (!(HPSATMF_LOG_TASK_ABORT & h->TMFSupportFlags))
7727 		dev_warn(&h->pdev->dev, "Logical aborts not supported\n");
7728 	if (!(HPSATMF_IOACCEL_ENABLED & h->TMFSupportFlags))
7729 		dev_warn(&h->pdev->dev, "HP SSD Smart Path aborts not supported\n");
7730 }
7731 
7732 static inline bool hpsa_CISS_signature_present(struct ctlr_info *h)
7733 {
7734 	if (!check_signature(h->cfgtable->Signature, "CISS", 4)) {
7735 		dev_err(&h->pdev->dev, "not a valid CISS config table\n");
7736 		return false;
7737 	}
7738 	return true;
7739 }
7740 
7741 static inline void hpsa_set_driver_support_bits(struct ctlr_info *h)
7742 {
7743 	u32 driver_support;
7744 
7745 	driver_support = readl(&(h->cfgtable->driver_support));
7746 	/* Need to enable prefetch in the SCSI core for 6400 in x86 */
7747 #ifdef CONFIG_X86
7748 	driver_support |= ENABLE_SCSI_PREFETCH;
7749 #endif
7750 	driver_support |= ENABLE_UNIT_ATTN;
7751 	writel(driver_support, &(h->cfgtable->driver_support));
7752 }
7753 
7754 /* Disable DMA prefetch for the P600.  Otherwise an ASIC bug may result
7755  * in a prefetch beyond physical memory.
7756  */
7757 static inline void hpsa_p600_dma_prefetch_quirk(struct ctlr_info *h)
7758 {
7759 	u32 dma_prefetch;
7760 
7761 	if (h->board_id != 0x3225103C)
7762 		return;
7763 	dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
7764 	dma_prefetch |= 0x8000;
7765 	writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
7766 }
7767 
7768 static int hpsa_wait_for_clear_event_notify_ack(struct ctlr_info *h)
7769 {
7770 	int i;
7771 	u32 doorbell_value;
7772 	unsigned long flags;
7773 	/* wait until the clear_event_notify bit 6 is cleared by controller. */
7774 	for (i = 0; i < MAX_CLEAR_EVENT_WAIT; i++) {
7775 		spin_lock_irqsave(&h->lock, flags);
7776 		doorbell_value = readl(h->vaddr + SA5_DOORBELL);
7777 		spin_unlock_irqrestore(&h->lock, flags);
7778 		if (!(doorbell_value & DOORBELL_CLEAR_EVENTS))
7779 			goto done;
7780 		/* delay and try again */
7781 		msleep(CLEAR_EVENT_WAIT_INTERVAL);
7782 	}
7783 	return -ENODEV;
7784 done:
7785 	return 0;
7786 }
7787 
7788 static int hpsa_wait_for_mode_change_ack(struct ctlr_info *h)
7789 {
7790 	int i;
7791 	u32 doorbell_value;
7792 	unsigned long flags;
7793 
7794 	/* under certain very rare conditions, this can take awhile.
7795 	 * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
7796 	 * as we enter this code.)
7797 	 */
7798 	for (i = 0; i < MAX_MODE_CHANGE_WAIT; i++) {
7799 		if (h->remove_in_progress)
7800 			goto done;
7801 		spin_lock_irqsave(&h->lock, flags);
7802 		doorbell_value = readl(h->vaddr + SA5_DOORBELL);
7803 		spin_unlock_irqrestore(&h->lock, flags);
7804 		if (!(doorbell_value & CFGTBL_ChangeReq))
7805 			goto done;
7806 		/* delay and try again */
7807 		msleep(MODE_CHANGE_WAIT_INTERVAL);
7808 	}
7809 	return -ENODEV;
7810 done:
7811 	return 0;
7812 }
7813 
7814 /* return -ENODEV or other reason on error, 0 on success */
7815 static int hpsa_enter_simple_mode(struct ctlr_info *h)
7816 {
7817 	u32 trans_support;
7818 
7819 	trans_support = readl(&(h->cfgtable->TransportSupport));
7820 	if (!(trans_support & SIMPLE_MODE))
7821 		return -ENOTSUPP;
7822 
7823 	h->max_commands = readl(&(h->cfgtable->CmdsOutMax));
7824 
7825 	/* Update the field, and then ring the doorbell */
7826 	writel(CFGTBL_Trans_Simple, &(h->cfgtable->HostWrite.TransportRequest));
7827 	writel(0, &h->cfgtable->HostWrite.command_pool_addr_hi);
7828 	writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
7829 	if (hpsa_wait_for_mode_change_ack(h))
7830 		goto error;
7831 	print_cfg_table(&h->pdev->dev, h->cfgtable);
7832 	if (!(readl(&(h->cfgtable->TransportActive)) & CFGTBL_Trans_Simple))
7833 		goto error;
7834 	h->transMethod = CFGTBL_Trans_Simple;
7835 	return 0;
7836 error:
7837 	dev_err(&h->pdev->dev, "failed to enter simple mode\n");
7838 	return -ENODEV;
7839 }
7840 
7841 /* free items allocated or mapped by hpsa_pci_init */
7842 static void hpsa_free_pci_init(struct ctlr_info *h)
7843 {
7844 	hpsa_free_cfgtables(h);			/* pci_init 4 */
7845 	iounmap(h->vaddr);			/* pci_init 3 */
7846 	h->vaddr = NULL;
7847 	hpsa_disable_interrupt_mode(h);		/* pci_init 2 */
7848 	/*
7849 	 * call pci_disable_device before pci_release_regions per
7850 	 * Documentation/driver-api/pci/pci.rst
7851 	 */
7852 	pci_disable_device(h->pdev);		/* pci_init 1 */
7853 	pci_release_regions(h->pdev);		/* pci_init 2 */
7854 }
7855 
7856 /* several items must be freed later */
7857 static int hpsa_pci_init(struct ctlr_info *h)
7858 {
7859 	int prod_index, err;
7860 	bool legacy_board;
7861 
7862 	prod_index = hpsa_lookup_board_id(h->pdev, &h->board_id, &legacy_board);
7863 	if (prod_index < 0)
7864 		return prod_index;
7865 	h->product_name = products[prod_index].product_name;
7866 	h->access = *(products[prod_index].access);
7867 	h->legacy_board = legacy_board;
7868 	pci_disable_link_state(h->pdev, PCIE_LINK_STATE_L0S |
7869 			       PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM);
7870 
7871 	err = pci_enable_device(h->pdev);
7872 	if (err) {
7873 		dev_err(&h->pdev->dev, "failed to enable PCI device\n");
7874 		pci_disable_device(h->pdev);
7875 		return err;
7876 	}
7877 
7878 	err = pci_request_regions(h->pdev, HPSA);
7879 	if (err) {
7880 		dev_err(&h->pdev->dev,
7881 			"failed to obtain PCI resources\n");
7882 		pci_disable_device(h->pdev);
7883 		return err;
7884 	}
7885 
7886 	pci_set_master(h->pdev);
7887 
7888 	err = hpsa_interrupt_mode(h);
7889 	if (err)
7890 		goto clean1;
7891 
7892 	/* setup mapping between CPU and reply queue */
7893 	hpsa_setup_reply_map(h);
7894 
7895 	err = hpsa_pci_find_memory_BAR(h->pdev, &h->paddr);
7896 	if (err)
7897 		goto clean2;	/* intmode+region, pci */
7898 	h->vaddr = remap_pci_mem(h->paddr, 0x250);
7899 	if (!h->vaddr) {
7900 		dev_err(&h->pdev->dev, "failed to remap PCI mem\n");
7901 		err = -ENOMEM;
7902 		goto clean2;	/* intmode+region, pci */
7903 	}
7904 	err = hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY);
7905 	if (err)
7906 		goto clean3;	/* vaddr, intmode+region, pci */
7907 	err = hpsa_find_cfgtables(h);
7908 	if (err)
7909 		goto clean3;	/* vaddr, intmode+region, pci */
7910 	hpsa_find_board_params(h);
7911 
7912 	if (!hpsa_CISS_signature_present(h)) {
7913 		err = -ENODEV;
7914 		goto clean4;	/* cfgtables, vaddr, intmode+region, pci */
7915 	}
7916 	hpsa_set_driver_support_bits(h);
7917 	hpsa_p600_dma_prefetch_quirk(h);
7918 	err = hpsa_enter_simple_mode(h);
7919 	if (err)
7920 		goto clean4;	/* cfgtables, vaddr, intmode+region, pci */
7921 	return 0;
7922 
7923 clean4:	/* cfgtables, vaddr, intmode+region, pci */
7924 	hpsa_free_cfgtables(h);
7925 clean3:	/* vaddr, intmode+region, pci */
7926 	iounmap(h->vaddr);
7927 	h->vaddr = NULL;
7928 clean2:	/* intmode+region, pci */
7929 	hpsa_disable_interrupt_mode(h);
7930 clean1:
7931 	/*
7932 	 * call pci_disable_device before pci_release_regions per
7933 	 * Documentation/driver-api/pci/pci.rst
7934 	 */
7935 	pci_disable_device(h->pdev);
7936 	pci_release_regions(h->pdev);
7937 	return err;
7938 }
7939 
7940 static void hpsa_hba_inquiry(struct ctlr_info *h)
7941 {
7942 	int rc;
7943 
7944 #define HBA_INQUIRY_BYTE_COUNT 64
7945 	h->hba_inquiry_data = kmalloc(HBA_INQUIRY_BYTE_COUNT, GFP_KERNEL);
7946 	if (!h->hba_inquiry_data)
7947 		return;
7948 	rc = hpsa_scsi_do_inquiry(h, RAID_CTLR_LUNID, 0,
7949 		h->hba_inquiry_data, HBA_INQUIRY_BYTE_COUNT);
7950 	if (rc != 0) {
7951 		kfree(h->hba_inquiry_data);
7952 		h->hba_inquiry_data = NULL;
7953 	}
7954 }
7955 
7956 static int hpsa_init_reset_devices(struct pci_dev *pdev, u32 board_id)
7957 {
7958 	int rc, i;
7959 	void __iomem *vaddr;
7960 
7961 	if (!reset_devices)
7962 		return 0;
7963 
7964 	/* kdump kernel is loading, we don't know in which state is
7965 	 * the pci interface. The dev->enable_cnt is equal zero
7966 	 * so we call enable+disable, wait a while and switch it on.
7967 	 */
7968 	rc = pci_enable_device(pdev);
7969 	if (rc) {
7970 		dev_warn(&pdev->dev, "Failed to enable PCI device\n");
7971 		return -ENODEV;
7972 	}
7973 	pci_disable_device(pdev);
7974 	msleep(260);			/* a randomly chosen number */
7975 	rc = pci_enable_device(pdev);
7976 	if (rc) {
7977 		dev_warn(&pdev->dev, "failed to enable device.\n");
7978 		return -ENODEV;
7979 	}
7980 
7981 	pci_set_master(pdev);
7982 
7983 	vaddr = pci_ioremap_bar(pdev, 0);
7984 	if (vaddr == NULL) {
7985 		rc = -ENOMEM;
7986 		goto out_disable;
7987 	}
7988 	writel(SA5_INTR_OFF, vaddr + SA5_REPLY_INTR_MASK_OFFSET);
7989 	iounmap(vaddr);
7990 
7991 	/* Reset the controller with a PCI power-cycle or via doorbell */
7992 	rc = hpsa_kdump_hard_reset_controller(pdev, board_id);
7993 
7994 	/* -ENOTSUPP here means we cannot reset the controller
7995 	 * but it's already (and still) up and running in
7996 	 * "performant mode".  Or, it might be 640x, which can't reset
7997 	 * due to concerns about shared bbwc between 6402/6404 pair.
7998 	 */
7999 	if (rc)
8000 		goto out_disable;
8001 
8002 	/* Now try to get the controller to respond to a no-op */
8003 	dev_info(&pdev->dev, "Waiting for controller to respond to no-op\n");
8004 	for (i = 0; i < HPSA_POST_RESET_NOOP_RETRIES; i++) {
8005 		if (hpsa_noop(pdev) == 0)
8006 			break;
8007 		else
8008 			dev_warn(&pdev->dev, "no-op failed%s\n",
8009 					(i < 11 ? "; re-trying" : ""));
8010 	}
8011 
8012 out_disable:
8013 
8014 	pci_disable_device(pdev);
8015 	return rc;
8016 }
8017 
8018 static void hpsa_free_cmd_pool(struct ctlr_info *h)
8019 {
8020 	bitmap_free(h->cmd_pool_bits);
8021 	h->cmd_pool_bits = NULL;
8022 	if (h->cmd_pool) {
8023 		dma_free_coherent(&h->pdev->dev,
8024 				h->nr_cmds * sizeof(struct CommandList),
8025 				h->cmd_pool,
8026 				h->cmd_pool_dhandle);
8027 		h->cmd_pool = NULL;
8028 		h->cmd_pool_dhandle = 0;
8029 	}
8030 	if (h->errinfo_pool) {
8031 		dma_free_coherent(&h->pdev->dev,
8032 				h->nr_cmds * sizeof(struct ErrorInfo),
8033 				h->errinfo_pool,
8034 				h->errinfo_pool_dhandle);
8035 		h->errinfo_pool = NULL;
8036 		h->errinfo_pool_dhandle = 0;
8037 	}
8038 }
8039 
8040 static int hpsa_alloc_cmd_pool(struct ctlr_info *h)
8041 {
8042 	h->cmd_pool_bits = bitmap_zalloc(h->nr_cmds, GFP_KERNEL);
8043 	h->cmd_pool = dma_alloc_coherent(&h->pdev->dev,
8044 		    h->nr_cmds * sizeof(*h->cmd_pool),
8045 		    &h->cmd_pool_dhandle, GFP_KERNEL);
8046 	h->errinfo_pool = dma_alloc_coherent(&h->pdev->dev,
8047 		    h->nr_cmds * sizeof(*h->errinfo_pool),
8048 		    &h->errinfo_pool_dhandle, GFP_KERNEL);
8049 	if ((h->cmd_pool_bits == NULL)
8050 	    || (h->cmd_pool == NULL)
8051 	    || (h->errinfo_pool == NULL)) {
8052 		dev_err(&h->pdev->dev, "out of memory in %s", __func__);
8053 		goto clean_up;
8054 	}
8055 	hpsa_preinitialize_commands(h);
8056 	return 0;
8057 clean_up:
8058 	hpsa_free_cmd_pool(h);
8059 	return -ENOMEM;
8060 }
8061 
8062 /* clear affinity hints and free MSI-X, MSI, or legacy INTx vectors */
8063 static void hpsa_free_irqs(struct ctlr_info *h)
8064 {
8065 	int i;
8066 	int irq_vector = 0;
8067 
8068 	if (hpsa_simple_mode)
8069 		irq_vector = h->intr_mode;
8070 
8071 	if (!h->msix_vectors || h->intr_mode != PERF_MODE_INT) {
8072 		/* Single reply queue, only one irq to free */
8073 		free_irq(pci_irq_vector(h->pdev, irq_vector),
8074 				&h->q[h->intr_mode]);
8075 		h->q[h->intr_mode] = 0;
8076 		return;
8077 	}
8078 
8079 	for (i = 0; i < h->msix_vectors; i++) {
8080 		free_irq(pci_irq_vector(h->pdev, i), &h->q[i]);
8081 		h->q[i] = 0;
8082 	}
8083 	for (; i < MAX_REPLY_QUEUES; i++)
8084 		h->q[i] = 0;
8085 }
8086 
8087 /* returns 0 on success; cleans up and returns -Enn on error */
8088 static int hpsa_request_irqs(struct ctlr_info *h,
8089 	irqreturn_t (*msixhandler)(int, void *),
8090 	irqreturn_t (*intxhandler)(int, void *))
8091 {
8092 	int rc, i;
8093 	int irq_vector = 0;
8094 
8095 	if (hpsa_simple_mode)
8096 		irq_vector = h->intr_mode;
8097 
8098 	/*
8099 	 * initialize h->q[x] = x so that interrupt handlers know which
8100 	 * queue to process.
8101 	 */
8102 	for (i = 0; i < MAX_REPLY_QUEUES; i++)
8103 		h->q[i] = (u8) i;
8104 
8105 	if (h->intr_mode == PERF_MODE_INT && h->msix_vectors > 0) {
8106 		/* If performant mode and MSI-X, use multiple reply queues */
8107 		for (i = 0; i < h->msix_vectors; i++) {
8108 			sprintf(h->intrname[i], "%s-msix%d", h->devname, i);
8109 			rc = request_irq(pci_irq_vector(h->pdev, i), msixhandler,
8110 					0, h->intrname[i],
8111 					&h->q[i]);
8112 			if (rc) {
8113 				int j;
8114 
8115 				dev_err(&h->pdev->dev,
8116 					"failed to get irq %d for %s\n",
8117 				       pci_irq_vector(h->pdev, i), h->devname);
8118 				for (j = 0; j < i; j++) {
8119 					free_irq(pci_irq_vector(h->pdev, j), &h->q[j]);
8120 					h->q[j] = 0;
8121 				}
8122 				for (; j < MAX_REPLY_QUEUES; j++)
8123 					h->q[j] = 0;
8124 				return rc;
8125 			}
8126 		}
8127 	} else {
8128 		/* Use single reply pool */
8129 		if (h->msix_vectors > 0 || h->pdev->msi_enabled) {
8130 			sprintf(h->intrname[0], "%s-msi%s", h->devname,
8131 				h->msix_vectors ? "x" : "");
8132 			rc = request_irq(pci_irq_vector(h->pdev, irq_vector),
8133 				msixhandler, 0,
8134 				h->intrname[0],
8135 				&h->q[h->intr_mode]);
8136 		} else {
8137 			sprintf(h->intrname[h->intr_mode],
8138 				"%s-intx", h->devname);
8139 			rc = request_irq(pci_irq_vector(h->pdev, irq_vector),
8140 				intxhandler, IRQF_SHARED,
8141 				h->intrname[0],
8142 				&h->q[h->intr_mode]);
8143 		}
8144 	}
8145 	if (rc) {
8146 		dev_err(&h->pdev->dev, "failed to get irq %d for %s\n",
8147 		       pci_irq_vector(h->pdev, irq_vector), h->devname);
8148 		hpsa_free_irqs(h);
8149 		return -ENODEV;
8150 	}
8151 	return 0;
8152 }
8153 
8154 static int hpsa_kdump_soft_reset(struct ctlr_info *h)
8155 {
8156 	int rc;
8157 	hpsa_send_host_reset(h, HPSA_RESET_TYPE_CONTROLLER);
8158 
8159 	dev_info(&h->pdev->dev, "Waiting for board to soft reset.\n");
8160 	rc = hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_NOT_READY);
8161 	if (rc) {
8162 		dev_warn(&h->pdev->dev, "Soft reset had no effect.\n");
8163 		return rc;
8164 	}
8165 
8166 	dev_info(&h->pdev->dev, "Board reset, awaiting READY status.\n");
8167 	rc = hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY);
8168 	if (rc) {
8169 		dev_warn(&h->pdev->dev, "Board failed to become ready "
8170 			"after soft reset.\n");
8171 		return rc;
8172 	}
8173 
8174 	return 0;
8175 }
8176 
8177 static void hpsa_free_reply_queues(struct ctlr_info *h)
8178 {
8179 	int i;
8180 
8181 	for (i = 0; i < h->nreply_queues; i++) {
8182 		if (!h->reply_queue[i].head)
8183 			continue;
8184 		dma_free_coherent(&h->pdev->dev,
8185 					h->reply_queue_size,
8186 					h->reply_queue[i].head,
8187 					h->reply_queue[i].busaddr);
8188 		h->reply_queue[i].head = NULL;
8189 		h->reply_queue[i].busaddr = 0;
8190 	}
8191 	h->reply_queue_size = 0;
8192 }
8193 
8194 static void hpsa_undo_allocations_after_kdump_soft_reset(struct ctlr_info *h)
8195 {
8196 	hpsa_free_performant_mode(h);		/* init_one 7 */
8197 	hpsa_free_sg_chain_blocks(h);		/* init_one 6 */
8198 	hpsa_free_cmd_pool(h);			/* init_one 5 */
8199 	hpsa_free_irqs(h);			/* init_one 4 */
8200 	scsi_host_put(h->scsi_host);		/* init_one 3 */
8201 	h->scsi_host = NULL;			/* init_one 3 */
8202 	hpsa_free_pci_init(h);			/* init_one 2_5 */
8203 	free_percpu(h->lockup_detected);	/* init_one 2 */
8204 	h->lockup_detected = NULL;		/* init_one 2 */
8205 	if (h->resubmit_wq) {
8206 		destroy_workqueue(h->resubmit_wq);	/* init_one 1 */
8207 		h->resubmit_wq = NULL;
8208 	}
8209 	if (h->rescan_ctlr_wq) {
8210 		destroy_workqueue(h->rescan_ctlr_wq);
8211 		h->rescan_ctlr_wq = NULL;
8212 	}
8213 	if (h->monitor_ctlr_wq) {
8214 		destroy_workqueue(h->monitor_ctlr_wq);
8215 		h->monitor_ctlr_wq = NULL;
8216 	}
8217 
8218 	kfree(h);				/* init_one 1 */
8219 }
8220 
8221 /* Called when controller lockup detected. */
8222 static void fail_all_outstanding_cmds(struct ctlr_info *h)
8223 {
8224 	int i, refcount;
8225 	struct CommandList *c;
8226 	int failcount = 0;
8227 
8228 	flush_workqueue(h->resubmit_wq); /* ensure all cmds are fully built */
8229 	for (i = 0; i < h->nr_cmds; i++) {
8230 		c = h->cmd_pool + i;
8231 		refcount = atomic_inc_return(&c->refcount);
8232 		if (refcount > 1) {
8233 			c->err_info->CommandStatus = CMD_CTLR_LOCKUP;
8234 			finish_cmd(c);
8235 			atomic_dec(&h->commands_outstanding);
8236 			failcount++;
8237 		}
8238 		cmd_free(h, c);
8239 	}
8240 	dev_warn(&h->pdev->dev,
8241 		"failed %d commands in fail_all\n", failcount);
8242 }
8243 
8244 static void set_lockup_detected_for_all_cpus(struct ctlr_info *h, u32 value)
8245 {
8246 	int cpu;
8247 
8248 	for_each_online_cpu(cpu) {
8249 		u32 *lockup_detected;
8250 		lockup_detected = per_cpu_ptr(h->lockup_detected, cpu);
8251 		*lockup_detected = value;
8252 	}
8253 	wmb(); /* be sure the per-cpu variables are out to memory */
8254 }
8255 
8256 static void controller_lockup_detected(struct ctlr_info *h)
8257 {
8258 	unsigned long flags;
8259 	u32 lockup_detected;
8260 
8261 	h->access.set_intr_mask(h, HPSA_INTR_OFF);
8262 	spin_lock_irqsave(&h->lock, flags);
8263 	lockup_detected = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
8264 	if (!lockup_detected) {
8265 		/* no heartbeat, but controller gave us a zero. */
8266 		dev_warn(&h->pdev->dev,
8267 			"lockup detected after %d but scratchpad register is zero\n",
8268 			h->heartbeat_sample_interval / HZ);
8269 		lockup_detected = 0xffffffff;
8270 	}
8271 	set_lockup_detected_for_all_cpus(h, lockup_detected);
8272 	spin_unlock_irqrestore(&h->lock, flags);
8273 	dev_warn(&h->pdev->dev, "Controller lockup detected: 0x%08x after %d\n",
8274 			lockup_detected, h->heartbeat_sample_interval / HZ);
8275 	if (lockup_detected == 0xffff0000) {
8276 		dev_warn(&h->pdev->dev, "Telling controller to do a CHKPT\n");
8277 		writel(DOORBELL_GENERATE_CHKPT, h->vaddr + SA5_DOORBELL);
8278 	}
8279 	pci_disable_device(h->pdev);
8280 	fail_all_outstanding_cmds(h);
8281 }
8282 
8283 static int detect_controller_lockup(struct ctlr_info *h)
8284 {
8285 	u64 now;
8286 	u32 heartbeat;
8287 	unsigned long flags;
8288 
8289 	now = get_jiffies_64();
8290 	/* If we've received an interrupt recently, we're ok. */
8291 	if (time_after64(h->last_intr_timestamp +
8292 				(h->heartbeat_sample_interval), now))
8293 		return false;
8294 
8295 	/*
8296 	 * If we've already checked the heartbeat recently, we're ok.
8297 	 * This could happen if someone sends us a signal. We
8298 	 * otherwise don't care about signals in this thread.
8299 	 */
8300 	if (time_after64(h->last_heartbeat_timestamp +
8301 				(h->heartbeat_sample_interval), now))
8302 		return false;
8303 
8304 	/* If heartbeat has not changed since we last looked, we're not ok. */
8305 	spin_lock_irqsave(&h->lock, flags);
8306 	heartbeat = readl(&h->cfgtable->HeartBeat);
8307 	spin_unlock_irqrestore(&h->lock, flags);
8308 	if (h->last_heartbeat == heartbeat) {
8309 		controller_lockup_detected(h);
8310 		return true;
8311 	}
8312 
8313 	/* We're ok. */
8314 	h->last_heartbeat = heartbeat;
8315 	h->last_heartbeat_timestamp = now;
8316 	return false;
8317 }
8318 
8319 /*
8320  * Set ioaccel status for all ioaccel volumes.
8321  *
8322  * Called from monitor controller worker (hpsa_event_monitor_worker)
8323  *
8324  * A Volume (or Volumes that comprise an Array set) may be undergoing a
8325  * transformation, so we will be turning off ioaccel for all volumes that
8326  * make up the Array.
8327  */
8328 static void hpsa_set_ioaccel_status(struct ctlr_info *h)
8329 {
8330 	int rc;
8331 	int i;
8332 	u8 ioaccel_status;
8333 	unsigned char *buf;
8334 	struct hpsa_scsi_dev_t *device;
8335 
8336 	if (!h)
8337 		return;
8338 
8339 	buf = kmalloc(64, GFP_KERNEL);
8340 	if (!buf)
8341 		return;
8342 
8343 	/*
8344 	 * Run through current device list used during I/O requests.
8345 	 */
8346 	for (i = 0; i < h->ndevices; i++) {
8347 		int offload_to_be_enabled = 0;
8348 		int offload_config = 0;
8349 
8350 		device = h->dev[i];
8351 
8352 		if (!device)
8353 			continue;
8354 		if (!hpsa_vpd_page_supported(h, device->scsi3addr,
8355 						HPSA_VPD_LV_IOACCEL_STATUS))
8356 			continue;
8357 
8358 		memset(buf, 0, 64);
8359 
8360 		rc = hpsa_scsi_do_inquiry(h, device->scsi3addr,
8361 					VPD_PAGE | HPSA_VPD_LV_IOACCEL_STATUS,
8362 					buf, 64);
8363 		if (rc != 0)
8364 			continue;
8365 
8366 		ioaccel_status = buf[IOACCEL_STATUS_BYTE];
8367 
8368 		/*
8369 		 * Check if offload is still configured on
8370 		 */
8371 		offload_config =
8372 				!!(ioaccel_status & OFFLOAD_CONFIGURED_BIT);
8373 		/*
8374 		 * If offload is configured on, check to see if ioaccel
8375 		 * needs to be enabled.
8376 		 */
8377 		if (offload_config)
8378 			offload_to_be_enabled =
8379 				!!(ioaccel_status & OFFLOAD_ENABLED_BIT);
8380 
8381 		/*
8382 		 * If ioaccel is to be re-enabled, re-enable later during the
8383 		 * scan operation so the driver can get a fresh raidmap
8384 		 * before turning ioaccel back on.
8385 		 */
8386 		if (offload_to_be_enabled)
8387 			continue;
8388 
8389 		/*
8390 		 * Immediately turn off ioaccel for any volume the
8391 		 * controller tells us to. Some of the reasons could be:
8392 		 *    transformation - change to the LVs of an Array.
8393 		 *    degraded volume - component failure
8394 		 */
8395 		hpsa_turn_off_ioaccel_for_device(device);
8396 	}
8397 
8398 	kfree(buf);
8399 }
8400 
8401 static void hpsa_ack_ctlr_events(struct ctlr_info *h)
8402 {
8403 	char *event_type;
8404 
8405 	if (!(h->fw_support & MISC_FW_EVENT_NOTIFY))
8406 		return;
8407 
8408 	/* Ask the controller to clear the events we're handling. */
8409 	if ((h->transMethod & (CFGTBL_Trans_io_accel1
8410 			| CFGTBL_Trans_io_accel2)) &&
8411 		(h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_STATE_CHANGE ||
8412 		 h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_CONFIG_CHANGE)) {
8413 
8414 		if (h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_STATE_CHANGE)
8415 			event_type = "state change";
8416 		if (h->events & HPSA_EVENT_NOTIFY_ACCEL_IO_PATH_CONFIG_CHANGE)
8417 			event_type = "configuration change";
8418 		/* Stop sending new RAID offload reqs via the IO accelerator */
8419 		scsi_block_requests(h->scsi_host);
8420 		hpsa_set_ioaccel_status(h);
8421 		hpsa_drain_accel_commands(h);
8422 		/* Set 'accelerator path config change' bit */
8423 		dev_warn(&h->pdev->dev,
8424 			"Acknowledging event: 0x%08x (HP SSD Smart Path %s)\n",
8425 			h->events, event_type);
8426 		writel(h->events, &(h->cfgtable->clear_event_notify));
8427 		/* Set the "clear event notify field update" bit 6 */
8428 		writel(DOORBELL_CLEAR_EVENTS, h->vaddr + SA5_DOORBELL);
8429 		/* Wait until ctlr clears 'clear event notify field', bit 6 */
8430 		hpsa_wait_for_clear_event_notify_ack(h);
8431 		scsi_unblock_requests(h->scsi_host);
8432 	} else {
8433 		/* Acknowledge controller notification events. */
8434 		writel(h->events, &(h->cfgtable->clear_event_notify));
8435 		writel(DOORBELL_CLEAR_EVENTS, h->vaddr + SA5_DOORBELL);
8436 		hpsa_wait_for_clear_event_notify_ack(h);
8437 	}
8438 	return;
8439 }
8440 
8441 /* Check a register on the controller to see if there are configuration
8442  * changes (added/changed/removed logical drives, etc.) which mean that
8443  * we should rescan the controller for devices.
8444  * Also check flag for driver-initiated rescan.
8445  */
8446 static int hpsa_ctlr_needs_rescan(struct ctlr_info *h)
8447 {
8448 	if (h->drv_req_rescan) {
8449 		h->drv_req_rescan = 0;
8450 		return 1;
8451 	}
8452 
8453 	if (!(h->fw_support & MISC_FW_EVENT_NOTIFY))
8454 		return 0;
8455 
8456 	h->events = readl(&(h->cfgtable->event_notify));
8457 	return h->events & RESCAN_REQUIRED_EVENT_BITS;
8458 }
8459 
8460 /*
8461  * Check if any of the offline devices have become ready
8462  */
8463 static int hpsa_offline_devices_ready(struct ctlr_info *h)
8464 {
8465 	unsigned long flags;
8466 	struct offline_device_entry *d;
8467 	struct list_head *this, *tmp;
8468 
8469 	spin_lock_irqsave(&h->offline_device_lock, flags);
8470 	list_for_each_safe(this, tmp, &h->offline_device_list) {
8471 		d = list_entry(this, struct offline_device_entry,
8472 				offline_list);
8473 		spin_unlock_irqrestore(&h->offline_device_lock, flags);
8474 		if (!hpsa_volume_offline(h, d->scsi3addr)) {
8475 			spin_lock_irqsave(&h->offline_device_lock, flags);
8476 			list_del(&d->offline_list);
8477 			spin_unlock_irqrestore(&h->offline_device_lock, flags);
8478 			return 1;
8479 		}
8480 		spin_lock_irqsave(&h->offline_device_lock, flags);
8481 	}
8482 	spin_unlock_irqrestore(&h->offline_device_lock, flags);
8483 	return 0;
8484 }
8485 
8486 static int hpsa_luns_changed(struct ctlr_info *h)
8487 {
8488 	int rc = 1; /* assume there are changes */
8489 	struct ReportLUNdata *logdev = NULL;
8490 
8491 	/* if we can't find out if lun data has changed,
8492 	 * assume that it has.
8493 	 */
8494 
8495 	if (!h->lastlogicals)
8496 		return rc;
8497 
8498 	logdev = kzalloc_obj(*logdev);
8499 	if (!logdev)
8500 		return rc;
8501 
8502 	if (hpsa_scsi_do_report_luns(h, 1, logdev, sizeof(*logdev), 0)) {
8503 		dev_warn(&h->pdev->dev,
8504 			"report luns failed, can't track lun changes.\n");
8505 		goto out;
8506 	}
8507 	if (memcmp(logdev, h->lastlogicals, sizeof(*logdev))) {
8508 		dev_info(&h->pdev->dev,
8509 			"Lun changes detected.\n");
8510 		memcpy(h->lastlogicals, logdev, sizeof(*logdev));
8511 		goto out;
8512 	} else
8513 		rc = 0; /* no changes detected. */
8514 out:
8515 	kfree(logdev);
8516 	return rc;
8517 }
8518 
8519 static void hpsa_perform_rescan(struct ctlr_info *h)
8520 {
8521 	struct Scsi_Host *sh = NULL;
8522 	unsigned long flags;
8523 
8524 	/*
8525 	 * Do the scan after the reset
8526 	 */
8527 	spin_lock_irqsave(&h->reset_lock, flags);
8528 	if (h->reset_in_progress) {
8529 		h->drv_req_rescan = 1;
8530 		spin_unlock_irqrestore(&h->reset_lock, flags);
8531 		return;
8532 	}
8533 	spin_unlock_irqrestore(&h->reset_lock, flags);
8534 
8535 	sh = scsi_host_get(h->scsi_host);
8536 	if (sh != NULL) {
8537 		hpsa_scan_start(sh);
8538 		scsi_host_put(sh);
8539 		h->drv_req_rescan = 0;
8540 	}
8541 }
8542 
8543 /*
8544  * watch for controller events
8545  */
8546 static void hpsa_event_monitor_worker(struct work_struct *work)
8547 {
8548 	struct ctlr_info *h = container_of(to_delayed_work(work),
8549 					struct ctlr_info, event_monitor_work);
8550 	unsigned long flags;
8551 
8552 	spin_lock_irqsave(&h->lock, flags);
8553 	if (h->remove_in_progress) {
8554 		spin_unlock_irqrestore(&h->lock, flags);
8555 		return;
8556 	}
8557 	spin_unlock_irqrestore(&h->lock, flags);
8558 
8559 	if (hpsa_ctlr_needs_rescan(h)) {
8560 		hpsa_ack_ctlr_events(h);
8561 		hpsa_perform_rescan(h);
8562 	}
8563 
8564 	spin_lock_irqsave(&h->lock, flags);
8565 	if (!h->remove_in_progress)
8566 		queue_delayed_work(h->monitor_ctlr_wq, &h->event_monitor_work,
8567 				HPSA_EVENT_MONITOR_INTERVAL);
8568 	spin_unlock_irqrestore(&h->lock, flags);
8569 }
8570 
8571 static void hpsa_rescan_ctlr_worker(struct work_struct *work)
8572 {
8573 	unsigned long flags;
8574 	struct ctlr_info *h = container_of(to_delayed_work(work),
8575 					struct ctlr_info, rescan_ctlr_work);
8576 
8577 	spin_lock_irqsave(&h->lock, flags);
8578 	if (h->remove_in_progress) {
8579 		spin_unlock_irqrestore(&h->lock, flags);
8580 		return;
8581 	}
8582 	spin_unlock_irqrestore(&h->lock, flags);
8583 
8584 	if (h->drv_req_rescan || hpsa_offline_devices_ready(h)) {
8585 		hpsa_perform_rescan(h);
8586 	} else if (h->discovery_polling) {
8587 		if (hpsa_luns_changed(h)) {
8588 			dev_info(&h->pdev->dev,
8589 				"driver discovery polling rescan.\n");
8590 			hpsa_perform_rescan(h);
8591 		}
8592 	}
8593 	spin_lock_irqsave(&h->lock, flags);
8594 	if (!h->remove_in_progress)
8595 		queue_delayed_work(h->rescan_ctlr_wq, &h->rescan_ctlr_work,
8596 				h->heartbeat_sample_interval);
8597 	spin_unlock_irqrestore(&h->lock, flags);
8598 }
8599 
8600 static void hpsa_monitor_ctlr_worker(struct work_struct *work)
8601 {
8602 	unsigned long flags;
8603 	struct ctlr_info *h = container_of(to_delayed_work(work),
8604 					struct ctlr_info, monitor_ctlr_work);
8605 
8606 	detect_controller_lockup(h);
8607 	if (lockup_detected(h))
8608 		return;
8609 
8610 	spin_lock_irqsave(&h->lock, flags);
8611 	if (!h->remove_in_progress)
8612 		queue_delayed_work(h->monitor_ctlr_wq, &h->monitor_ctlr_work,
8613 				h->heartbeat_sample_interval);
8614 	spin_unlock_irqrestore(&h->lock, flags);
8615 }
8616 
8617 static struct workqueue_struct *hpsa_create_controller_wq(struct ctlr_info *h,
8618 						char *name)
8619 {
8620 	struct workqueue_struct *wq = NULL;
8621 
8622 	wq = alloc_ordered_workqueue("%s_%d_hpsa", 0, name, h->ctlr);
8623 	if (!wq)
8624 		dev_err(&h->pdev->dev, "failed to create %s workqueue\n", name);
8625 
8626 	return wq;
8627 }
8628 
8629 static void hpda_free_ctlr_info(struct ctlr_info *h)
8630 {
8631 	kfree(h->reply_map);
8632 	kfree(h);
8633 }
8634 
8635 static struct ctlr_info *hpda_alloc_ctlr_info(void)
8636 {
8637 	struct ctlr_info *h;
8638 
8639 	h = kzalloc_obj(*h);
8640 	if (!h)
8641 		return NULL;
8642 
8643 	h->reply_map = kcalloc(nr_cpu_ids, sizeof(*h->reply_map), GFP_KERNEL);
8644 	if (!h->reply_map) {
8645 		kfree(h);
8646 		return NULL;
8647 	}
8648 	return h;
8649 }
8650 
8651 static int hpsa_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
8652 {
8653 	int rc;
8654 	struct ctlr_info *h;
8655 	int try_soft_reset = 0;
8656 	unsigned long flags;
8657 	u32 board_id;
8658 
8659 	if (number_of_controllers == 0)
8660 		printk(KERN_INFO DRIVER_NAME "\n");
8661 
8662 	rc = hpsa_lookup_board_id(pdev, &board_id, NULL);
8663 	if (rc < 0) {
8664 		dev_warn(&pdev->dev, "Board ID not found\n");
8665 		return rc;
8666 	}
8667 
8668 	rc = hpsa_init_reset_devices(pdev, board_id);
8669 	if (rc) {
8670 		if (rc != -ENOTSUPP)
8671 			return rc;
8672 		/* If the reset fails in a particular way (it has no way to do
8673 		 * a proper hard reset, so returns -ENOTSUPP) we can try to do
8674 		 * a soft reset once we get the controller configured up to the
8675 		 * point that it can accept a command.
8676 		 */
8677 		try_soft_reset = 1;
8678 		rc = 0;
8679 	}
8680 
8681 reinit_after_soft_reset:
8682 
8683 	/* Command structures must be aligned on a 32-byte boundary because
8684 	 * the 5 lower bits of the address are used by the hardware. and by
8685 	 * the driver.  See comments in hpsa.h for more info.
8686 	 */
8687 	BUILD_BUG_ON(sizeof(struct CommandList) % COMMANDLIST_ALIGNMENT);
8688 	h = hpda_alloc_ctlr_info();
8689 	if (!h) {
8690 		dev_err(&pdev->dev, "Failed to allocate controller head\n");
8691 		return -ENOMEM;
8692 	}
8693 
8694 	h->pdev = pdev;
8695 
8696 	h->intr_mode = hpsa_simple_mode ? SIMPLE_MODE_INT : PERF_MODE_INT;
8697 	INIT_LIST_HEAD(&h->offline_device_list);
8698 	spin_lock_init(&h->lock);
8699 	spin_lock_init(&h->offline_device_lock);
8700 	spin_lock_init(&h->scan_lock);
8701 	spin_lock_init(&h->reset_lock);
8702 	atomic_set(&h->passthru_cmds_avail, HPSA_MAX_CONCURRENT_PASSTHRUS);
8703 
8704 	/* Allocate and clear per-cpu variable lockup_detected */
8705 	h->lockup_detected = alloc_percpu(u32);
8706 	if (!h->lockup_detected) {
8707 		dev_err(&h->pdev->dev, "Failed to allocate lockup detector\n");
8708 		rc = -ENOMEM;
8709 		goto clean1;	/* aer/h */
8710 	}
8711 	set_lockup_detected_for_all_cpus(h, 0);
8712 
8713 	rc = hpsa_pci_init(h);
8714 	if (rc)
8715 		goto clean2;	/* lu, aer/h */
8716 
8717 	/* relies on h-> settings made by hpsa_pci_init, including
8718 	 * interrupt_mode h->intr */
8719 	rc = hpsa_scsi_host_alloc(h);
8720 	if (rc)
8721 		goto clean2_5;	/* pci, lu, aer/h */
8722 
8723 	sprintf(h->devname, HPSA "%d", h->scsi_host->host_no);
8724 	h->ctlr = number_of_controllers;
8725 	number_of_controllers++;
8726 
8727 	/* configure PCI DMA stuff */
8728 	rc = dma_set_mask(&pdev->dev, DMA_BIT_MASK(64));
8729 	if (rc != 0) {
8730 		rc = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
8731 		if (rc != 0) {
8732 			dev_err(&pdev->dev, "no suitable DMA available\n");
8733 			goto clean3;	/* shost, pci, lu, aer/h */
8734 		}
8735 	}
8736 
8737 	/* make sure the board interrupts are off */
8738 	h->access.set_intr_mask(h, HPSA_INTR_OFF);
8739 
8740 	rc = hpsa_request_irqs(h, do_hpsa_intr_msi, do_hpsa_intr_intx);
8741 	if (rc)
8742 		goto clean3;	/* shost, pci, lu, aer/h */
8743 	rc = hpsa_alloc_cmd_pool(h);
8744 	if (rc)
8745 		goto clean4;	/* irq, shost, pci, lu, aer/h */
8746 	rc = hpsa_alloc_sg_chain_blocks(h);
8747 	if (rc)
8748 		goto clean5;	/* cmd, irq, shost, pci, lu, aer/h */
8749 	init_waitqueue_head(&h->scan_wait_queue);
8750 	init_waitqueue_head(&h->event_sync_wait_queue);
8751 	mutex_init(&h->reset_mutex);
8752 	h->scan_finished = 1; /* no scan currently in progress */
8753 	h->scan_waiting = 0;
8754 
8755 	pci_set_drvdata(pdev, h);
8756 	h->ndevices = 0;
8757 
8758 	spin_lock_init(&h->devlock);
8759 	rc = hpsa_put_ctlr_into_performant_mode(h);
8760 	if (rc)
8761 		goto clean6; /* sg, cmd, irq, shost, pci, lu, aer/h */
8762 
8763 	/* create the resubmit workqueue */
8764 	h->rescan_ctlr_wq = hpsa_create_controller_wq(h, "rescan");
8765 	if (!h->rescan_ctlr_wq) {
8766 		rc = -ENOMEM;
8767 		goto clean7;
8768 	}
8769 
8770 	h->resubmit_wq = hpsa_create_controller_wq(h, "resubmit");
8771 	if (!h->resubmit_wq) {
8772 		rc = -ENOMEM;
8773 		goto clean7;	/* aer/h */
8774 	}
8775 
8776 	h->monitor_ctlr_wq = hpsa_create_controller_wq(h, "monitor");
8777 	if (!h->monitor_ctlr_wq) {
8778 		rc = -ENOMEM;
8779 		goto clean7;
8780 	}
8781 
8782 	/*
8783 	 * At this point, the controller is ready to take commands.
8784 	 * Now, if reset_devices and the hard reset didn't work, try
8785 	 * the soft reset and see if that works.
8786 	 */
8787 	if (try_soft_reset) {
8788 
8789 		/* This is kind of gross.  We may or may not get a completion
8790 		 * from the soft reset command, and if we do, then the value
8791 		 * from the fifo may or may not be valid.  So, we wait 10 secs
8792 		 * after the reset throwing away any completions we get during
8793 		 * that time.  Unregister the interrupt handler and register
8794 		 * fake ones to scoop up any residual completions.
8795 		 */
8796 		spin_lock_irqsave(&h->lock, flags);
8797 		h->access.set_intr_mask(h, HPSA_INTR_OFF);
8798 		spin_unlock_irqrestore(&h->lock, flags);
8799 		hpsa_free_irqs(h);
8800 		rc = hpsa_request_irqs(h, hpsa_msix_discard_completions,
8801 					hpsa_intx_discard_completions);
8802 		if (rc) {
8803 			dev_warn(&h->pdev->dev,
8804 				"Failed to request_irq after soft reset.\n");
8805 			/*
8806 			 * cannot goto clean7 or free_irqs will be called
8807 			 * again. Instead, do its work
8808 			 */
8809 			hpsa_free_performant_mode(h);	/* clean7 */
8810 			hpsa_free_sg_chain_blocks(h);	/* clean6 */
8811 			hpsa_free_cmd_pool(h);		/* clean5 */
8812 			/*
8813 			 * skip hpsa_free_irqs(h) clean4 since that
8814 			 * was just called before request_irqs failed
8815 			 */
8816 			goto clean3;
8817 		}
8818 
8819 		rc = hpsa_kdump_soft_reset(h);
8820 		if (rc)
8821 			/* Neither hard nor soft reset worked, we're hosed. */
8822 			goto clean7;
8823 
8824 		dev_info(&h->pdev->dev, "Board READY.\n");
8825 		dev_info(&h->pdev->dev,
8826 			"Waiting for stale completions to drain.\n");
8827 		h->access.set_intr_mask(h, HPSA_INTR_ON);
8828 		msleep(10000);
8829 		h->access.set_intr_mask(h, HPSA_INTR_OFF);
8830 
8831 		rc = controller_reset_failed(h->cfgtable);
8832 		if (rc)
8833 			dev_info(&h->pdev->dev,
8834 				"Soft reset appears to have failed.\n");
8835 
8836 		/* since the controller's reset, we have to go back and re-init
8837 		 * everything.  Easiest to just forget what we've done and do it
8838 		 * all over again.
8839 		 */
8840 		hpsa_undo_allocations_after_kdump_soft_reset(h);
8841 		try_soft_reset = 0;
8842 		if (rc)
8843 			/* don't goto clean, we already unallocated */
8844 			return -ENODEV;
8845 
8846 		goto reinit_after_soft_reset;
8847 	}
8848 
8849 	/* Enable Accelerated IO path at driver layer */
8850 	h->acciopath_status = 1;
8851 	/* Disable discovery polling.*/
8852 	h->discovery_polling = 0;
8853 
8854 
8855 	/* Turn the interrupts on so we can service requests */
8856 	h->access.set_intr_mask(h, HPSA_INTR_ON);
8857 
8858 	hpsa_hba_inquiry(h);
8859 
8860 	h->lastlogicals = kzalloc_obj(*(h->lastlogicals));
8861 	if (!h->lastlogicals)
8862 		dev_info(&h->pdev->dev,
8863 			"Can't track change to report lun data\n");
8864 
8865 	/* hook into SCSI subsystem */
8866 	rc = hpsa_scsi_add_host(h);
8867 	if (rc)
8868 		goto clean8; /* lastlogicals, perf, sg, cmd, irq, shost, pci, lu, aer/h */
8869 
8870 	/* Monitor the controller for firmware lockups */
8871 	h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
8872 	INIT_DELAYED_WORK(&h->monitor_ctlr_work, hpsa_monitor_ctlr_worker);
8873 	schedule_delayed_work(&h->monitor_ctlr_work,
8874 				h->heartbeat_sample_interval);
8875 	INIT_DELAYED_WORK(&h->rescan_ctlr_work, hpsa_rescan_ctlr_worker);
8876 	queue_delayed_work(h->rescan_ctlr_wq, &h->rescan_ctlr_work,
8877 				h->heartbeat_sample_interval);
8878 	INIT_DELAYED_WORK(&h->event_monitor_work, hpsa_event_monitor_worker);
8879 	schedule_delayed_work(&h->event_monitor_work,
8880 				HPSA_EVENT_MONITOR_INTERVAL);
8881 	return 0;
8882 
8883 clean8: /* lastlogicals, perf, sg, cmd, irq, shost, pci, lu, aer/h */
8884 	kfree(h->lastlogicals);
8885 clean7: /* perf, sg, cmd, irq, shost, pci, lu, aer/h */
8886 	hpsa_free_performant_mode(h);
8887 	h->access.set_intr_mask(h, HPSA_INTR_OFF);
8888 clean6: /* sg, cmd, irq, pci, lockup, wq/aer/h */
8889 	hpsa_free_sg_chain_blocks(h);
8890 clean5: /* cmd, irq, shost, pci, lu, aer/h */
8891 	hpsa_free_cmd_pool(h);
8892 clean4: /* irq, shost, pci, lu, aer/h */
8893 	hpsa_free_irqs(h);
8894 clean3: /* shost, pci, lu, aer/h */
8895 	scsi_host_put(h->scsi_host);
8896 	h->scsi_host = NULL;
8897 clean2_5: /* pci, lu, aer/h */
8898 	hpsa_free_pci_init(h);
8899 clean2: /* lu, aer/h */
8900 	if (h->lockup_detected) {
8901 		free_percpu(h->lockup_detected);
8902 		h->lockup_detected = NULL;
8903 	}
8904 clean1:	/* wq/aer/h */
8905 	if (h->resubmit_wq) {
8906 		destroy_workqueue(h->resubmit_wq);
8907 		h->resubmit_wq = NULL;
8908 	}
8909 	if (h->rescan_ctlr_wq) {
8910 		destroy_workqueue(h->rescan_ctlr_wq);
8911 		h->rescan_ctlr_wq = NULL;
8912 	}
8913 	if (h->monitor_ctlr_wq) {
8914 		destroy_workqueue(h->monitor_ctlr_wq);
8915 		h->monitor_ctlr_wq = NULL;
8916 	}
8917 	hpda_free_ctlr_info(h);
8918 	return rc;
8919 }
8920 
8921 static void hpsa_flush_cache(struct ctlr_info *h)
8922 {
8923 	char *flush_buf;
8924 	struct CommandList *c;
8925 	int rc;
8926 
8927 	if (unlikely(lockup_detected(h)))
8928 		return;
8929 	flush_buf = kzalloc(4, GFP_KERNEL);
8930 	if (!flush_buf)
8931 		return;
8932 
8933 	c = cmd_alloc(h);
8934 
8935 	if (fill_cmd(c, HPSA_CACHE_FLUSH, h, flush_buf, 4, 0,
8936 		RAID_CTLR_LUNID, TYPE_CMD)) {
8937 		goto out;
8938 	}
8939 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_TO_DEVICE,
8940 			DEFAULT_TIMEOUT);
8941 	if (rc)
8942 		goto out;
8943 	if (c->err_info->CommandStatus != 0)
8944 out:
8945 		dev_warn(&h->pdev->dev,
8946 			"error flushing cache on controller\n");
8947 	cmd_free(h, c);
8948 	kfree(flush_buf);
8949 }
8950 
8951 /* Make controller gather fresh report lun data each time we
8952  * send down a report luns request
8953  */
8954 static void hpsa_disable_rld_caching(struct ctlr_info *h)
8955 {
8956 	u32 *options;
8957 	struct CommandList *c;
8958 	int rc;
8959 
8960 	/* Don't bother trying to set diag options if locked up */
8961 	if (unlikely(h->lockup_detected))
8962 		return;
8963 
8964 	options = kzalloc_obj(*options);
8965 	if (!options)
8966 		return;
8967 
8968 	c = cmd_alloc(h);
8969 
8970 	/* first, get the current diag options settings */
8971 	if (fill_cmd(c, BMIC_SENSE_DIAG_OPTIONS, h, options, 4, 0,
8972 		RAID_CTLR_LUNID, TYPE_CMD))
8973 		goto errout;
8974 
8975 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
8976 			NO_TIMEOUT);
8977 	if ((rc != 0) || (c->err_info->CommandStatus != 0))
8978 		goto errout;
8979 
8980 	/* Now, set the bit for disabling the RLD caching */
8981 	*options |= HPSA_DIAG_OPTS_DISABLE_RLD_CACHING;
8982 
8983 	if (fill_cmd(c, BMIC_SET_DIAG_OPTIONS, h, options, 4, 0,
8984 		RAID_CTLR_LUNID, TYPE_CMD))
8985 		goto errout;
8986 
8987 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_TO_DEVICE,
8988 			NO_TIMEOUT);
8989 	if ((rc != 0)  || (c->err_info->CommandStatus != 0))
8990 		goto errout;
8991 
8992 	/* Now verify that it got set: */
8993 	if (fill_cmd(c, BMIC_SENSE_DIAG_OPTIONS, h, options, 4, 0,
8994 		RAID_CTLR_LUNID, TYPE_CMD))
8995 		goto errout;
8996 
8997 	rc = hpsa_scsi_do_simple_cmd_with_retry(h, c, DMA_FROM_DEVICE,
8998 			NO_TIMEOUT);
8999 	if ((rc != 0)  || (c->err_info->CommandStatus != 0))
9000 		goto errout;
9001 
9002 	if (*options & HPSA_DIAG_OPTS_DISABLE_RLD_CACHING)
9003 		goto out;
9004 
9005 errout:
9006 	dev_err(&h->pdev->dev,
9007 			"Error: failed to disable report lun data caching.\n");
9008 out:
9009 	cmd_free(h, c);
9010 	kfree(options);
9011 }
9012 
9013 static void __hpsa_shutdown(struct pci_dev *pdev)
9014 {
9015 	struct ctlr_info *h;
9016 
9017 	h = pci_get_drvdata(pdev);
9018 	/* Turn board interrupts off  and send the flush cache command
9019 	 * sendcmd will turn off interrupt, and send the flush...
9020 	 * To write all data in the battery backed cache to disks
9021 	 */
9022 	hpsa_flush_cache(h);
9023 	h->access.set_intr_mask(h, HPSA_INTR_OFF);
9024 	hpsa_free_irqs(h);			/* init_one 4 */
9025 	hpsa_disable_interrupt_mode(h);		/* pci_init 2 */
9026 }
9027 
9028 static void hpsa_shutdown(struct pci_dev *pdev)
9029 {
9030 	__hpsa_shutdown(pdev);
9031 	pci_disable_device(pdev);
9032 }
9033 
9034 static void hpsa_free_device_info(struct ctlr_info *h)
9035 {
9036 	int i;
9037 
9038 	for (i = 0; i < h->ndevices; i++) {
9039 		kfree(h->dev[i]);
9040 		h->dev[i] = NULL;
9041 	}
9042 }
9043 
9044 static void hpsa_remove_one(struct pci_dev *pdev)
9045 {
9046 	struct ctlr_info *h;
9047 	unsigned long flags;
9048 
9049 	if (pci_get_drvdata(pdev) == NULL) {
9050 		dev_err(&pdev->dev, "unable to remove device\n");
9051 		return;
9052 	}
9053 	h = pci_get_drvdata(pdev);
9054 
9055 	/* Get rid of any controller monitoring work items */
9056 	spin_lock_irqsave(&h->lock, flags);
9057 	h->remove_in_progress = 1;
9058 	spin_unlock_irqrestore(&h->lock, flags);
9059 	cancel_delayed_work_sync(&h->monitor_ctlr_work);
9060 	cancel_delayed_work_sync(&h->rescan_ctlr_work);
9061 	cancel_delayed_work_sync(&h->event_monitor_work);
9062 	destroy_workqueue(h->rescan_ctlr_wq);
9063 	destroy_workqueue(h->resubmit_wq);
9064 	destroy_workqueue(h->monitor_ctlr_wq);
9065 
9066 	hpsa_delete_sas_host(h);
9067 
9068 	/*
9069 	 * Call before disabling interrupts.
9070 	 * scsi_remove_host can trigger I/O operations especially
9071 	 * when multipath is enabled. There can be SYNCHRONIZE CACHE
9072 	 * operations which cannot complete and will hang the system.
9073 	 */
9074 	if (h->scsi_host)
9075 		scsi_remove_host(h->scsi_host);		/* init_one 8 */
9076 	/* includes hpsa_free_irqs - init_one 4 */
9077 	/* includes hpsa_disable_interrupt_mode - pci_init 2 */
9078 	__hpsa_shutdown(pdev);
9079 
9080 	hpsa_free_device_info(h);		/* scan */
9081 
9082 	kfree(h->hba_inquiry_data);			/* init_one 10 */
9083 	h->hba_inquiry_data = NULL;			/* init_one 10 */
9084 	hpsa_free_ioaccel2_sg_chain_blocks(h);
9085 	hpsa_free_performant_mode(h);			/* init_one 7 */
9086 	hpsa_free_sg_chain_blocks(h);			/* init_one 6 */
9087 	hpsa_free_cmd_pool(h);				/* init_one 5 */
9088 	kfree(h->lastlogicals);
9089 
9090 	/* hpsa_free_irqs already called via hpsa_shutdown init_one 4 */
9091 
9092 	scsi_host_put(h->scsi_host);			/* init_one 3 */
9093 	h->scsi_host = NULL;				/* init_one 3 */
9094 
9095 	/* includes hpsa_disable_interrupt_mode - pci_init 2 */
9096 	hpsa_free_pci_init(h);				/* init_one 2.5 */
9097 
9098 	free_percpu(h->lockup_detected);		/* init_one 2 */
9099 	h->lockup_detected = NULL;			/* init_one 2 */
9100 
9101 	hpda_free_ctlr_info(h);				/* init_one 1 */
9102 }
9103 
9104 static int __maybe_unused hpsa_suspend(
9105 	__attribute__((unused)) struct device *dev)
9106 {
9107 	return -ENOSYS;
9108 }
9109 
9110 static int __maybe_unused hpsa_resume
9111 	(__attribute__((unused)) struct device *dev)
9112 {
9113 	return -ENOSYS;
9114 }
9115 
9116 static SIMPLE_DEV_PM_OPS(hpsa_pm_ops, hpsa_suspend, hpsa_resume);
9117 
9118 static struct pci_driver hpsa_pci_driver = {
9119 	.name = HPSA,
9120 	.probe = hpsa_init_one,
9121 	.remove = hpsa_remove_one,
9122 	.id_table = hpsa_pci_device_id,	/* id_table */
9123 	.shutdown = hpsa_shutdown,
9124 	.driver.pm = &hpsa_pm_ops,
9125 };
9126 
9127 /* Fill in bucket_map[], given nsgs (the max number of
9128  * scatter gather elements supported) and bucket[],
9129  * which is an array of 8 integers.  The bucket[] array
9130  * contains 8 different DMA transfer sizes (in 16
9131  * byte increments) which the controller uses to fetch
9132  * commands.  This function fills in bucket_map[], which
9133  * maps a given number of scatter gather elements to one of
9134  * the 8 DMA transfer sizes.  The point of it is to allow the
9135  * controller to only do as much DMA as needed to fetch the
9136  * command, with the DMA transfer size encoded in the lower
9137  * bits of the command address.
9138  */
9139 static void  calc_bucket_map(int bucket[], int num_buckets,
9140 	int nsgs, int min_blocks, u32 *bucket_map)
9141 {
9142 	int i, j, b, size;
9143 
9144 	/* Note, bucket_map must have nsgs+1 entries. */
9145 	for (i = 0; i <= nsgs; i++) {
9146 		/* Compute size of a command with i SG entries */
9147 		size = i + min_blocks;
9148 		b = num_buckets; /* Assume the biggest bucket */
9149 		/* Find the bucket that is just big enough */
9150 		for (j = 0; j < num_buckets; j++) {
9151 			if (bucket[j] >= size) {
9152 				b = j;
9153 				break;
9154 			}
9155 		}
9156 		/* for a command with i SG entries, use bucket b. */
9157 		bucket_map[i] = b;
9158 	}
9159 }
9160 
9161 /*
9162  * return -ENODEV on err, 0 on success (or no action)
9163  * allocates numerous items that must be freed later
9164  */
9165 static int hpsa_enter_performant_mode(struct ctlr_info *h, u32 trans_support)
9166 {
9167 	int i;
9168 	unsigned long register_value;
9169 	unsigned long transMethod = CFGTBL_Trans_Performant |
9170 			(trans_support & CFGTBL_Trans_use_short_tags) |
9171 				CFGTBL_Trans_enable_directed_msix |
9172 			(trans_support & (CFGTBL_Trans_io_accel1 |
9173 				CFGTBL_Trans_io_accel2));
9174 	struct access_method access = SA5_performant_access;
9175 
9176 	/* This is a bit complicated.  There are 8 registers on
9177 	 * the controller which we write to to tell it 8 different
9178 	 * sizes of commands which there may be.  It's a way of
9179 	 * reducing the DMA done to fetch each command.  Encoded into
9180 	 * each command's tag are 3 bits which communicate to the controller
9181 	 * which of the eight sizes that command fits within.  The size of
9182 	 * each command depends on how many scatter gather entries there are.
9183 	 * Each SG entry requires 16 bytes.  The eight registers are programmed
9184 	 * with the number of 16-byte blocks a command of that size requires.
9185 	 * The smallest command possible requires 5 such 16 byte blocks.
9186 	 * the largest command possible requires SG_ENTRIES_IN_CMD + 4 16-byte
9187 	 * blocks.  Note, this only extends to the SG entries contained
9188 	 * within the command block, and does not extend to chained blocks
9189 	 * of SG elements.   bft[] contains the eight values we write to
9190 	 * the registers.  They are not evenly distributed, but have more
9191 	 * sizes for small commands, and fewer sizes for larger commands.
9192 	 */
9193 	int bft[8] = {5, 6, 8, 10, 12, 20, 28, SG_ENTRIES_IN_CMD + 4};
9194 #define MIN_IOACCEL2_BFT_ENTRY 5
9195 #define HPSA_IOACCEL2_HEADER_SZ 4
9196 	int bft2[16] = {MIN_IOACCEL2_BFT_ENTRY, 6, 7, 8, 9, 10, 11, 12,
9197 			13, 14, 15, 16, 17, 18, 19,
9198 			HPSA_IOACCEL2_HEADER_SZ + IOACCEL2_MAXSGENTRIES};
9199 	BUILD_BUG_ON(ARRAY_SIZE(bft2) != 16);
9200 	BUILD_BUG_ON(ARRAY_SIZE(bft) != 8);
9201 	BUILD_BUG_ON(offsetof(struct io_accel2_cmd, sg) >
9202 				 16 * MIN_IOACCEL2_BFT_ENTRY);
9203 	BUILD_BUG_ON(sizeof(struct ioaccel2_sg_element) != 16);
9204 	BUILD_BUG_ON(28 > SG_ENTRIES_IN_CMD + 4);
9205 	/*  5 = 1 s/g entry or 4k
9206 	 *  6 = 2 s/g entry or 8k
9207 	 *  8 = 4 s/g entry or 16k
9208 	 * 10 = 6 s/g entry or 24k
9209 	 */
9210 
9211 	/* If the controller supports either ioaccel method then
9212 	 * we can also use the RAID stack submit path that does not
9213 	 * perform the superfluous readl() after each command submission.
9214 	 */
9215 	if (trans_support & (CFGTBL_Trans_io_accel1 | CFGTBL_Trans_io_accel2))
9216 		access = SA5_performant_access_no_read;
9217 
9218 	/* Controller spec: zero out this buffer. */
9219 	for (i = 0; i < h->nreply_queues; i++)
9220 		memset(h->reply_queue[i].head, 0, h->reply_queue_size);
9221 
9222 	bft[7] = SG_ENTRIES_IN_CMD + 4;
9223 	calc_bucket_map(bft, ARRAY_SIZE(bft),
9224 				SG_ENTRIES_IN_CMD, 4, h->blockFetchTable);
9225 	for (i = 0; i < 8; i++)
9226 		writel(bft[i], &h->transtable->BlockFetch[i]);
9227 
9228 	/* size of controller ring buffer */
9229 	writel(h->max_commands, &h->transtable->RepQSize);
9230 	writel(h->nreply_queues, &h->transtable->RepQCount);
9231 	writel(0, &h->transtable->RepQCtrAddrLow32);
9232 	writel(0, &h->transtable->RepQCtrAddrHigh32);
9233 
9234 	for (i = 0; i < h->nreply_queues; i++) {
9235 		writel(0, &h->transtable->RepQAddr[i].upper);
9236 		writel(h->reply_queue[i].busaddr,
9237 			&h->transtable->RepQAddr[i].lower);
9238 	}
9239 
9240 	writel(0, &h->cfgtable->HostWrite.command_pool_addr_hi);
9241 	writel(transMethod, &(h->cfgtable->HostWrite.TransportRequest));
9242 	/*
9243 	 * enable outbound interrupt coalescing in accelerator mode;
9244 	 */
9245 	if (trans_support & CFGTBL_Trans_io_accel1) {
9246 		access = SA5_ioaccel_mode1_access;
9247 		writel(10, &h->cfgtable->HostWrite.CoalIntDelay);
9248 		writel(4, &h->cfgtable->HostWrite.CoalIntCount);
9249 	} else
9250 		if (trans_support & CFGTBL_Trans_io_accel2)
9251 			access = SA5_ioaccel_mode2_access;
9252 	writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
9253 	if (hpsa_wait_for_mode_change_ack(h)) {
9254 		dev_err(&h->pdev->dev,
9255 			"performant mode problem - doorbell timeout\n");
9256 		return -ENODEV;
9257 	}
9258 	register_value = readl(&(h->cfgtable->TransportActive));
9259 	if (!(register_value & CFGTBL_Trans_Performant)) {
9260 		dev_err(&h->pdev->dev,
9261 			"performant mode problem - transport not active\n");
9262 		return -ENODEV;
9263 	}
9264 	/* Change the access methods to the performant access methods */
9265 	h->access = access;
9266 	h->transMethod = transMethod;
9267 
9268 	if (!((trans_support & CFGTBL_Trans_io_accel1) ||
9269 		(trans_support & CFGTBL_Trans_io_accel2)))
9270 		return 0;
9271 
9272 	if (trans_support & CFGTBL_Trans_io_accel1) {
9273 		/* Set up I/O accelerator mode */
9274 		for (i = 0; i < h->nreply_queues; i++) {
9275 			writel(i, h->vaddr + IOACCEL_MODE1_REPLY_QUEUE_INDEX);
9276 			h->reply_queue[i].current_entry =
9277 				readl(h->vaddr + IOACCEL_MODE1_PRODUCER_INDEX);
9278 		}
9279 		bft[7] = h->ioaccel_maxsg + 8;
9280 		calc_bucket_map(bft, ARRAY_SIZE(bft), h->ioaccel_maxsg, 8,
9281 				h->ioaccel1_blockFetchTable);
9282 
9283 		/* initialize all reply queue entries to unused */
9284 		for (i = 0; i < h->nreply_queues; i++)
9285 			memset(h->reply_queue[i].head,
9286 				(u8) IOACCEL_MODE1_REPLY_UNUSED,
9287 				h->reply_queue_size);
9288 
9289 		/* set all the constant fields in the accelerator command
9290 		 * frames once at init time to save CPU cycles later.
9291 		 */
9292 		for (i = 0; i < h->nr_cmds; i++) {
9293 			struct io_accel1_cmd *cp = &h->ioaccel_cmd_pool[i];
9294 
9295 			cp->function = IOACCEL1_FUNCTION_SCSIIO;
9296 			cp->err_info = (u32) (h->errinfo_pool_dhandle +
9297 					(i * sizeof(struct ErrorInfo)));
9298 			cp->err_info_len = sizeof(struct ErrorInfo);
9299 			cp->sgl_offset = IOACCEL1_SGLOFFSET;
9300 			cp->host_context_flags =
9301 				cpu_to_le16(IOACCEL1_HCFLAGS_CISS_FORMAT);
9302 			cp->timeout_sec = 0;
9303 			cp->ReplyQueue = 0;
9304 			cp->tag =
9305 				cpu_to_le64((i << DIRECT_LOOKUP_SHIFT));
9306 			cp->host_addr =
9307 				cpu_to_le64(h->ioaccel_cmd_pool_dhandle +
9308 					(i * sizeof(struct io_accel1_cmd)));
9309 		}
9310 	} else if (trans_support & CFGTBL_Trans_io_accel2) {
9311 		u64 cfg_offset, cfg_base_addr_index;
9312 		u32 bft2_offset, cfg_base_addr;
9313 
9314 		hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
9315 				    &cfg_base_addr_index, &cfg_offset);
9316 		BUILD_BUG_ON(offsetof(struct io_accel2_cmd, sg) != 64);
9317 		bft2[15] = h->ioaccel_maxsg + HPSA_IOACCEL2_HEADER_SZ;
9318 		calc_bucket_map(bft2, ARRAY_SIZE(bft2), h->ioaccel_maxsg,
9319 				4, h->ioaccel2_blockFetchTable);
9320 		bft2_offset = readl(&h->cfgtable->io_accel_request_size_offset);
9321 		BUILD_BUG_ON(offsetof(struct CfgTable,
9322 				io_accel_request_size_offset) != 0xb8);
9323 		h->ioaccel2_bft2_regs =
9324 			remap_pci_mem(pci_resource_start(h->pdev,
9325 					cfg_base_addr_index) +
9326 					cfg_offset + bft2_offset,
9327 					ARRAY_SIZE(bft2) *
9328 					sizeof(*h->ioaccel2_bft2_regs));
9329 		for (i = 0; i < ARRAY_SIZE(bft2); i++)
9330 			writel(bft2[i], &h->ioaccel2_bft2_regs[i]);
9331 	}
9332 	writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
9333 	if (hpsa_wait_for_mode_change_ack(h)) {
9334 		dev_err(&h->pdev->dev,
9335 			"performant mode problem - enabling ioaccel mode\n");
9336 		return -ENODEV;
9337 	}
9338 	return 0;
9339 }
9340 
9341 /* Free ioaccel1 mode command blocks and block fetch table */
9342 static void hpsa_free_ioaccel1_cmd_and_bft(struct ctlr_info *h)
9343 {
9344 	if (h->ioaccel_cmd_pool) {
9345 		dma_free_coherent(&h->pdev->dev,
9346 				  h->nr_cmds * sizeof(*h->ioaccel_cmd_pool),
9347 				  h->ioaccel_cmd_pool,
9348 				  h->ioaccel_cmd_pool_dhandle);
9349 		h->ioaccel_cmd_pool = NULL;
9350 		h->ioaccel_cmd_pool_dhandle = 0;
9351 	}
9352 	kfree(h->ioaccel1_blockFetchTable);
9353 	h->ioaccel1_blockFetchTable = NULL;
9354 }
9355 
9356 /* Allocate ioaccel1 mode command blocks and block fetch table */
9357 static int hpsa_alloc_ioaccel1_cmd_and_bft(struct ctlr_info *h)
9358 {
9359 	h->ioaccel_maxsg =
9360 		readl(&(h->cfgtable->io_accel_max_embedded_sg_count));
9361 	if (h->ioaccel_maxsg > IOACCEL1_MAXSGENTRIES)
9362 		h->ioaccel_maxsg = IOACCEL1_MAXSGENTRIES;
9363 
9364 	/* Command structures must be aligned on a 128-byte boundary
9365 	 * because the 7 lower bits of the address are used by the
9366 	 * hardware.
9367 	 */
9368 	BUILD_BUG_ON(sizeof(struct io_accel1_cmd) %
9369 			IOACCEL1_COMMANDLIST_ALIGNMENT);
9370 	h->ioaccel_cmd_pool =
9371 		dma_alloc_coherent(&h->pdev->dev,
9372 			h->nr_cmds * sizeof(*h->ioaccel_cmd_pool),
9373 			&h->ioaccel_cmd_pool_dhandle, GFP_KERNEL);
9374 
9375 	h->ioaccel1_blockFetchTable =
9376 		kmalloc(((h->ioaccel_maxsg + 1) *
9377 				sizeof(u32)), GFP_KERNEL);
9378 
9379 	if ((h->ioaccel_cmd_pool == NULL) ||
9380 		(h->ioaccel1_blockFetchTable == NULL))
9381 		goto clean_up;
9382 
9383 	memset(h->ioaccel_cmd_pool, 0,
9384 		h->nr_cmds * sizeof(*h->ioaccel_cmd_pool));
9385 	return 0;
9386 
9387 clean_up:
9388 	hpsa_free_ioaccel1_cmd_and_bft(h);
9389 	return -ENOMEM;
9390 }
9391 
9392 /* Free ioaccel2 mode command blocks and block fetch table */
9393 static void hpsa_free_ioaccel2_cmd_and_bft(struct ctlr_info *h)
9394 {
9395 	hpsa_free_ioaccel2_sg_chain_blocks(h);
9396 
9397 	if (h->ioaccel2_cmd_pool) {
9398 		dma_free_coherent(&h->pdev->dev,
9399 				  h->nr_cmds * sizeof(*h->ioaccel2_cmd_pool),
9400 				  h->ioaccel2_cmd_pool,
9401 				  h->ioaccel2_cmd_pool_dhandle);
9402 		h->ioaccel2_cmd_pool = NULL;
9403 		h->ioaccel2_cmd_pool_dhandle = 0;
9404 	}
9405 	kfree(h->ioaccel2_blockFetchTable);
9406 	h->ioaccel2_blockFetchTable = NULL;
9407 }
9408 
9409 /* Allocate ioaccel2 mode command blocks and block fetch table */
9410 static int hpsa_alloc_ioaccel2_cmd_and_bft(struct ctlr_info *h)
9411 {
9412 	int rc;
9413 
9414 	/* Allocate ioaccel2 mode command blocks and block fetch table */
9415 
9416 	h->ioaccel_maxsg =
9417 		readl(&(h->cfgtable->io_accel_max_embedded_sg_count));
9418 	if (h->ioaccel_maxsg > IOACCEL2_MAXSGENTRIES)
9419 		h->ioaccel_maxsg = IOACCEL2_MAXSGENTRIES;
9420 
9421 	BUILD_BUG_ON(sizeof(struct io_accel2_cmd) %
9422 			IOACCEL2_COMMANDLIST_ALIGNMENT);
9423 	h->ioaccel2_cmd_pool =
9424 		dma_alloc_coherent(&h->pdev->dev,
9425 			h->nr_cmds * sizeof(*h->ioaccel2_cmd_pool),
9426 			&h->ioaccel2_cmd_pool_dhandle, GFP_KERNEL);
9427 
9428 	h->ioaccel2_blockFetchTable =
9429 		kmalloc(((h->ioaccel_maxsg + 1) *
9430 				sizeof(u32)), GFP_KERNEL);
9431 
9432 	if ((h->ioaccel2_cmd_pool == NULL) ||
9433 		(h->ioaccel2_blockFetchTable == NULL)) {
9434 		rc = -ENOMEM;
9435 		goto clean_up;
9436 	}
9437 
9438 	rc = hpsa_allocate_ioaccel2_sg_chain_blocks(h);
9439 	if (rc)
9440 		goto clean_up;
9441 
9442 	memset(h->ioaccel2_cmd_pool, 0,
9443 		h->nr_cmds * sizeof(*h->ioaccel2_cmd_pool));
9444 	return 0;
9445 
9446 clean_up:
9447 	hpsa_free_ioaccel2_cmd_and_bft(h);
9448 	return rc;
9449 }
9450 
9451 /* Free items allocated by hpsa_put_ctlr_into_performant_mode */
9452 static void hpsa_free_performant_mode(struct ctlr_info *h)
9453 {
9454 	kfree(h->blockFetchTable);
9455 	h->blockFetchTable = NULL;
9456 	hpsa_free_reply_queues(h);
9457 	hpsa_free_ioaccel1_cmd_and_bft(h);
9458 	hpsa_free_ioaccel2_cmd_and_bft(h);
9459 }
9460 
9461 /* return -ENODEV on error, 0 on success (or no action)
9462  * allocates numerous items that must be freed later
9463  */
9464 static int hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h)
9465 {
9466 	u32 trans_support;
9467 	int i, rc;
9468 
9469 	if (hpsa_simple_mode)
9470 		return 0;
9471 
9472 	trans_support = readl(&(h->cfgtable->TransportSupport));
9473 	if (!(trans_support & PERFORMANT_MODE))
9474 		return 0;
9475 
9476 	/* Check for I/O accelerator mode support */
9477 	if (trans_support & CFGTBL_Trans_io_accel1) {
9478 		rc = hpsa_alloc_ioaccel1_cmd_and_bft(h);
9479 		if (rc)
9480 			return rc;
9481 	} else if (trans_support & CFGTBL_Trans_io_accel2) {
9482 		rc = hpsa_alloc_ioaccel2_cmd_and_bft(h);
9483 		if (rc)
9484 			return rc;
9485 	}
9486 
9487 	h->nreply_queues = h->msix_vectors > 0 ? h->msix_vectors : 1;
9488 	hpsa_get_max_perf_mode_cmds(h);
9489 	/* Performant mode ring buffer and supporting data structures */
9490 	h->reply_queue_size = h->max_commands * sizeof(u64);
9491 
9492 	for (i = 0; i < h->nreply_queues; i++) {
9493 		h->reply_queue[i].head = dma_alloc_coherent(&h->pdev->dev,
9494 						h->reply_queue_size,
9495 						&h->reply_queue[i].busaddr,
9496 						GFP_KERNEL);
9497 		if (!h->reply_queue[i].head) {
9498 			rc = -ENOMEM;
9499 			goto clean1;	/* rq, ioaccel */
9500 		}
9501 		h->reply_queue[i].size = h->max_commands;
9502 		h->reply_queue[i].wraparound = 1;  /* spec: init to 1 */
9503 		h->reply_queue[i].current_entry = 0;
9504 	}
9505 
9506 	/* Need a block fetch table for performant mode */
9507 	h->blockFetchTable = kmalloc(((SG_ENTRIES_IN_CMD + 1) *
9508 				sizeof(u32)), GFP_KERNEL);
9509 	if (!h->blockFetchTable) {
9510 		rc = -ENOMEM;
9511 		goto clean1;	/* rq, ioaccel */
9512 	}
9513 
9514 	rc = hpsa_enter_performant_mode(h, trans_support);
9515 	if (rc)
9516 		goto clean2;	/* bft, rq, ioaccel */
9517 	return 0;
9518 
9519 clean2:	/* bft, rq, ioaccel */
9520 	kfree(h->blockFetchTable);
9521 	h->blockFetchTable = NULL;
9522 clean1:	/* rq, ioaccel */
9523 	hpsa_free_reply_queues(h);
9524 	hpsa_free_ioaccel1_cmd_and_bft(h);
9525 	hpsa_free_ioaccel2_cmd_and_bft(h);
9526 	return rc;
9527 }
9528 
9529 static int is_accelerated_cmd(struct CommandList *c)
9530 {
9531 	return c->cmd_type == CMD_IOACCEL1 || c->cmd_type == CMD_IOACCEL2;
9532 }
9533 
9534 static void hpsa_drain_accel_commands(struct ctlr_info *h)
9535 {
9536 	struct CommandList *c = NULL;
9537 	int i, accel_cmds_out;
9538 	int refcount;
9539 
9540 	do { /* wait for all outstanding ioaccel commands to drain out */
9541 		accel_cmds_out = 0;
9542 		for (i = 0; i < h->nr_cmds; i++) {
9543 			c = h->cmd_pool + i;
9544 			refcount = atomic_inc_return(&c->refcount);
9545 			if (refcount > 1) /* Command is allocated */
9546 				accel_cmds_out += is_accelerated_cmd(c);
9547 			cmd_free(h, c);
9548 		}
9549 		if (accel_cmds_out <= 0)
9550 			break;
9551 		msleep(100);
9552 	} while (1);
9553 }
9554 
9555 static struct hpsa_sas_phy *hpsa_alloc_sas_phy(
9556 				struct hpsa_sas_port *hpsa_sas_port)
9557 {
9558 	struct hpsa_sas_phy *hpsa_sas_phy;
9559 	struct sas_phy *phy;
9560 
9561 	hpsa_sas_phy = kzalloc_obj(*hpsa_sas_phy);
9562 	if (!hpsa_sas_phy)
9563 		return NULL;
9564 
9565 	phy = sas_phy_alloc(hpsa_sas_port->parent_node->parent_dev,
9566 		hpsa_sas_port->next_phy_index);
9567 	if (!phy) {
9568 		kfree(hpsa_sas_phy);
9569 		return NULL;
9570 	}
9571 
9572 	hpsa_sas_port->next_phy_index++;
9573 	hpsa_sas_phy->phy = phy;
9574 	hpsa_sas_phy->parent_port = hpsa_sas_port;
9575 
9576 	return hpsa_sas_phy;
9577 }
9578 
9579 static void hpsa_free_sas_phy(struct hpsa_sas_phy *hpsa_sas_phy)
9580 {
9581 	struct sas_phy *phy = hpsa_sas_phy->phy;
9582 
9583 	sas_port_delete_phy(hpsa_sas_phy->parent_port->port, phy);
9584 	if (hpsa_sas_phy->added_to_port)
9585 		list_del(&hpsa_sas_phy->phy_list_entry);
9586 	sas_phy_delete(phy);
9587 	kfree(hpsa_sas_phy);
9588 }
9589 
9590 static int hpsa_sas_port_add_phy(struct hpsa_sas_phy *hpsa_sas_phy)
9591 {
9592 	int rc;
9593 	struct hpsa_sas_port *hpsa_sas_port;
9594 	struct sas_phy *phy;
9595 	struct sas_identify *identify;
9596 
9597 	hpsa_sas_port = hpsa_sas_phy->parent_port;
9598 	phy = hpsa_sas_phy->phy;
9599 
9600 	identify = &phy->identify;
9601 	memset(identify, 0, sizeof(*identify));
9602 	identify->sas_address = hpsa_sas_port->sas_address;
9603 	identify->device_type = SAS_END_DEVICE;
9604 	identify->initiator_port_protocols = SAS_PROTOCOL_STP;
9605 	identify->target_port_protocols = SAS_PROTOCOL_STP;
9606 	phy->minimum_linkrate_hw = SAS_LINK_RATE_UNKNOWN;
9607 	phy->maximum_linkrate_hw = SAS_LINK_RATE_UNKNOWN;
9608 	phy->minimum_linkrate = SAS_LINK_RATE_UNKNOWN;
9609 	phy->maximum_linkrate = SAS_LINK_RATE_UNKNOWN;
9610 	phy->negotiated_linkrate = SAS_LINK_RATE_UNKNOWN;
9611 
9612 	rc = sas_phy_add(hpsa_sas_phy->phy);
9613 	if (rc)
9614 		return rc;
9615 
9616 	sas_port_add_phy(hpsa_sas_port->port, hpsa_sas_phy->phy);
9617 	list_add_tail(&hpsa_sas_phy->phy_list_entry,
9618 			&hpsa_sas_port->phy_list_head);
9619 	hpsa_sas_phy->added_to_port = true;
9620 
9621 	return 0;
9622 }
9623 
9624 static int
9625 	hpsa_sas_port_add_rphy(struct hpsa_sas_port *hpsa_sas_port,
9626 				struct sas_rphy *rphy)
9627 {
9628 	struct sas_identify *identify;
9629 
9630 	identify = &rphy->identify;
9631 	identify->sas_address = hpsa_sas_port->sas_address;
9632 	identify->initiator_port_protocols = SAS_PROTOCOL_STP;
9633 	identify->target_port_protocols = SAS_PROTOCOL_STP;
9634 
9635 	return sas_rphy_add(rphy);
9636 }
9637 
9638 static struct hpsa_sas_port
9639 	*hpsa_alloc_sas_port(struct hpsa_sas_node *hpsa_sas_node,
9640 				u64 sas_address)
9641 {
9642 	int rc;
9643 	struct hpsa_sas_port *hpsa_sas_port;
9644 	struct sas_port *port;
9645 
9646 	hpsa_sas_port = kzalloc_obj(*hpsa_sas_port);
9647 	if (!hpsa_sas_port)
9648 		return NULL;
9649 
9650 	INIT_LIST_HEAD(&hpsa_sas_port->phy_list_head);
9651 	hpsa_sas_port->parent_node = hpsa_sas_node;
9652 
9653 	port = sas_port_alloc_num(hpsa_sas_node->parent_dev);
9654 	if (!port)
9655 		goto free_hpsa_port;
9656 
9657 	rc = sas_port_add(port);
9658 	if (rc)
9659 		goto free_sas_port;
9660 
9661 	hpsa_sas_port->port = port;
9662 	hpsa_sas_port->sas_address = sas_address;
9663 	list_add_tail(&hpsa_sas_port->port_list_entry,
9664 			&hpsa_sas_node->port_list_head);
9665 
9666 	return hpsa_sas_port;
9667 
9668 free_sas_port:
9669 	sas_port_free(port);
9670 free_hpsa_port:
9671 	kfree(hpsa_sas_port);
9672 
9673 	return NULL;
9674 }
9675 
9676 static void hpsa_free_sas_port(struct hpsa_sas_port *hpsa_sas_port)
9677 {
9678 	struct hpsa_sas_phy *hpsa_sas_phy;
9679 	struct hpsa_sas_phy *next;
9680 
9681 	list_for_each_entry_safe(hpsa_sas_phy, next,
9682 			&hpsa_sas_port->phy_list_head, phy_list_entry)
9683 		hpsa_free_sas_phy(hpsa_sas_phy);
9684 
9685 	sas_port_delete(hpsa_sas_port->port);
9686 	list_del(&hpsa_sas_port->port_list_entry);
9687 	kfree(hpsa_sas_port);
9688 }
9689 
9690 static struct hpsa_sas_node *hpsa_alloc_sas_node(struct device *parent_dev)
9691 {
9692 	struct hpsa_sas_node *hpsa_sas_node;
9693 
9694 	hpsa_sas_node = kzalloc_obj(*hpsa_sas_node);
9695 	if (hpsa_sas_node) {
9696 		hpsa_sas_node->parent_dev = parent_dev;
9697 		INIT_LIST_HEAD(&hpsa_sas_node->port_list_head);
9698 	}
9699 
9700 	return hpsa_sas_node;
9701 }
9702 
9703 static void hpsa_free_sas_node(struct hpsa_sas_node *hpsa_sas_node)
9704 {
9705 	struct hpsa_sas_port *hpsa_sas_port;
9706 	struct hpsa_sas_port *next;
9707 
9708 	if (!hpsa_sas_node)
9709 		return;
9710 
9711 	list_for_each_entry_safe(hpsa_sas_port, next,
9712 			&hpsa_sas_node->port_list_head, port_list_entry)
9713 		hpsa_free_sas_port(hpsa_sas_port);
9714 
9715 	kfree(hpsa_sas_node);
9716 }
9717 
9718 static struct hpsa_scsi_dev_t
9719 	*hpsa_find_device_by_sas_rphy(struct ctlr_info *h,
9720 					struct sas_rphy *rphy)
9721 {
9722 	int i;
9723 	struct hpsa_scsi_dev_t *device;
9724 
9725 	for (i = 0; i < h->ndevices; i++) {
9726 		device = h->dev[i];
9727 		if (!device->sas_port)
9728 			continue;
9729 		if (device->sas_port->rphy == rphy)
9730 			return device;
9731 	}
9732 
9733 	return NULL;
9734 }
9735 
9736 static int hpsa_add_sas_host(struct ctlr_info *h)
9737 {
9738 	int rc;
9739 	struct device *parent_dev;
9740 	struct hpsa_sas_node *hpsa_sas_node;
9741 	struct hpsa_sas_port *hpsa_sas_port;
9742 	struct hpsa_sas_phy *hpsa_sas_phy;
9743 
9744 	parent_dev = &h->scsi_host->shost_dev;
9745 
9746 	hpsa_sas_node = hpsa_alloc_sas_node(parent_dev);
9747 	if (!hpsa_sas_node)
9748 		return -ENOMEM;
9749 
9750 	hpsa_sas_port = hpsa_alloc_sas_port(hpsa_sas_node, h->sas_address);
9751 	if (!hpsa_sas_port) {
9752 		rc = -ENODEV;
9753 		goto free_sas_node;
9754 	}
9755 
9756 	hpsa_sas_phy = hpsa_alloc_sas_phy(hpsa_sas_port);
9757 	if (!hpsa_sas_phy) {
9758 		rc = -ENODEV;
9759 		goto free_sas_port;
9760 	}
9761 
9762 	rc = hpsa_sas_port_add_phy(hpsa_sas_phy);
9763 	if (rc)
9764 		goto free_sas_phy;
9765 
9766 	h->sas_host = hpsa_sas_node;
9767 
9768 	return 0;
9769 
9770 free_sas_phy:
9771 	sas_phy_free(hpsa_sas_phy->phy);
9772 	kfree(hpsa_sas_phy);
9773 free_sas_port:
9774 	hpsa_free_sas_port(hpsa_sas_port);
9775 free_sas_node:
9776 	hpsa_free_sas_node(hpsa_sas_node);
9777 
9778 	return rc;
9779 }
9780 
9781 static void hpsa_delete_sas_host(struct ctlr_info *h)
9782 {
9783 	hpsa_free_sas_node(h->sas_host);
9784 }
9785 
9786 static int hpsa_add_sas_device(struct hpsa_sas_node *hpsa_sas_node,
9787 				struct hpsa_scsi_dev_t *device)
9788 {
9789 	int rc;
9790 	struct hpsa_sas_port *hpsa_sas_port;
9791 	struct sas_rphy *rphy;
9792 
9793 	hpsa_sas_port = hpsa_alloc_sas_port(hpsa_sas_node, device->sas_address);
9794 	if (!hpsa_sas_port)
9795 		return -ENOMEM;
9796 
9797 	rphy = sas_end_device_alloc(hpsa_sas_port->port);
9798 	if (!rphy) {
9799 		rc = -ENODEV;
9800 		goto free_sas_port;
9801 	}
9802 
9803 	hpsa_sas_port->rphy = rphy;
9804 	device->sas_port = hpsa_sas_port;
9805 
9806 	rc = hpsa_sas_port_add_rphy(hpsa_sas_port, rphy);
9807 	if (rc)
9808 		goto free_sas_rphy;
9809 
9810 	return 0;
9811 
9812 free_sas_rphy:
9813 	sas_rphy_free(rphy);
9814 free_sas_port:
9815 	hpsa_free_sas_port(hpsa_sas_port);
9816 	device->sas_port = NULL;
9817 
9818 	return rc;
9819 }
9820 
9821 static void hpsa_remove_sas_device(struct hpsa_scsi_dev_t *device)
9822 {
9823 	if (device->sas_port) {
9824 		hpsa_free_sas_port(device->sas_port);
9825 		device->sas_port = NULL;
9826 	}
9827 }
9828 
9829 static int
9830 hpsa_sas_get_linkerrors(struct sas_phy *phy)
9831 {
9832 	return 0;
9833 }
9834 
9835 static int
9836 hpsa_sas_get_enclosure_identifier(struct sas_rphy *rphy, u64 *identifier)
9837 {
9838 	struct Scsi_Host *shost = phy_to_shost(rphy);
9839 	struct ctlr_info *h;
9840 	struct hpsa_scsi_dev_t *sd;
9841 
9842 	if (!shost)
9843 		return -ENXIO;
9844 
9845 	h = shost_to_hba(shost);
9846 
9847 	if (!h)
9848 		return -ENXIO;
9849 
9850 	sd = hpsa_find_device_by_sas_rphy(h, rphy);
9851 	if (!sd)
9852 		return -ENXIO;
9853 
9854 	*identifier = sd->eli;
9855 
9856 	return 0;
9857 }
9858 
9859 static int
9860 hpsa_sas_get_bay_identifier(struct sas_rphy *rphy)
9861 {
9862 	return -ENXIO;
9863 }
9864 
9865 static int
9866 hpsa_sas_phy_reset(struct sas_phy *phy, int hard_reset)
9867 {
9868 	return 0;
9869 }
9870 
9871 static int
9872 hpsa_sas_phy_enable(struct sas_phy *phy, int enable)
9873 {
9874 	return 0;
9875 }
9876 
9877 static int
9878 hpsa_sas_phy_setup(struct sas_phy *phy)
9879 {
9880 	return 0;
9881 }
9882 
9883 static void
9884 hpsa_sas_phy_release(struct sas_phy *phy)
9885 {
9886 }
9887 
9888 static int
9889 hpsa_sas_phy_speed(struct sas_phy *phy, struct sas_phy_linkrates *rates)
9890 {
9891 	return -EINVAL;
9892 }
9893 
9894 static struct sas_function_template hpsa_sas_transport_functions = {
9895 	.get_linkerrors = hpsa_sas_get_linkerrors,
9896 	.get_enclosure_identifier = hpsa_sas_get_enclosure_identifier,
9897 	.get_bay_identifier = hpsa_sas_get_bay_identifier,
9898 	.phy_reset = hpsa_sas_phy_reset,
9899 	.phy_enable = hpsa_sas_phy_enable,
9900 	.phy_setup = hpsa_sas_phy_setup,
9901 	.phy_release = hpsa_sas_phy_release,
9902 	.set_phy_speed = hpsa_sas_phy_speed,
9903 };
9904 
9905 /*
9906  *  This is it.  Register the PCI driver information for the cards we control
9907  *  the OS will call our registered routines when it finds one of our cards.
9908  */
9909 static int __init hpsa_init(void)
9910 {
9911 	int rc;
9912 
9913 	hpsa_sas_transport_template =
9914 		sas_attach_transport(&hpsa_sas_transport_functions);
9915 	if (!hpsa_sas_transport_template)
9916 		return -ENODEV;
9917 
9918 	rc = pci_register_driver(&hpsa_pci_driver);
9919 
9920 	if (rc)
9921 		sas_release_transport(hpsa_sas_transport_template);
9922 
9923 	return rc;
9924 }
9925 
9926 static void __exit hpsa_cleanup(void)
9927 {
9928 	pci_unregister_driver(&hpsa_pci_driver);
9929 	sas_release_transport(hpsa_sas_transport_template);
9930 }
9931 
9932 static void __attribute__((unused)) verify_offsets(void)
9933 {
9934 #define VERIFY_OFFSET(member, offset) \
9935 	BUILD_BUG_ON(offsetof(struct raid_map_data, member) != offset)
9936 
9937 	VERIFY_OFFSET(structure_size, 0);
9938 	VERIFY_OFFSET(volume_blk_size, 4);
9939 	VERIFY_OFFSET(volume_blk_cnt, 8);
9940 	VERIFY_OFFSET(phys_blk_shift, 16);
9941 	VERIFY_OFFSET(parity_rotation_shift, 17);
9942 	VERIFY_OFFSET(strip_size, 18);
9943 	VERIFY_OFFSET(disk_starting_blk, 20);
9944 	VERIFY_OFFSET(disk_blk_cnt, 28);
9945 	VERIFY_OFFSET(data_disks_per_row, 36);
9946 	VERIFY_OFFSET(metadata_disks_per_row, 38);
9947 	VERIFY_OFFSET(row_cnt, 40);
9948 	VERIFY_OFFSET(layout_map_count, 42);
9949 	VERIFY_OFFSET(flags, 44);
9950 	VERIFY_OFFSET(dekindex, 46);
9951 	/* VERIFY_OFFSET(reserved, 48 */
9952 	VERIFY_OFFSET(data, 64);
9953 
9954 #undef VERIFY_OFFSET
9955 
9956 #define VERIFY_OFFSET(member, offset) \
9957 	BUILD_BUG_ON(offsetof(struct io_accel2_cmd, member) != offset)
9958 
9959 	VERIFY_OFFSET(IU_type, 0);
9960 	VERIFY_OFFSET(direction, 1);
9961 	VERIFY_OFFSET(reply_queue, 2);
9962 	/* VERIFY_OFFSET(reserved1, 3);  */
9963 	VERIFY_OFFSET(scsi_nexus, 4);
9964 	VERIFY_OFFSET(Tag, 8);
9965 	VERIFY_OFFSET(cdb, 16);
9966 	VERIFY_OFFSET(cciss_lun, 32);
9967 	VERIFY_OFFSET(data_len, 40);
9968 	VERIFY_OFFSET(cmd_priority_task_attr, 44);
9969 	VERIFY_OFFSET(sg_count, 45);
9970 	/* VERIFY_OFFSET(reserved3 */
9971 	VERIFY_OFFSET(err_ptr, 48);
9972 	VERIFY_OFFSET(err_len, 56);
9973 	/* VERIFY_OFFSET(reserved4  */
9974 	VERIFY_OFFSET(sg, 64);
9975 
9976 #undef VERIFY_OFFSET
9977 
9978 #define VERIFY_OFFSET(member, offset) \
9979 	BUILD_BUG_ON(offsetof(struct io_accel1_cmd, member) != offset)
9980 
9981 	VERIFY_OFFSET(dev_handle, 0x00);
9982 	VERIFY_OFFSET(reserved1, 0x02);
9983 	VERIFY_OFFSET(function, 0x03);
9984 	VERIFY_OFFSET(reserved2, 0x04);
9985 	VERIFY_OFFSET(err_info, 0x0C);
9986 	VERIFY_OFFSET(reserved3, 0x10);
9987 	VERIFY_OFFSET(err_info_len, 0x12);
9988 	VERIFY_OFFSET(reserved4, 0x13);
9989 	VERIFY_OFFSET(sgl_offset, 0x14);
9990 	VERIFY_OFFSET(reserved5, 0x15);
9991 	VERIFY_OFFSET(transfer_len, 0x1C);
9992 	VERIFY_OFFSET(reserved6, 0x20);
9993 	VERIFY_OFFSET(io_flags, 0x24);
9994 	VERIFY_OFFSET(reserved7, 0x26);
9995 	VERIFY_OFFSET(LUN, 0x34);
9996 	VERIFY_OFFSET(control, 0x3C);
9997 	VERIFY_OFFSET(CDB, 0x40);
9998 	VERIFY_OFFSET(reserved8, 0x50);
9999 	VERIFY_OFFSET(host_context_flags, 0x60);
10000 	VERIFY_OFFSET(timeout_sec, 0x62);
10001 	VERIFY_OFFSET(ReplyQueue, 0x64);
10002 	VERIFY_OFFSET(reserved9, 0x65);
10003 	VERIFY_OFFSET(tag, 0x68);
10004 	VERIFY_OFFSET(host_addr, 0x70);
10005 	VERIFY_OFFSET(CISS_LUN, 0x78);
10006 	VERIFY_OFFSET(SG, 0x78 + 8);
10007 #undef VERIFY_OFFSET
10008 }
10009 
10010 module_init(hpsa_init);
10011 module_exit(hpsa_cleanup);
10012