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