• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /netgear-R7000-V1.0.7.12_1.2.5/components/opensource/linux/linux-2.6.36/drivers/block/
1/*
2 *    Disk Array driver for HP Smart Array controllers.
3 *    (C) Copyright 2000, 2007 Hewlett-Packard Development Company, L.P.
4 *
5 *    This program is free software; you can redistribute it and/or modify
6 *    it under the terms of the GNU General Public License as published by
7 *    the Free Software Foundation; version 2 of the License.
8 *
9 *    This program is distributed in the hope that it will be useful,
10 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
11 *    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 *    General Public License for more details.
13 *
14 *    You should have received a copy of the GNU General Public License
15 *    along with this program; if not, write to the Free Software
16 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17 *    02111-1307, USA.
18 *
19 *    Questions/Comments/Bugfixes to iss_storagedev@hp.com
20 *
21 */
22
23#include <linux/module.h>
24#include <linux/interrupt.h>
25#include <linux/types.h>
26#include <linux/pci.h>
27#include <linux/kernel.h>
28#include <linux/slab.h>
29#include <linux/smp_lock.h>
30#include <linux/delay.h>
31#include <linux/major.h>
32#include <linux/fs.h>
33#include <linux/bio.h>
34#include <linux/blkpg.h>
35#include <linux/timer.h>
36#include <linux/proc_fs.h>
37#include <linux/seq_file.h>
38#include <linux/init.h>
39#include <linux/jiffies.h>
40#include <linux/hdreg.h>
41#include <linux/spinlock.h>
42#include <linux/compat.h>
43#include <linux/mutex.h>
44#include <asm/uaccess.h>
45#include <asm/io.h>
46
47#include <linux/dma-mapping.h>
48#include <linux/blkdev.h>
49#include <linux/genhd.h>
50#include <linux/completion.h>
51#include <scsi/scsi.h>
52#include <scsi/sg.h>
53#include <scsi/scsi_ioctl.h>
54#include <linux/cdrom.h>
55#include <linux/scatterlist.h>
56#include <linux/kthread.h>
57
58#define CCISS_DRIVER_VERSION(maj,min,submin) ((maj<<16)|(min<<8)|(submin))
59#define DRIVER_NAME "HP CISS Driver (v 3.6.26)"
60#define DRIVER_VERSION CCISS_DRIVER_VERSION(3, 6, 26)
61
62/* Embedded module documentation macros - see modules.h */
63MODULE_AUTHOR("Hewlett-Packard Company");
64MODULE_DESCRIPTION("Driver for HP Smart Array Controllers");
65MODULE_SUPPORTED_DEVICE("HP Smart Array Controllers");
66MODULE_VERSION("3.6.26");
67MODULE_LICENSE("GPL");
68
69static int cciss_allow_hpsa;
70module_param(cciss_allow_hpsa, int, S_IRUGO|S_IWUSR);
71MODULE_PARM_DESC(cciss_allow_hpsa,
72	"Prevent cciss driver from accessing hardware known to be "
73	" supported by the hpsa driver");
74
75#include "cciss_cmd.h"
76#include "cciss.h"
77#include <linux/cciss_ioctl.h>
78
79/* define the PCI info for the cards we can control */
80static const struct pci_device_id cciss_pci_device_id[] = {
81	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISS,  0x0E11, 0x4070},
82	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4080},
83	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4082},
84	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4083},
85	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x4091},
86	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409A},
87	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409B},
88	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409C},
89	{PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409D},
90	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSA,     0x103C, 0x3225},
91	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3223},
92	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3234},
93	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3235},
94	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3211},
95	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3212},
96	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3213},
97	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3214},
98	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3215},
99	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3237},
100	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x323D},
101	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3241},
102	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3243},
103	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3245},
104	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3247},
105	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3249},
106	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324A},
107	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324B},
108	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3250},
109	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3251},
110	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3252},
111	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3253},
112	{PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3254},
113	{0,}
114};
115
116MODULE_DEVICE_TABLE(pci, cciss_pci_device_id);
117
118/*  board_id = Subsystem Device ID & Vendor ID
119 *  product = Marketing Name for the board
120 *  access = Address of the struct of function pointers
121 */
122static struct board_type products[] = {
123	{0x40700E11, "Smart Array 5300", &SA5_access},
124	{0x40800E11, "Smart Array 5i", &SA5B_access},
125	{0x40820E11, "Smart Array 532", &SA5B_access},
126	{0x40830E11, "Smart Array 5312", &SA5B_access},
127	{0x409A0E11, "Smart Array 641", &SA5_access},
128	{0x409B0E11, "Smart Array 642", &SA5_access},
129	{0x409C0E11, "Smart Array 6400", &SA5_access},
130	{0x409D0E11, "Smart Array 6400 EM", &SA5_access},
131	{0x40910E11, "Smart Array 6i", &SA5_access},
132	{0x3225103C, "Smart Array P600", &SA5_access},
133	{0x3235103C, "Smart Array P400i", &SA5_access},
134	{0x3211103C, "Smart Array E200i", &SA5_access},
135	{0x3212103C, "Smart Array E200", &SA5_access},
136	{0x3213103C, "Smart Array E200i", &SA5_access},
137	{0x3214103C, "Smart Array E200i", &SA5_access},
138	{0x3215103C, "Smart Array E200i", &SA5_access},
139	{0x3237103C, "Smart Array E500", &SA5_access},
140/* controllers below this line are also supported by the hpsa driver. */
141#define HPSA_BOUNDARY 0x3223103C
142	{0x3223103C, "Smart Array P800", &SA5_access},
143	{0x3234103C, "Smart Array P400", &SA5_access},
144	{0x323D103C, "Smart Array P700m", &SA5_access},
145	{0x3241103C, "Smart Array P212", &SA5_access},
146	{0x3243103C, "Smart Array P410", &SA5_access},
147	{0x3245103C, "Smart Array P410i", &SA5_access},
148	{0x3247103C, "Smart Array P411", &SA5_access},
149	{0x3249103C, "Smart Array P812", &SA5_access},
150	{0x324A103C, "Smart Array P712m", &SA5_access},
151	{0x324B103C, "Smart Array P711m", &SA5_access},
152	{0x3250103C, "Smart Array", &SA5_access},
153	{0x3251103C, "Smart Array", &SA5_access},
154	{0x3252103C, "Smart Array", &SA5_access},
155	{0x3253103C, "Smart Array", &SA5_access},
156	{0x3254103C, "Smart Array", &SA5_access},
157};
158
159/* How long to wait (in milliseconds) for board to go into simple mode */
160#define MAX_CONFIG_WAIT 30000
161#define MAX_IOCTL_CONFIG_WAIT 1000
162
163/*define how many times we will try a command because of bus resets */
164#define MAX_CMD_RETRIES 3
165
166#define MAX_CTLR	32
167
168/* Originally cciss driver only supports 8 major numbers */
169#define MAX_CTLR_ORIG 	8
170
171static ctlr_info_t *hba[MAX_CTLR];
172
173static struct task_struct *cciss_scan_thread;
174static DEFINE_MUTEX(scan_mutex);
175static LIST_HEAD(scan_q);
176
177static void do_cciss_request(struct request_queue *q);
178static irqreturn_t do_cciss_intx(int irq, void *dev_id);
179static irqreturn_t do_cciss_msix_intr(int irq, void *dev_id);
180static int cciss_open(struct block_device *bdev, fmode_t mode);
181static int cciss_unlocked_open(struct block_device *bdev, fmode_t mode);
182static int cciss_release(struct gendisk *disk, fmode_t mode);
183static int do_ioctl(struct block_device *bdev, fmode_t mode,
184		    unsigned int cmd, unsigned long arg);
185static int cciss_ioctl(struct block_device *bdev, fmode_t mode,
186		       unsigned int cmd, unsigned long arg);
187static int cciss_getgeo(struct block_device *bdev, struct hd_geometry *geo);
188
189static int cciss_revalidate(struct gendisk *disk);
190static int rebuild_lun_table(ctlr_info_t *h, int first_time, int via_ioctl);
191static int deregister_disk(ctlr_info_t *h, int drv_index,
192			   int clear_all, int via_ioctl);
193
194static void cciss_read_capacity(ctlr_info_t *h, int logvol,
195			sector_t *total_size, unsigned int *block_size);
196static void cciss_read_capacity_16(ctlr_info_t *h, int logvol,
197			sector_t *total_size, unsigned int *block_size);
198static void cciss_geometry_inquiry(ctlr_info_t *h, int logvol,
199			sector_t total_size,
200			unsigned int block_size, InquiryData_struct *inq_buff,
201				   drive_info_struct *drv);
202static void __devinit cciss_interrupt_mode(ctlr_info_t *);
203static void start_io(ctlr_info_t *h);
204static int sendcmd_withirq(ctlr_info_t *h, __u8 cmd, void *buff, size_t size,
205			__u8 page_code, unsigned char scsi3addr[],
206			int cmd_type);
207static int sendcmd_withirq_core(ctlr_info_t *h, CommandList_struct *c,
208	int attempt_retry);
209static int process_sendcmd_error(ctlr_info_t *h, CommandList_struct *c);
210
211static int add_to_scan_list(struct ctlr_info *h);
212static int scan_thread(void *data);
213static int check_for_unit_attention(ctlr_info_t *h, CommandList_struct *c);
214static void cciss_hba_release(struct device *dev);
215static void cciss_device_release(struct device *dev);
216static void cciss_free_gendisk(ctlr_info_t *h, int drv_index);
217static void cciss_free_drive_info(ctlr_info_t *h, int drv_index);
218static inline u32 next_command(ctlr_info_t *h);
219static int __devinit cciss_find_cfg_addrs(struct pci_dev *pdev,
220	void __iomem *vaddr, u32 *cfg_base_addr, u64 *cfg_base_addr_index,
221	u64 *cfg_offset);
222static int __devinit cciss_pci_find_memory_BAR(struct pci_dev *pdev,
223	unsigned long *memory_bar);
224
225
226/* performant mode helper functions */
227static void  calc_bucket_map(int *bucket, int num_buckets, int nsgs,
228				int *bucket_map);
229static void cciss_put_controller_into_performant_mode(ctlr_info_t *h);
230
231#ifdef CONFIG_PROC_FS
232static void cciss_procinit(ctlr_info_t *h);
233#else
234static void cciss_procinit(ctlr_info_t *h)
235{
236}
237#endif				/* CONFIG_PROC_FS */
238
239#ifdef CONFIG_COMPAT
240static int cciss_compat_ioctl(struct block_device *, fmode_t,
241			      unsigned, unsigned long);
242#endif
243
244static const struct block_device_operations cciss_fops = {
245	.owner = THIS_MODULE,
246	.open = cciss_unlocked_open,
247	.release = cciss_release,
248	.ioctl = do_ioctl,
249	.getgeo = cciss_getgeo,
250#ifdef CONFIG_COMPAT
251	.compat_ioctl = cciss_compat_ioctl,
252#endif
253	.revalidate_disk = cciss_revalidate,
254};
255
256/* set_performant_mode: Modify the tag for cciss performant
257 * set bit 0 for pull model, bits 3-1 for block fetch
258 * register number
259 */
260static void set_performant_mode(ctlr_info_t *h, CommandList_struct *c)
261{
262	if (likely(h->transMethod == CFGTBL_Trans_Performant))
263		c->busaddr |= 1 | (h->blockFetchTable[c->Header.SGList] << 1);
264}
265
266/*
267 * Enqueuing and dequeuing functions for cmdlists.
268 */
269static inline void addQ(struct hlist_head *list, CommandList_struct *c)
270{
271	hlist_add_head(&c->list, list);
272}
273
274static inline void removeQ(CommandList_struct *c)
275{
276	/*
277	 * After kexec/dump some commands might still
278	 * be in flight, which the firmware will try
279	 * to complete. Resetting the firmware doesn't work
280	 * with old fw revisions, so we have to mark
281	 * them off as 'stale' to prevent the driver from
282	 * falling over.
283	 */
284	if (WARN_ON(hlist_unhashed(&c->list))) {
285		c->cmd_type = CMD_MSG_STALE;
286		return;
287	}
288
289	hlist_del_init(&c->list);
290}
291
292static void enqueue_cmd_and_start_io(ctlr_info_t *h,
293	CommandList_struct *c)
294{
295	unsigned long flags;
296	set_performant_mode(h, c);
297	spin_lock_irqsave(&h->lock, flags);
298	addQ(&h->reqQ, c);
299	h->Qdepth++;
300	if (h->Qdepth > h->maxQsinceinit)
301		h->maxQsinceinit = h->Qdepth;
302	start_io(h);
303	spin_unlock_irqrestore(&h->lock, flags);
304}
305
306static void cciss_free_sg_chain_blocks(SGDescriptor_struct **cmd_sg_list,
307	int nr_cmds)
308{
309	int i;
310
311	if (!cmd_sg_list)
312		return;
313	for (i = 0; i < nr_cmds; i++) {
314		kfree(cmd_sg_list[i]);
315		cmd_sg_list[i] = NULL;
316	}
317	kfree(cmd_sg_list);
318}
319
320static SGDescriptor_struct **cciss_allocate_sg_chain_blocks(
321	ctlr_info_t *h, int chainsize, int nr_cmds)
322{
323	int j;
324	SGDescriptor_struct **cmd_sg_list;
325
326	if (chainsize <= 0)
327		return NULL;
328
329	cmd_sg_list = kmalloc(sizeof(*cmd_sg_list) * nr_cmds, GFP_KERNEL);
330	if (!cmd_sg_list)
331		return NULL;
332
333	/* Build up chain blocks for each command */
334	for (j = 0; j < nr_cmds; j++) {
335		/* Need a block of chainsized s/g elements. */
336		cmd_sg_list[j] = kmalloc((chainsize *
337			sizeof(*cmd_sg_list[j])), GFP_KERNEL);
338		if (!cmd_sg_list[j]) {
339			dev_err(&h->pdev->dev, "Cannot get memory "
340				"for s/g chains.\n");
341			goto clean;
342		}
343	}
344	return cmd_sg_list;
345clean:
346	cciss_free_sg_chain_blocks(cmd_sg_list, nr_cmds);
347	return NULL;
348}
349
350static void cciss_unmap_sg_chain_block(ctlr_info_t *h, CommandList_struct *c)
351{
352	SGDescriptor_struct *chain_sg;
353	u64bit temp64;
354
355	if (c->Header.SGTotal <= h->max_cmd_sgentries)
356		return;
357
358	chain_sg = &c->SG[h->max_cmd_sgentries - 1];
359	temp64.val32.lower = chain_sg->Addr.lower;
360	temp64.val32.upper = chain_sg->Addr.upper;
361	pci_unmap_single(h->pdev, temp64.val, chain_sg->Len, PCI_DMA_TODEVICE);
362}
363
364static void cciss_map_sg_chain_block(ctlr_info_t *h, CommandList_struct *c,
365	SGDescriptor_struct *chain_block, int len)
366{
367	SGDescriptor_struct *chain_sg;
368	u64bit temp64;
369
370	chain_sg = &c->SG[h->max_cmd_sgentries - 1];
371	chain_sg->Ext = CCISS_SG_CHAIN;
372	chain_sg->Len = len;
373	temp64.val = pci_map_single(h->pdev, chain_block, len,
374				PCI_DMA_TODEVICE);
375	chain_sg->Addr.lower = temp64.val32.lower;
376	chain_sg->Addr.upper = temp64.val32.upper;
377}
378
379#include "cciss_scsi.c"		/* For SCSI tape support */
380
381static const char *raid_label[] = { "0", "4", "1(1+0)", "5", "5+1", "ADG",
382	"UNKNOWN"
383};
384#define RAID_UNKNOWN (ARRAY_SIZE(raid_label)-1)
385
386#ifdef CONFIG_PROC_FS
387
388/*
389 * Report information about this controller.
390 */
391#define ENG_GIG 1000000000
392#define ENG_GIG_FACTOR (ENG_GIG/512)
393#define ENGAGE_SCSI	"engage scsi"
394
395static struct proc_dir_entry *proc_cciss;
396
397static void cciss_seq_show_header(struct seq_file *seq)
398{
399	ctlr_info_t *h = seq->private;
400
401	seq_printf(seq, "%s: HP %s Controller\n"
402		"Board ID: 0x%08lx\n"
403		"Firmware Version: %c%c%c%c\n"
404		"IRQ: %d\n"
405		"Logical drives: %d\n"
406		"Current Q depth: %d\n"
407		"Current # commands on controller: %d\n"
408		"Max Q depth since init: %d\n"
409		"Max # commands on controller since init: %d\n"
410		"Max SG entries since init: %d\n",
411		h->devname,
412		h->product_name,
413		(unsigned long)h->board_id,
414		h->firm_ver[0], h->firm_ver[1], h->firm_ver[2],
415		h->firm_ver[3], (unsigned int)h->intr[PERF_MODE_INT],
416		h->num_luns,
417		h->Qdepth, h->commands_outstanding,
418		h->maxQsinceinit, h->max_outstanding, h->maxSG);
419
420#ifdef CONFIG_CISS_SCSI_TAPE
421	cciss_seq_tape_report(seq, h);
422#endif /* CONFIG_CISS_SCSI_TAPE */
423}
424
425static void *cciss_seq_start(struct seq_file *seq, loff_t *pos)
426{
427	ctlr_info_t *h = seq->private;
428	unsigned long flags;
429
430	/* prevent displaying bogus info during configuration
431	 * or deconfiguration of a logical volume
432	 */
433	spin_lock_irqsave(&h->lock, flags);
434	if (h->busy_configuring) {
435		spin_unlock_irqrestore(&h->lock, flags);
436		return ERR_PTR(-EBUSY);
437	}
438	h->busy_configuring = 1;
439	spin_unlock_irqrestore(&h->lock, flags);
440
441	if (*pos == 0)
442		cciss_seq_show_header(seq);
443
444	return pos;
445}
446
447static int cciss_seq_show(struct seq_file *seq, void *v)
448{
449	sector_t vol_sz, vol_sz_frac;
450	ctlr_info_t *h = seq->private;
451	unsigned ctlr = h->ctlr;
452	loff_t *pos = v;
453	drive_info_struct *drv = h->drv[*pos];
454
455	if (*pos > h->highest_lun)
456		return 0;
457
458	if (drv == NULL) /* it's possible for h->drv[] to have holes. */
459		return 0;
460
461	if (drv->heads == 0)
462		return 0;
463
464	vol_sz = drv->nr_blocks;
465	vol_sz_frac = sector_div(vol_sz, ENG_GIG_FACTOR);
466	vol_sz_frac *= 100;
467	sector_div(vol_sz_frac, ENG_GIG_FACTOR);
468
469	if (drv->raid_level < 0 || drv->raid_level > RAID_UNKNOWN)
470		drv->raid_level = RAID_UNKNOWN;
471	seq_printf(seq, "cciss/c%dd%d:"
472			"\t%4u.%02uGB\tRAID %s\n",
473			ctlr, (int) *pos, (int)vol_sz, (int)vol_sz_frac,
474			raid_label[drv->raid_level]);
475	return 0;
476}
477
478static void *cciss_seq_next(struct seq_file *seq, void *v, loff_t *pos)
479{
480	ctlr_info_t *h = seq->private;
481
482	if (*pos > h->highest_lun)
483		return NULL;
484	*pos += 1;
485
486	return pos;
487}
488
489static void cciss_seq_stop(struct seq_file *seq, void *v)
490{
491	ctlr_info_t *h = seq->private;
492
493	/* Only reset h->busy_configuring if we succeeded in setting
494	 * it during cciss_seq_start. */
495	if (v == ERR_PTR(-EBUSY))
496		return;
497
498	h->busy_configuring = 0;
499}
500
501static const struct seq_operations cciss_seq_ops = {
502	.start = cciss_seq_start,
503	.show  = cciss_seq_show,
504	.next  = cciss_seq_next,
505	.stop  = cciss_seq_stop,
506};
507
508static int cciss_seq_open(struct inode *inode, struct file *file)
509{
510	int ret = seq_open(file, &cciss_seq_ops);
511	struct seq_file *seq = file->private_data;
512
513	if (!ret)
514		seq->private = PDE(inode)->data;
515
516	return ret;
517}
518
519static ssize_t
520cciss_proc_write(struct file *file, const char __user *buf,
521		 size_t length, loff_t *ppos)
522{
523	int err;
524	char *buffer;
525
526#ifndef CONFIG_CISS_SCSI_TAPE
527	return -EINVAL;
528#endif
529
530	if (!buf || length > PAGE_SIZE - 1)
531		return -EINVAL;
532
533	buffer = (char *)__get_free_page(GFP_KERNEL);
534	if (!buffer)
535		return -ENOMEM;
536
537	err = -EFAULT;
538	if (copy_from_user(buffer, buf, length))
539		goto out;
540	buffer[length] = '\0';
541
542#ifdef CONFIG_CISS_SCSI_TAPE
543	if (strncmp(ENGAGE_SCSI, buffer, sizeof ENGAGE_SCSI - 1) == 0) {
544		struct seq_file *seq = file->private_data;
545		ctlr_info_t *h = seq->private;
546
547		err = cciss_engage_scsi(h);
548		if (err == 0)
549			err = length;
550	} else
551#endif /* CONFIG_CISS_SCSI_TAPE */
552		err = -EINVAL;
553	/* might be nice to have "disengage" too, but it's not
554	   safely possible. (only 1 module use count, lock issues.) */
555
556out:
557	free_page((unsigned long)buffer);
558	return err;
559}
560
561static const struct file_operations cciss_proc_fops = {
562	.owner	 = THIS_MODULE,
563	.open    = cciss_seq_open,
564	.read    = seq_read,
565	.llseek  = seq_lseek,
566	.release = seq_release,
567	.write	 = cciss_proc_write,
568};
569
570static void __devinit cciss_procinit(ctlr_info_t *h)
571{
572	struct proc_dir_entry *pde;
573
574	if (proc_cciss == NULL)
575		proc_cciss = proc_mkdir("driver/cciss", NULL);
576	if (!proc_cciss)
577		return;
578	pde = proc_create_data(h->devname, S_IWUSR | S_IRUSR | S_IRGRP |
579					S_IROTH, proc_cciss,
580					&cciss_proc_fops, h);
581}
582#endif				/* CONFIG_PROC_FS */
583
584#define MAX_PRODUCT_NAME_LEN 19
585
586#define to_hba(n) container_of(n, struct ctlr_info, dev)
587#define to_drv(n) container_of(n, drive_info_struct, dev)
588
589static ssize_t host_store_rescan(struct device *dev,
590				 struct device_attribute *attr,
591				 const char *buf, size_t count)
592{
593	struct ctlr_info *h = to_hba(dev);
594
595	add_to_scan_list(h);
596	wake_up_process(cciss_scan_thread);
597	wait_for_completion_interruptible(&h->scan_wait);
598
599	return count;
600}
601static DEVICE_ATTR(rescan, S_IWUSR, NULL, host_store_rescan);
602
603static ssize_t dev_show_unique_id(struct device *dev,
604				 struct device_attribute *attr,
605				 char *buf)
606{
607	drive_info_struct *drv = to_drv(dev);
608	struct ctlr_info *h = to_hba(drv->dev.parent);
609	__u8 sn[16];
610	unsigned long flags;
611	int ret = 0;
612
613	spin_lock_irqsave(&h->lock, flags);
614	if (h->busy_configuring)
615		ret = -EBUSY;
616	else
617		memcpy(sn, drv->serial_no, sizeof(sn));
618	spin_unlock_irqrestore(&h->lock, flags);
619
620	if (ret)
621		return ret;
622	else
623		return snprintf(buf, 16 * 2 + 2,
624				"%02X%02X%02X%02X%02X%02X%02X%02X"
625				"%02X%02X%02X%02X%02X%02X%02X%02X\n",
626				sn[0], sn[1], sn[2], sn[3],
627				sn[4], sn[5], sn[6], sn[7],
628				sn[8], sn[9], sn[10], sn[11],
629				sn[12], sn[13], sn[14], sn[15]);
630}
631static DEVICE_ATTR(unique_id, S_IRUGO, dev_show_unique_id, NULL);
632
633static ssize_t dev_show_vendor(struct device *dev,
634			       struct device_attribute *attr,
635			       char *buf)
636{
637	drive_info_struct *drv = to_drv(dev);
638	struct ctlr_info *h = to_hba(drv->dev.parent);
639	char vendor[VENDOR_LEN + 1];
640	unsigned long flags;
641	int ret = 0;
642
643	spin_lock_irqsave(&h->lock, flags);
644	if (h->busy_configuring)
645		ret = -EBUSY;
646	else
647		memcpy(vendor, drv->vendor, VENDOR_LEN + 1);
648	spin_unlock_irqrestore(&h->lock, flags);
649
650	if (ret)
651		return ret;
652	else
653		return snprintf(buf, sizeof(vendor) + 1, "%s\n", drv->vendor);
654}
655static DEVICE_ATTR(vendor, S_IRUGO, dev_show_vendor, NULL);
656
657static ssize_t dev_show_model(struct device *dev,
658			      struct device_attribute *attr,
659			      char *buf)
660{
661	drive_info_struct *drv = to_drv(dev);
662	struct ctlr_info *h = to_hba(drv->dev.parent);
663	char model[MODEL_LEN + 1];
664	unsigned long flags;
665	int ret = 0;
666
667	spin_lock_irqsave(&h->lock, flags);
668	if (h->busy_configuring)
669		ret = -EBUSY;
670	else
671		memcpy(model, drv->model, MODEL_LEN + 1);
672	spin_unlock_irqrestore(&h->lock, flags);
673
674	if (ret)
675		return ret;
676	else
677		return snprintf(buf, sizeof(model) + 1, "%s\n", drv->model);
678}
679static DEVICE_ATTR(model, S_IRUGO, dev_show_model, NULL);
680
681static ssize_t dev_show_rev(struct device *dev,
682			    struct device_attribute *attr,
683			    char *buf)
684{
685	drive_info_struct *drv = to_drv(dev);
686	struct ctlr_info *h = to_hba(drv->dev.parent);
687	char rev[REV_LEN + 1];
688	unsigned long flags;
689	int ret = 0;
690
691	spin_lock_irqsave(&h->lock, flags);
692	if (h->busy_configuring)
693		ret = -EBUSY;
694	else
695		memcpy(rev, drv->rev, REV_LEN + 1);
696	spin_unlock_irqrestore(&h->lock, flags);
697
698	if (ret)
699		return ret;
700	else
701		return snprintf(buf, sizeof(rev) + 1, "%s\n", drv->rev);
702}
703static DEVICE_ATTR(rev, S_IRUGO, dev_show_rev, NULL);
704
705static ssize_t cciss_show_lunid(struct device *dev,
706				struct device_attribute *attr, char *buf)
707{
708	drive_info_struct *drv = to_drv(dev);
709	struct ctlr_info *h = to_hba(drv->dev.parent);
710	unsigned long flags;
711	unsigned char lunid[8];
712
713	spin_lock_irqsave(&h->lock, flags);
714	if (h->busy_configuring) {
715		spin_unlock_irqrestore(&h->lock, flags);
716		return -EBUSY;
717	}
718	if (!drv->heads) {
719		spin_unlock_irqrestore(&h->lock, flags);
720		return -ENOTTY;
721	}
722	memcpy(lunid, drv->LunID, sizeof(lunid));
723	spin_unlock_irqrestore(&h->lock, flags);
724	return snprintf(buf, 20, "0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
725		lunid[0], lunid[1], lunid[2], lunid[3],
726		lunid[4], lunid[5], lunid[6], lunid[7]);
727}
728static DEVICE_ATTR(lunid, S_IRUGO, cciss_show_lunid, NULL);
729
730static ssize_t cciss_show_raid_level(struct device *dev,
731				     struct device_attribute *attr, char *buf)
732{
733	drive_info_struct *drv = to_drv(dev);
734	struct ctlr_info *h = to_hba(drv->dev.parent);
735	int raid;
736	unsigned long flags;
737
738	spin_lock_irqsave(&h->lock, flags);
739	if (h->busy_configuring) {
740		spin_unlock_irqrestore(&h->lock, flags);
741		return -EBUSY;
742	}
743	raid = drv->raid_level;
744	spin_unlock_irqrestore(&h->lock, flags);
745	if (raid < 0 || raid > RAID_UNKNOWN)
746		raid = RAID_UNKNOWN;
747
748	return snprintf(buf, strlen(raid_label[raid]) + 7, "RAID %s\n",
749			raid_label[raid]);
750}
751static DEVICE_ATTR(raid_level, S_IRUGO, cciss_show_raid_level, NULL);
752
753static ssize_t cciss_show_usage_count(struct device *dev,
754				      struct device_attribute *attr, char *buf)
755{
756	drive_info_struct *drv = to_drv(dev);
757	struct ctlr_info *h = to_hba(drv->dev.parent);
758	unsigned long flags;
759	int count;
760
761	spin_lock_irqsave(&h->lock, flags);
762	if (h->busy_configuring) {
763		spin_unlock_irqrestore(&h->lock, flags);
764		return -EBUSY;
765	}
766	count = drv->usage_count;
767	spin_unlock_irqrestore(&h->lock, flags);
768	return snprintf(buf, 20, "%d\n", count);
769}
770static DEVICE_ATTR(usage_count, S_IRUGO, cciss_show_usage_count, NULL);
771
772static struct attribute *cciss_host_attrs[] = {
773	&dev_attr_rescan.attr,
774	NULL
775};
776
777static struct attribute_group cciss_host_attr_group = {
778	.attrs = cciss_host_attrs,
779};
780
781static const struct attribute_group *cciss_host_attr_groups[] = {
782	&cciss_host_attr_group,
783	NULL
784};
785
786static struct device_type cciss_host_type = {
787	.name		= "cciss_host",
788	.groups		= cciss_host_attr_groups,
789	.release	= cciss_hba_release,
790};
791
792static struct attribute *cciss_dev_attrs[] = {
793	&dev_attr_unique_id.attr,
794	&dev_attr_model.attr,
795	&dev_attr_vendor.attr,
796	&dev_attr_rev.attr,
797	&dev_attr_lunid.attr,
798	&dev_attr_raid_level.attr,
799	&dev_attr_usage_count.attr,
800	NULL
801};
802
803static struct attribute_group cciss_dev_attr_group = {
804	.attrs = cciss_dev_attrs,
805};
806
807static const struct attribute_group *cciss_dev_attr_groups[] = {
808	&cciss_dev_attr_group,
809	NULL
810};
811
812static struct device_type cciss_dev_type = {
813	.name		= "cciss_device",
814	.groups		= cciss_dev_attr_groups,
815	.release	= cciss_device_release,
816};
817
818static struct bus_type cciss_bus_type = {
819	.name		= "cciss",
820};
821
822/*
823 * cciss_hba_release is called when the reference count
824 * of h->dev goes to zero.
825 */
826static void cciss_hba_release(struct device *dev)
827{
828	/*
829	 * nothing to do, but need this to avoid a warning
830	 * about not having a release handler from lib/kref.c.
831	 */
832}
833
834/*
835 * Initialize sysfs entry for each controller.  This sets up and registers
836 * the 'cciss#' directory for each individual controller under
837 * /sys/bus/pci/devices/<dev>/.
838 */
839static int cciss_create_hba_sysfs_entry(struct ctlr_info *h)
840{
841	device_initialize(&h->dev);
842	h->dev.type = &cciss_host_type;
843	h->dev.bus = &cciss_bus_type;
844	dev_set_name(&h->dev, "%s", h->devname);
845	h->dev.parent = &h->pdev->dev;
846
847	return device_add(&h->dev);
848}
849
850/*
851 * Remove sysfs entries for an hba.
852 */
853static void cciss_destroy_hba_sysfs_entry(struct ctlr_info *h)
854{
855	device_del(&h->dev);
856	put_device(&h->dev); /* final put. */
857}
858
859/* cciss_device_release is called when the reference count
860 * of h->drv[x]dev goes to zero.
861 */
862static void cciss_device_release(struct device *dev)
863{
864	drive_info_struct *drv = to_drv(dev);
865	kfree(drv);
866}
867
868/*
869 * Initialize sysfs for each logical drive.  This sets up and registers
870 * the 'c#d#' directory for each individual logical drive under
871 * /sys/bus/pci/devices/<dev/ccis#/. We also create a link from
872 * /sys/block/cciss!c#d# to this entry.
873 */
874static long cciss_create_ld_sysfs_entry(struct ctlr_info *h,
875				       int drv_index)
876{
877	struct device *dev;
878
879	if (h->drv[drv_index]->device_initialized)
880		return 0;
881
882	dev = &h->drv[drv_index]->dev;
883	device_initialize(dev);
884	dev->type = &cciss_dev_type;
885	dev->bus = &cciss_bus_type;
886	dev_set_name(dev, "c%dd%d", h->ctlr, drv_index);
887	dev->parent = &h->dev;
888	h->drv[drv_index]->device_initialized = 1;
889	return device_add(dev);
890}
891
892/*
893 * Remove sysfs entries for a logical drive.
894 */
895static void cciss_destroy_ld_sysfs_entry(struct ctlr_info *h, int drv_index,
896	int ctlr_exiting)
897{
898	struct device *dev = &h->drv[drv_index]->dev;
899
900	/* special case for c*d0, we only destroy it on controller exit */
901	if (drv_index == 0 && !ctlr_exiting)
902		return;
903
904	device_del(dev);
905	put_device(dev); /* the "final" put. */
906	h->drv[drv_index] = NULL;
907}
908
909/*
910 * For operations that cannot sleep, a command block is allocated at init,
911 * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
912 * which ones are free or in use.
913 */
914static CommandList_struct *cmd_alloc(ctlr_info_t *h)
915{
916	CommandList_struct *c;
917	int i;
918	u64bit temp64;
919	dma_addr_t cmd_dma_handle, err_dma_handle;
920
921	do {
922		i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
923		if (i == h->nr_cmds)
924			return NULL;
925	} while (test_and_set_bit(i & (BITS_PER_LONG - 1),
926		  h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
927	c = h->cmd_pool + i;
928	memset(c, 0, sizeof(CommandList_struct));
929	cmd_dma_handle = h->cmd_pool_dhandle + i * sizeof(CommandList_struct);
930	c->err_info = h->errinfo_pool + i;
931	memset(c->err_info, 0, sizeof(ErrorInfo_struct));
932	err_dma_handle = h->errinfo_pool_dhandle
933	    + i * sizeof(ErrorInfo_struct);
934	h->nr_allocs++;
935
936	c->cmdindex = i;
937
938	INIT_HLIST_NODE(&c->list);
939	c->busaddr = (__u32) cmd_dma_handle;
940	temp64.val = (__u64) err_dma_handle;
941	c->ErrDesc.Addr.lower = temp64.val32.lower;
942	c->ErrDesc.Addr.upper = temp64.val32.upper;
943	c->ErrDesc.Len = sizeof(ErrorInfo_struct);
944
945	c->ctlr = h->ctlr;
946	return c;
947}
948
949/* allocate a command using pci_alloc_consistent, used for ioctls,
950 * etc., not for the main i/o path.
951 */
952static CommandList_struct *cmd_special_alloc(ctlr_info_t *h)
953{
954	CommandList_struct *c;
955	u64bit temp64;
956	dma_addr_t cmd_dma_handle, err_dma_handle;
957
958	c = (CommandList_struct *) pci_alloc_consistent(h->pdev,
959		sizeof(CommandList_struct), &cmd_dma_handle);
960	if (c == NULL)
961		return NULL;
962	memset(c, 0, sizeof(CommandList_struct));
963
964	c->cmdindex = -1;
965
966	c->err_info = (ErrorInfo_struct *)
967	    pci_alloc_consistent(h->pdev, sizeof(ErrorInfo_struct),
968		    &err_dma_handle);
969
970	if (c->err_info == NULL) {
971		pci_free_consistent(h->pdev,
972			sizeof(CommandList_struct), c, cmd_dma_handle);
973		return NULL;
974	}
975	memset(c->err_info, 0, sizeof(ErrorInfo_struct));
976
977	INIT_HLIST_NODE(&c->list);
978	c->busaddr = (__u32) cmd_dma_handle;
979	temp64.val = (__u64) err_dma_handle;
980	c->ErrDesc.Addr.lower = temp64.val32.lower;
981	c->ErrDesc.Addr.upper = temp64.val32.upper;
982	c->ErrDesc.Len = sizeof(ErrorInfo_struct);
983
984	c->ctlr = h->ctlr;
985	return c;
986}
987
988static void cmd_free(ctlr_info_t *h, CommandList_struct *c)
989{
990	int i;
991
992	i = c - h->cmd_pool;
993	clear_bit(i & (BITS_PER_LONG - 1),
994		  h->cmd_pool_bits + (i / BITS_PER_LONG));
995	h->nr_frees++;
996}
997
998static void cmd_special_free(ctlr_info_t *h, CommandList_struct *c)
999{
1000	u64bit temp64;
1001
1002	temp64.val32.lower = c->ErrDesc.Addr.lower;
1003	temp64.val32.upper = c->ErrDesc.Addr.upper;
1004	pci_free_consistent(h->pdev, sizeof(ErrorInfo_struct),
1005			    c->err_info, (dma_addr_t) temp64.val);
1006	pci_free_consistent(h->pdev, sizeof(CommandList_struct),
1007			    c, (dma_addr_t) c->busaddr);
1008}
1009
1010static inline ctlr_info_t *get_host(struct gendisk *disk)
1011{
1012	return disk->queue->queuedata;
1013}
1014
1015static inline drive_info_struct *get_drv(struct gendisk *disk)
1016{
1017	return disk->private_data;
1018}
1019
1020/*
1021 * Open.  Make sure the device is really there.
1022 */
1023static int cciss_open(struct block_device *bdev, fmode_t mode)
1024{
1025	ctlr_info_t *h = get_host(bdev->bd_disk);
1026	drive_info_struct *drv = get_drv(bdev->bd_disk);
1027
1028	dev_dbg(&h->pdev->dev, "cciss_open %s\n", bdev->bd_disk->disk_name);
1029	if (drv->busy_configuring)
1030		return -EBUSY;
1031	/*
1032	 * Root is allowed to open raw volume zero even if it's not configured
1033	 * so array config can still work. Root is also allowed to open any
1034	 * volume that has a LUN ID, so it can issue IOCTL to reread the
1035	 * disk information.  I don't think I really like this
1036	 * but I'm already using way to many device nodes to claim another one
1037	 * for "raw controller".
1038	 */
1039	if (drv->heads == 0) {
1040		if (MINOR(bdev->bd_dev) != 0) {	/* not node 0? */
1041			/* if not node 0 make sure it is a partition = 0 */
1042			if (MINOR(bdev->bd_dev) & 0x0f) {
1043				return -ENXIO;
1044				/* if it is, make sure we have a LUN ID */
1045			} else if (memcmp(drv->LunID, CTLR_LUNID,
1046				sizeof(drv->LunID))) {
1047				return -ENXIO;
1048			}
1049		}
1050		if (!capable(CAP_SYS_ADMIN))
1051			return -EPERM;
1052	}
1053	drv->usage_count++;
1054	h->usage_count++;
1055	return 0;
1056}
1057
1058static int cciss_unlocked_open(struct block_device *bdev, fmode_t mode)
1059{
1060	int ret;
1061
1062	lock_kernel();
1063	ret = cciss_open(bdev, mode);
1064	unlock_kernel();
1065
1066	return ret;
1067}
1068
1069/*
1070 * Close.  Sync first.
1071 */
1072static int cciss_release(struct gendisk *disk, fmode_t mode)
1073{
1074	ctlr_info_t *h;
1075	drive_info_struct *drv;
1076
1077	lock_kernel();
1078	h = get_host(disk);
1079	drv = get_drv(disk);
1080	dev_dbg(&h->pdev->dev, "cciss_release %s\n", disk->disk_name);
1081	drv->usage_count--;
1082	h->usage_count--;
1083	unlock_kernel();
1084	return 0;
1085}
1086
1087static int do_ioctl(struct block_device *bdev, fmode_t mode,
1088		    unsigned cmd, unsigned long arg)
1089{
1090	int ret;
1091	lock_kernel();
1092	ret = cciss_ioctl(bdev, mode, cmd, arg);
1093	unlock_kernel();
1094	return ret;
1095}
1096
1097#ifdef CONFIG_COMPAT
1098
1099static int cciss_ioctl32_passthru(struct block_device *bdev, fmode_t mode,
1100				  unsigned cmd, unsigned long arg);
1101static int cciss_ioctl32_big_passthru(struct block_device *bdev, fmode_t mode,
1102				      unsigned cmd, unsigned long arg);
1103
1104static int cciss_compat_ioctl(struct block_device *bdev, fmode_t mode,
1105			      unsigned cmd, unsigned long arg)
1106{
1107	switch (cmd) {
1108	case CCISS_GETPCIINFO:
1109	case CCISS_GETINTINFO:
1110	case CCISS_SETINTINFO:
1111	case CCISS_GETNODENAME:
1112	case CCISS_SETNODENAME:
1113	case CCISS_GETHEARTBEAT:
1114	case CCISS_GETBUSTYPES:
1115	case CCISS_GETFIRMVER:
1116	case CCISS_GETDRIVVER:
1117	case CCISS_REVALIDVOLS:
1118	case CCISS_DEREGDISK:
1119	case CCISS_REGNEWDISK:
1120	case CCISS_REGNEWD:
1121	case CCISS_RESCANDISK:
1122	case CCISS_GETLUNINFO:
1123		return do_ioctl(bdev, mode, cmd, arg);
1124
1125	case CCISS_PASSTHRU32:
1126		return cciss_ioctl32_passthru(bdev, mode, cmd, arg);
1127	case CCISS_BIG_PASSTHRU32:
1128		return cciss_ioctl32_big_passthru(bdev, mode, cmd, arg);
1129
1130	default:
1131		return -ENOIOCTLCMD;
1132	}
1133}
1134
1135static int cciss_ioctl32_passthru(struct block_device *bdev, fmode_t mode,
1136				  unsigned cmd, unsigned long arg)
1137{
1138	IOCTL32_Command_struct __user *arg32 =
1139	    (IOCTL32_Command_struct __user *) arg;
1140	IOCTL_Command_struct arg64;
1141	IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
1142	int err;
1143	u32 cp;
1144
1145	err = 0;
1146	err |=
1147	    copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
1148			   sizeof(arg64.LUN_info));
1149	err |=
1150	    copy_from_user(&arg64.Request, &arg32->Request,
1151			   sizeof(arg64.Request));
1152	err |=
1153	    copy_from_user(&arg64.error_info, &arg32->error_info,
1154			   sizeof(arg64.error_info));
1155	err |= get_user(arg64.buf_size, &arg32->buf_size);
1156	err |= get_user(cp, &arg32->buf);
1157	arg64.buf = compat_ptr(cp);
1158	err |= copy_to_user(p, &arg64, sizeof(arg64));
1159
1160	if (err)
1161		return -EFAULT;
1162
1163	err = do_ioctl(bdev, mode, CCISS_PASSTHRU, (unsigned long)p);
1164	if (err)
1165		return err;
1166	err |=
1167	    copy_in_user(&arg32->error_info, &p->error_info,
1168			 sizeof(arg32->error_info));
1169	if (err)
1170		return -EFAULT;
1171	return err;
1172}
1173
1174static int cciss_ioctl32_big_passthru(struct block_device *bdev, fmode_t mode,
1175				      unsigned cmd, unsigned long arg)
1176{
1177	BIG_IOCTL32_Command_struct __user *arg32 =
1178	    (BIG_IOCTL32_Command_struct __user *) arg;
1179	BIG_IOCTL_Command_struct arg64;
1180	BIG_IOCTL_Command_struct __user *p =
1181	    compat_alloc_user_space(sizeof(arg64));
1182	int err;
1183	u32 cp;
1184
1185	err = 0;
1186	err |=
1187	    copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
1188			   sizeof(arg64.LUN_info));
1189	err |=
1190	    copy_from_user(&arg64.Request, &arg32->Request,
1191			   sizeof(arg64.Request));
1192	err |=
1193	    copy_from_user(&arg64.error_info, &arg32->error_info,
1194			   sizeof(arg64.error_info));
1195	err |= get_user(arg64.buf_size, &arg32->buf_size);
1196	err |= get_user(arg64.malloc_size, &arg32->malloc_size);
1197	err |= get_user(cp, &arg32->buf);
1198	arg64.buf = compat_ptr(cp);
1199	err |= copy_to_user(p, &arg64, sizeof(arg64));
1200
1201	if (err)
1202		return -EFAULT;
1203
1204	err = do_ioctl(bdev, mode, CCISS_BIG_PASSTHRU, (unsigned long)p);
1205	if (err)
1206		return err;
1207	err |=
1208	    copy_in_user(&arg32->error_info, &p->error_info,
1209			 sizeof(arg32->error_info));
1210	if (err)
1211		return -EFAULT;
1212	return err;
1213}
1214#endif
1215
1216static int cciss_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1217{
1218	drive_info_struct *drv = get_drv(bdev->bd_disk);
1219
1220	if (!drv->cylinders)
1221		return -ENXIO;
1222
1223	geo->heads = drv->heads;
1224	geo->sectors = drv->sectors;
1225	geo->cylinders = drv->cylinders;
1226	return 0;
1227}
1228
1229static void check_ioctl_unit_attention(ctlr_info_t *h, CommandList_struct *c)
1230{
1231	if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
1232			c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
1233		(void)check_for_unit_attention(h, c);
1234}
1235/*
1236 * ioctl
1237 */
1238static int cciss_ioctl(struct block_device *bdev, fmode_t mode,
1239		       unsigned int cmd, unsigned long arg)
1240{
1241	struct gendisk *disk = bdev->bd_disk;
1242	ctlr_info_t *h = get_host(disk);
1243	drive_info_struct *drv = get_drv(disk);
1244	void __user *argp = (void __user *)arg;
1245
1246	dev_dbg(&h->pdev->dev, "cciss_ioctl: Called with cmd=%x %lx\n",
1247		cmd, arg);
1248	switch (cmd) {
1249	case CCISS_GETPCIINFO:
1250		{
1251			cciss_pci_info_struct pciinfo;
1252
1253			if (!arg)
1254				return -EINVAL;
1255			pciinfo.domain = pci_domain_nr(h->pdev->bus);
1256			pciinfo.bus = h->pdev->bus->number;
1257			pciinfo.dev_fn = h->pdev->devfn;
1258			pciinfo.board_id = h->board_id;
1259			if (copy_to_user
1260			    (argp, &pciinfo, sizeof(cciss_pci_info_struct)))
1261				return -EFAULT;
1262			return 0;
1263		}
1264	case CCISS_GETINTINFO:
1265		{
1266			cciss_coalint_struct intinfo;
1267			if (!arg)
1268				return -EINVAL;
1269			intinfo.delay =
1270			    readl(&h->cfgtable->HostWrite.CoalIntDelay);
1271			intinfo.count =
1272			    readl(&h->cfgtable->HostWrite.CoalIntCount);
1273			if (copy_to_user
1274			    (argp, &intinfo, sizeof(cciss_coalint_struct)))
1275				return -EFAULT;
1276			return 0;
1277		}
1278	case CCISS_SETINTINFO:
1279		{
1280			cciss_coalint_struct intinfo;
1281			unsigned long flags;
1282			int i;
1283
1284			if (!arg)
1285				return -EINVAL;
1286			if (!capable(CAP_SYS_ADMIN))
1287				return -EPERM;
1288			if (copy_from_user
1289			    (&intinfo, argp, sizeof(cciss_coalint_struct)))
1290				return -EFAULT;
1291			if ((intinfo.delay == 0) && (intinfo.count == 0))
1292				return -EINVAL;
1293			spin_lock_irqsave(&h->lock, flags);
1294			/* Update the field, and then ring the doorbell */
1295			writel(intinfo.delay,
1296			       &(h->cfgtable->HostWrite.CoalIntDelay));
1297			writel(intinfo.count,
1298			       &(h->cfgtable->HostWrite.CoalIntCount));
1299			writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
1300
1301			for (i = 0; i < MAX_IOCTL_CONFIG_WAIT; i++) {
1302				if (!(readl(h->vaddr + SA5_DOORBELL)
1303				      & CFGTBL_ChangeReq))
1304					break;
1305				/* delay and try again */
1306				udelay(1000);
1307			}
1308			spin_unlock_irqrestore(&h->lock, flags);
1309			if (i >= MAX_IOCTL_CONFIG_WAIT)
1310				return -EAGAIN;
1311			return 0;
1312		}
1313	case CCISS_GETNODENAME:
1314		{
1315			NodeName_type NodeName;
1316			int i;
1317
1318			if (!arg)
1319				return -EINVAL;
1320			for (i = 0; i < 16; i++)
1321				NodeName[i] =
1322				    readb(&h->cfgtable->ServerName[i]);
1323			if (copy_to_user(argp, NodeName, sizeof(NodeName_type)))
1324				return -EFAULT;
1325			return 0;
1326		}
1327	case CCISS_SETNODENAME:
1328		{
1329			NodeName_type NodeName;
1330			unsigned long flags;
1331			int i;
1332
1333			if (!arg)
1334				return -EINVAL;
1335			if (!capable(CAP_SYS_ADMIN))
1336				return -EPERM;
1337
1338			if (copy_from_user
1339			    (NodeName, argp, sizeof(NodeName_type)))
1340				return -EFAULT;
1341
1342			spin_lock_irqsave(&h->lock, flags);
1343
1344			/* Update the field, and then ring the doorbell */
1345			for (i = 0; i < 16; i++)
1346				writeb(NodeName[i],
1347				       &h->cfgtable->ServerName[i]);
1348
1349			writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
1350
1351			for (i = 0; i < MAX_IOCTL_CONFIG_WAIT; i++) {
1352				if (!(readl(h->vaddr + SA5_DOORBELL)
1353				      & CFGTBL_ChangeReq))
1354					break;
1355				/* delay and try again */
1356				udelay(1000);
1357			}
1358			spin_unlock_irqrestore(&h->lock, flags);
1359			if (i >= MAX_IOCTL_CONFIG_WAIT)
1360				return -EAGAIN;
1361			return 0;
1362		}
1363
1364	case CCISS_GETHEARTBEAT:
1365		{
1366			Heartbeat_type heartbeat;
1367
1368			if (!arg)
1369				return -EINVAL;
1370			heartbeat = readl(&h->cfgtable->HeartBeat);
1371			if (copy_to_user
1372			    (argp, &heartbeat, sizeof(Heartbeat_type)))
1373				return -EFAULT;
1374			return 0;
1375		}
1376	case CCISS_GETBUSTYPES:
1377		{
1378			BusTypes_type BusTypes;
1379
1380			if (!arg)
1381				return -EINVAL;
1382			BusTypes = readl(&h->cfgtable->BusTypes);
1383			if (copy_to_user
1384			    (argp, &BusTypes, sizeof(BusTypes_type)))
1385				return -EFAULT;
1386			return 0;
1387		}
1388	case CCISS_GETFIRMVER:
1389		{
1390			FirmwareVer_type firmware;
1391
1392			if (!arg)
1393				return -EINVAL;
1394			memcpy(firmware, h->firm_ver, 4);
1395
1396			if (copy_to_user
1397			    (argp, firmware, sizeof(FirmwareVer_type)))
1398				return -EFAULT;
1399			return 0;
1400		}
1401	case CCISS_GETDRIVVER:
1402		{
1403			DriverVer_type DriverVer = DRIVER_VERSION;
1404
1405			if (!arg)
1406				return -EINVAL;
1407
1408			if (copy_to_user
1409			    (argp, &DriverVer, sizeof(DriverVer_type)))
1410				return -EFAULT;
1411			return 0;
1412		}
1413
1414	case CCISS_DEREGDISK:
1415	case CCISS_REGNEWD:
1416	case CCISS_REVALIDVOLS:
1417		return rebuild_lun_table(h, 0, 1);
1418
1419	case CCISS_GETLUNINFO:{
1420			LogvolInfo_struct luninfo;
1421
1422			memcpy(&luninfo.LunID, drv->LunID,
1423				sizeof(luninfo.LunID));
1424			luninfo.num_opens = drv->usage_count;
1425			luninfo.num_parts = 0;
1426			if (copy_to_user(argp, &luninfo,
1427					 sizeof(LogvolInfo_struct)))
1428				return -EFAULT;
1429			return 0;
1430		}
1431	case CCISS_PASSTHRU:
1432		{
1433			IOCTL_Command_struct iocommand;
1434			CommandList_struct *c;
1435			char *buff = NULL;
1436			u64bit temp64;
1437			DECLARE_COMPLETION_ONSTACK(wait);
1438
1439			if (!arg)
1440				return -EINVAL;
1441
1442			if (!capable(CAP_SYS_RAWIO))
1443				return -EPERM;
1444
1445			if (copy_from_user
1446			    (&iocommand, argp, sizeof(IOCTL_Command_struct)))
1447				return -EFAULT;
1448			if ((iocommand.buf_size < 1) &&
1449			    (iocommand.Request.Type.Direction != XFER_NONE)) {
1450				return -EINVAL;
1451			}
1452			if (iocommand.buf_size > 0) {
1453				buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
1454				if (buff == NULL)
1455					return -EFAULT;
1456			}
1457			if (iocommand.Request.Type.Direction == XFER_WRITE) {
1458				/* Copy the data into the buffer we created */
1459				if (copy_from_user
1460				    (buff, iocommand.buf, iocommand.buf_size)) {
1461					kfree(buff);
1462					return -EFAULT;
1463				}
1464			} else {
1465				memset(buff, 0, iocommand.buf_size);
1466			}
1467			c = cmd_special_alloc(h);
1468			if (!c) {
1469				kfree(buff);
1470				return -ENOMEM;
1471			}
1472			/* Fill in the command type */
1473			c->cmd_type = CMD_IOCTL_PEND;
1474			/* Fill in Command Header */
1475			c->Header.ReplyQueue = 0;   /* unused in simple mode */
1476			if (iocommand.buf_size > 0) /* buffer to fill */
1477			{
1478				c->Header.SGList = 1;
1479				c->Header.SGTotal = 1;
1480			} else /* no buffers to fill */
1481			{
1482				c->Header.SGList = 0;
1483				c->Header.SGTotal = 0;
1484			}
1485			c->Header.LUN = iocommand.LUN_info;
1486			/* use the kernel address the cmd block for tag */
1487			c->Header.Tag.lower = c->busaddr;
1488
1489			/* Fill in Request block */
1490			c->Request = iocommand.Request;
1491
1492			/* Fill in the scatter gather information */
1493			if (iocommand.buf_size > 0) {
1494				temp64.val = pci_map_single(h->pdev, buff,
1495					iocommand.buf_size,
1496					PCI_DMA_BIDIRECTIONAL);
1497				c->SG[0].Addr.lower = temp64.val32.lower;
1498				c->SG[0].Addr.upper = temp64.val32.upper;
1499				c->SG[0].Len = iocommand.buf_size;
1500				c->SG[0].Ext = 0;  /* we are not chaining */
1501			}
1502			c->waiting = &wait;
1503
1504			enqueue_cmd_and_start_io(h, c);
1505			wait_for_completion(&wait);
1506
1507			/* unlock the buffers from DMA */
1508			temp64.val32.lower = c->SG[0].Addr.lower;
1509			temp64.val32.upper = c->SG[0].Addr.upper;
1510			pci_unmap_single(h->pdev, (dma_addr_t) temp64.val,
1511					 iocommand.buf_size,
1512					 PCI_DMA_BIDIRECTIONAL);
1513
1514			check_ioctl_unit_attention(h, c);
1515
1516			/* Copy the error information out */
1517			iocommand.error_info = *(c->err_info);
1518			if (copy_to_user
1519			    (argp, &iocommand, sizeof(IOCTL_Command_struct))) {
1520				kfree(buff);
1521				cmd_special_free(h, c);
1522				return -EFAULT;
1523			}
1524
1525			if (iocommand.Request.Type.Direction == XFER_READ) {
1526				/* Copy the data out of the buffer we created */
1527				if (copy_to_user
1528				    (iocommand.buf, buff, iocommand.buf_size)) {
1529					kfree(buff);
1530					cmd_special_free(h, c);
1531					return -EFAULT;
1532				}
1533			}
1534			kfree(buff);
1535			cmd_special_free(h, c);
1536			return 0;
1537		}
1538	case CCISS_BIG_PASSTHRU:{
1539			BIG_IOCTL_Command_struct *ioc;
1540			CommandList_struct *c;
1541			unsigned char **buff = NULL;
1542			int *buff_size = NULL;
1543			u64bit temp64;
1544			BYTE sg_used = 0;
1545			int status = 0;
1546			int i;
1547			DECLARE_COMPLETION_ONSTACK(wait);
1548			__u32 left;
1549			__u32 sz;
1550			BYTE __user *data_ptr;
1551
1552			if (!arg)
1553				return -EINVAL;
1554			if (!capable(CAP_SYS_RAWIO))
1555				return -EPERM;
1556			ioc = (BIG_IOCTL_Command_struct *)
1557			    kmalloc(sizeof(*ioc), GFP_KERNEL);
1558			if (!ioc) {
1559				status = -ENOMEM;
1560				goto cleanup1;
1561			}
1562			if (copy_from_user(ioc, argp, sizeof(*ioc))) {
1563				status = -EFAULT;
1564				goto cleanup1;
1565			}
1566			if ((ioc->buf_size < 1) &&
1567			    (ioc->Request.Type.Direction != XFER_NONE)) {
1568				status = -EINVAL;
1569				goto cleanup1;
1570			}
1571			/* Check kmalloc limits  using all SGs */
1572			if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
1573				status = -EINVAL;
1574				goto cleanup1;
1575			}
1576			if (ioc->buf_size > ioc->malloc_size * MAXSGENTRIES) {
1577				status = -EINVAL;
1578				goto cleanup1;
1579			}
1580			buff =
1581			    kzalloc(MAXSGENTRIES * sizeof(char *), GFP_KERNEL);
1582			if (!buff) {
1583				status = -ENOMEM;
1584				goto cleanup1;
1585			}
1586			buff_size = kmalloc(MAXSGENTRIES * sizeof(int),
1587						   GFP_KERNEL);
1588			if (!buff_size) {
1589				status = -ENOMEM;
1590				goto cleanup1;
1591			}
1592			left = ioc->buf_size;
1593			data_ptr = ioc->buf;
1594			while (left) {
1595				sz = (left >
1596				      ioc->malloc_size) ? ioc->
1597				    malloc_size : left;
1598				buff_size[sg_used] = sz;
1599				buff[sg_used] = kmalloc(sz, GFP_KERNEL);
1600				if (buff[sg_used] == NULL) {
1601					status = -ENOMEM;
1602					goto cleanup1;
1603				}
1604				if (ioc->Request.Type.Direction == XFER_WRITE) {
1605					if (copy_from_user
1606					    (buff[sg_used], data_ptr, sz)) {
1607						status = -EFAULT;
1608						goto cleanup1;
1609					}
1610				} else {
1611					memset(buff[sg_used], 0, sz);
1612				}
1613				left -= sz;
1614				data_ptr += sz;
1615				sg_used++;
1616			}
1617			c = cmd_special_alloc(h);
1618			if (!c) {
1619				status = -ENOMEM;
1620				goto cleanup1;
1621			}
1622			c->cmd_type = CMD_IOCTL_PEND;
1623			c->Header.ReplyQueue = 0;
1624
1625			if (ioc->buf_size > 0) {
1626				c->Header.SGList = sg_used;
1627				c->Header.SGTotal = sg_used;
1628			} else {
1629				c->Header.SGList = 0;
1630				c->Header.SGTotal = 0;
1631			}
1632			c->Header.LUN = ioc->LUN_info;
1633			c->Header.Tag.lower = c->busaddr;
1634
1635			c->Request = ioc->Request;
1636			if (ioc->buf_size > 0) {
1637				for (i = 0; i < sg_used; i++) {
1638					temp64.val =
1639					    pci_map_single(h->pdev, buff[i],
1640						    buff_size[i],
1641						    PCI_DMA_BIDIRECTIONAL);
1642					c->SG[i].Addr.lower =
1643					    temp64.val32.lower;
1644					c->SG[i].Addr.upper =
1645					    temp64.val32.upper;
1646					c->SG[i].Len = buff_size[i];
1647					c->SG[i].Ext = 0;	/* we are not chaining */
1648				}
1649			}
1650			c->waiting = &wait;
1651			enqueue_cmd_and_start_io(h, c);
1652			wait_for_completion(&wait);
1653			/* unlock the buffers from DMA */
1654			for (i = 0; i < sg_used; i++) {
1655				temp64.val32.lower = c->SG[i].Addr.lower;
1656				temp64.val32.upper = c->SG[i].Addr.upper;
1657				pci_unmap_single(h->pdev,
1658					(dma_addr_t) temp64.val, buff_size[i],
1659					PCI_DMA_BIDIRECTIONAL);
1660			}
1661			check_ioctl_unit_attention(h, c);
1662			/* Copy the error information out */
1663			ioc->error_info = *(c->err_info);
1664			if (copy_to_user(argp, ioc, sizeof(*ioc))) {
1665				cmd_special_free(h, c);
1666				status = -EFAULT;
1667				goto cleanup1;
1668			}
1669			if (ioc->Request.Type.Direction == XFER_READ) {
1670				/* Copy the data out of the buffer we created */
1671				BYTE __user *ptr = ioc->buf;
1672				for (i = 0; i < sg_used; i++) {
1673					if (copy_to_user
1674					    (ptr, buff[i], buff_size[i])) {
1675						cmd_special_free(h, c);
1676						status = -EFAULT;
1677						goto cleanup1;
1678					}
1679					ptr += buff_size[i];
1680				}
1681			}
1682			cmd_special_free(h, c);
1683			status = 0;
1684		      cleanup1:
1685			if (buff) {
1686				for (i = 0; i < sg_used; i++)
1687					kfree(buff[i]);
1688				kfree(buff);
1689			}
1690			kfree(buff_size);
1691			kfree(ioc);
1692			return status;
1693		}
1694
1695	/* scsi_cmd_ioctl handles these, below, though some are not */
1696	/* very meaningful for cciss.  SG_IO is the main one people want. */
1697
1698	case SG_GET_VERSION_NUM:
1699	case SG_SET_TIMEOUT:
1700	case SG_GET_TIMEOUT:
1701	case SG_GET_RESERVED_SIZE:
1702	case SG_SET_RESERVED_SIZE:
1703	case SG_EMULATED_HOST:
1704	case SG_IO:
1705	case SCSI_IOCTL_SEND_COMMAND:
1706		return scsi_cmd_ioctl(disk->queue, disk, mode, cmd, argp);
1707
1708	/* scsi_cmd_ioctl would normally handle these, below, but */
1709	/* they aren't a good fit for cciss, as CD-ROMs are */
1710	/* not supported, and we don't have any bus/target/lun */
1711	/* which we present to the kernel. */
1712
1713	case CDROM_SEND_PACKET:
1714	case CDROMCLOSETRAY:
1715	case CDROMEJECT:
1716	case SCSI_IOCTL_GET_IDLUN:
1717	case SCSI_IOCTL_GET_BUS_NUMBER:
1718	default:
1719		return -ENOTTY;
1720	}
1721}
1722
1723static void cciss_check_queues(ctlr_info_t *h)
1724{
1725	int start_queue = h->next_to_run;
1726	int i;
1727
1728	/* check to see if we have maxed out the number of commands that can
1729	 * be placed on the queue.  If so then exit.  We do this check here
1730	 * in case the interrupt we serviced was from an ioctl and did not
1731	 * free any new commands.
1732	 */
1733	if ((find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds)) == h->nr_cmds)
1734		return;
1735
1736	/* We have room on the queue for more commands.  Now we need to queue
1737	 * them up.  We will also keep track of the next queue to run so
1738	 * that every queue gets a chance to be started first.
1739	 */
1740	for (i = 0; i < h->highest_lun + 1; i++) {
1741		int curr_queue = (start_queue + i) % (h->highest_lun + 1);
1742		/* make sure the disk has been added and the drive is real
1743		 * because this can be called from the middle of init_one.
1744		 */
1745		if (!h->drv[curr_queue])
1746			continue;
1747		if (!(h->drv[curr_queue]->queue) ||
1748			!(h->drv[curr_queue]->heads))
1749			continue;
1750		blk_start_queue(h->gendisk[curr_queue]->queue);
1751
1752		/* check to see if we have maxed out the number of commands
1753		 * that can be placed on the queue.
1754		 */
1755		if ((find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds)) == h->nr_cmds) {
1756			if (curr_queue == start_queue) {
1757				h->next_to_run =
1758				    (start_queue + 1) % (h->highest_lun + 1);
1759				break;
1760			} else {
1761				h->next_to_run = curr_queue;
1762				break;
1763			}
1764		}
1765	}
1766}
1767
1768static void cciss_softirq_done(struct request *rq)
1769{
1770	CommandList_struct *c = rq->completion_data;
1771	ctlr_info_t *h = hba[c->ctlr];
1772	SGDescriptor_struct *curr_sg = c->SG;
1773	u64bit temp64;
1774	unsigned long flags;
1775	int i, ddir;
1776	int sg_index = 0;
1777
1778	if (c->Request.Type.Direction == XFER_READ)
1779		ddir = PCI_DMA_FROMDEVICE;
1780	else
1781		ddir = PCI_DMA_TODEVICE;
1782
1783	/* command did not need to be retried */
1784	/* unmap the DMA mapping for all the scatter gather elements */
1785	for (i = 0; i < c->Header.SGList; i++) {
1786		if (curr_sg[sg_index].Ext == CCISS_SG_CHAIN) {
1787			cciss_unmap_sg_chain_block(h, c);
1788			/* Point to the next block */
1789			curr_sg = h->cmd_sg_list[c->cmdindex];
1790			sg_index = 0;
1791		}
1792		temp64.val32.lower = curr_sg[sg_index].Addr.lower;
1793		temp64.val32.upper = curr_sg[sg_index].Addr.upper;
1794		pci_unmap_page(h->pdev, temp64.val, curr_sg[sg_index].Len,
1795				ddir);
1796		++sg_index;
1797	}
1798
1799	dev_dbg(&h->pdev->dev, "Done with %p\n", rq);
1800
1801	/* set the residual count for pc requests */
1802	if (rq->cmd_type == REQ_TYPE_BLOCK_PC)
1803		rq->resid_len = c->err_info->ResidualCnt;
1804
1805	blk_end_request_all(rq, (rq->errors == 0) ? 0 : -EIO);
1806
1807	spin_lock_irqsave(&h->lock, flags);
1808	cmd_free(h, c);
1809	cciss_check_queues(h);
1810	spin_unlock_irqrestore(&h->lock, flags);
1811}
1812
1813static inline void log_unit_to_scsi3addr(ctlr_info_t *h,
1814	unsigned char scsi3addr[], uint32_t log_unit)
1815{
1816	memcpy(scsi3addr, h->drv[log_unit]->LunID,
1817		sizeof(h->drv[log_unit]->LunID));
1818}
1819
1820/* This function gets the SCSI vendor, model, and revision of a logical drive
1821 * via the inquiry page 0.  Model, vendor, and rev are set to empty strings if
1822 * they cannot be read.
1823 */
1824static void cciss_get_device_descr(ctlr_info_t *h, int logvol,
1825				   char *vendor, char *model, char *rev)
1826{
1827	int rc;
1828	InquiryData_struct *inq_buf;
1829	unsigned char scsi3addr[8];
1830
1831	*vendor = '\0';
1832	*model = '\0';
1833	*rev = '\0';
1834
1835	inq_buf = kzalloc(sizeof(InquiryData_struct), GFP_KERNEL);
1836	if (!inq_buf)
1837		return;
1838
1839	log_unit_to_scsi3addr(h, scsi3addr, logvol);
1840	rc = sendcmd_withirq(h, CISS_INQUIRY, inq_buf, sizeof(*inq_buf), 0,
1841			scsi3addr, TYPE_CMD);
1842	if (rc == IO_OK) {
1843		memcpy(vendor, &inq_buf->data_byte[8], VENDOR_LEN);
1844		vendor[VENDOR_LEN] = '\0';
1845		memcpy(model, &inq_buf->data_byte[16], MODEL_LEN);
1846		model[MODEL_LEN] = '\0';
1847		memcpy(rev, &inq_buf->data_byte[32], REV_LEN);
1848		rev[REV_LEN] = '\0';
1849	}
1850
1851	kfree(inq_buf);
1852	return;
1853}
1854
1855/* This function gets the serial number of a logical drive via
1856 * inquiry page 0x83.  Serial no. is 16 bytes.  If the serial
1857 * number cannot be had, for whatever reason, 16 bytes of 0xff
1858 * are returned instead.
1859 */
1860static void cciss_get_serial_no(ctlr_info_t *h, int logvol,
1861				unsigned char *serial_no, int buflen)
1862{
1863#define PAGE_83_INQ_BYTES 64
1864	int rc;
1865	unsigned char *buf;
1866	unsigned char scsi3addr[8];
1867
1868	if (buflen > 16)
1869		buflen = 16;
1870	memset(serial_no, 0xff, buflen);
1871	buf = kzalloc(PAGE_83_INQ_BYTES, GFP_KERNEL);
1872	if (!buf)
1873		return;
1874	memset(serial_no, 0, buflen);
1875	log_unit_to_scsi3addr(h, scsi3addr, logvol);
1876	rc = sendcmd_withirq(h, CISS_INQUIRY, buf,
1877		PAGE_83_INQ_BYTES, 0x83, scsi3addr, TYPE_CMD);
1878	if (rc == IO_OK)
1879		memcpy(serial_no, &buf[8], buflen);
1880	kfree(buf);
1881	return;
1882}
1883
1884/*
1885 * cciss_add_disk sets up the block device queue for a logical drive
1886 */
1887static int cciss_add_disk(ctlr_info_t *h, struct gendisk *disk,
1888				int drv_index)
1889{
1890	disk->queue = blk_init_queue(do_cciss_request, &h->lock);
1891	if (!disk->queue)
1892		goto init_queue_failure;
1893	sprintf(disk->disk_name, "cciss/c%dd%d", h->ctlr, drv_index);
1894	disk->major = h->major;
1895	disk->first_minor = drv_index << NWD_SHIFT;
1896	disk->fops = &cciss_fops;
1897	if (cciss_create_ld_sysfs_entry(h, drv_index))
1898		goto cleanup_queue;
1899	disk->private_data = h->drv[drv_index];
1900	disk->driverfs_dev = &h->drv[drv_index]->dev;
1901
1902	/* Set up queue information */
1903	blk_queue_bounce_limit(disk->queue, h->pdev->dma_mask);
1904
1905	/* This is a hardware imposed limit. */
1906	blk_queue_max_segments(disk->queue, h->maxsgentries);
1907
1908	blk_queue_max_hw_sectors(disk->queue, h->cciss_max_sectors);
1909
1910	blk_queue_softirq_done(disk->queue, cciss_softirq_done);
1911
1912	disk->queue->queuedata = h;
1913
1914	blk_queue_logical_block_size(disk->queue,
1915				     h->drv[drv_index]->block_size);
1916
1917	/* Make sure all queue data is written out before */
1918	/* setting h->drv[drv_index]->queue, as setting this */
1919	/* allows the interrupt handler to start the queue */
1920	wmb();
1921	h->drv[drv_index]->queue = disk->queue;
1922	add_disk(disk);
1923	return 0;
1924
1925cleanup_queue:
1926	blk_cleanup_queue(disk->queue);
1927	disk->queue = NULL;
1928init_queue_failure:
1929	return -1;
1930}
1931
1932/* This function will check the usage_count of the drive to be updated/added.
1933 * If the usage_count is zero and it is a heretofore unknown drive, or,
1934 * the drive's capacity, geometry, or serial number has changed,
1935 * then the drive information will be updated and the disk will be
1936 * re-registered with the kernel.  If these conditions don't hold,
1937 * then it will be left alone for the next reboot.  The exception to this
1938 * is disk 0 which will always be left registered with the kernel since it
1939 * is also the controller node.  Any changes to disk 0 will show up on
1940 * the next reboot.
1941 */
1942static void cciss_update_drive_info(ctlr_info_t *h, int drv_index,
1943	int first_time, int via_ioctl)
1944{
1945	struct gendisk *disk;
1946	InquiryData_struct *inq_buff = NULL;
1947	unsigned int block_size;
1948	sector_t total_size;
1949	unsigned long flags = 0;
1950	int ret = 0;
1951	drive_info_struct *drvinfo;
1952
1953	/* Get information about the disk and modify the driver structure */
1954	inq_buff = kmalloc(sizeof(InquiryData_struct), GFP_KERNEL);
1955	drvinfo = kzalloc(sizeof(*drvinfo), GFP_KERNEL);
1956	if (inq_buff == NULL || drvinfo == NULL)
1957		goto mem_msg;
1958
1959	/* testing to see if 16-byte CDBs are already being used */
1960	if (h->cciss_read == CCISS_READ_16) {
1961		cciss_read_capacity_16(h, drv_index,
1962			&total_size, &block_size);
1963
1964	} else {
1965		cciss_read_capacity(h, drv_index, &total_size, &block_size);
1966		/* if read_capacity returns all F's this volume is >2TB */
1967		/* in size so we switch to 16-byte CDB's for all */
1968		/* read/write ops */
1969		if (total_size == 0xFFFFFFFFULL) {
1970			cciss_read_capacity_16(h, drv_index,
1971			&total_size, &block_size);
1972			h->cciss_read = CCISS_READ_16;
1973			h->cciss_write = CCISS_WRITE_16;
1974		} else {
1975			h->cciss_read = CCISS_READ_10;
1976			h->cciss_write = CCISS_WRITE_10;
1977		}
1978	}
1979
1980	cciss_geometry_inquiry(h, drv_index, total_size, block_size,
1981			       inq_buff, drvinfo);
1982	drvinfo->block_size = block_size;
1983	drvinfo->nr_blocks = total_size + 1;
1984
1985	cciss_get_device_descr(h, drv_index, drvinfo->vendor,
1986				drvinfo->model, drvinfo->rev);
1987	cciss_get_serial_no(h, drv_index, drvinfo->serial_no,
1988			sizeof(drvinfo->serial_no));
1989	/* Save the lunid in case we deregister the disk, below. */
1990	memcpy(drvinfo->LunID, h->drv[drv_index]->LunID,
1991		sizeof(drvinfo->LunID));
1992
1993	/* Is it the same disk we already know, and nothing's changed? */
1994	if (h->drv[drv_index]->raid_level != -1 &&
1995		((memcmp(drvinfo->serial_no,
1996				h->drv[drv_index]->serial_no, 16) == 0) &&
1997		drvinfo->block_size == h->drv[drv_index]->block_size &&
1998		drvinfo->nr_blocks == h->drv[drv_index]->nr_blocks &&
1999		drvinfo->heads == h->drv[drv_index]->heads &&
2000		drvinfo->sectors == h->drv[drv_index]->sectors &&
2001		drvinfo->cylinders == h->drv[drv_index]->cylinders))
2002			/* The disk is unchanged, nothing to update */
2003			goto freeret;
2004
2005	/* If we get here it's not the same disk, or something's changed,
2006	 * so we need to * deregister it, and re-register it, if it's not
2007	 * in use.
2008	 * If the disk already exists then deregister it before proceeding
2009	 * (unless it's the first disk (for the controller node).
2010	 */
2011	if (h->drv[drv_index]->raid_level != -1 && drv_index != 0) {
2012		dev_warn(&h->pdev->dev, "disk %d has changed.\n", drv_index);
2013		spin_lock_irqsave(&h->lock, flags);
2014		h->drv[drv_index]->busy_configuring = 1;
2015		spin_unlock_irqrestore(&h->lock, flags);
2016
2017		/* deregister_disk sets h->drv[drv_index]->queue = NULL
2018		 * which keeps the interrupt handler from starting
2019		 * the queue.
2020		 */
2021		ret = deregister_disk(h, drv_index, 0, via_ioctl);
2022	}
2023
2024	/* If the disk is in use return */
2025	if (ret)
2026		goto freeret;
2027
2028	/* Save the new information from cciss_geometry_inquiry
2029	 * and serial number inquiry.  If the disk was deregistered
2030	 * above, then h->drv[drv_index] will be NULL.
2031	 */
2032	if (h->drv[drv_index] == NULL) {
2033		drvinfo->device_initialized = 0;
2034		h->drv[drv_index] = drvinfo;
2035		drvinfo = NULL; /* so it won't be freed below. */
2036	} else {
2037		/* special case for cxd0 */
2038		h->drv[drv_index]->block_size = drvinfo->block_size;
2039		h->drv[drv_index]->nr_blocks = drvinfo->nr_blocks;
2040		h->drv[drv_index]->heads = drvinfo->heads;
2041		h->drv[drv_index]->sectors = drvinfo->sectors;
2042		h->drv[drv_index]->cylinders = drvinfo->cylinders;
2043		h->drv[drv_index]->raid_level = drvinfo->raid_level;
2044		memcpy(h->drv[drv_index]->serial_no, drvinfo->serial_no, 16);
2045		memcpy(h->drv[drv_index]->vendor, drvinfo->vendor,
2046			VENDOR_LEN + 1);
2047		memcpy(h->drv[drv_index]->model, drvinfo->model, MODEL_LEN + 1);
2048		memcpy(h->drv[drv_index]->rev, drvinfo->rev, REV_LEN + 1);
2049	}
2050
2051	++h->num_luns;
2052	disk = h->gendisk[drv_index];
2053	set_capacity(disk, h->drv[drv_index]->nr_blocks);
2054
2055	/* If it's not disk 0 (drv_index != 0)
2056	 * or if it was disk 0, but there was previously
2057	 * no actual corresponding configured logical drive
2058	 * (raid_leve == -1) then we want to update the
2059	 * logical drive's information.
2060	 */
2061	if (drv_index || first_time) {
2062		if (cciss_add_disk(h, disk, drv_index) != 0) {
2063			cciss_free_gendisk(h, drv_index);
2064			cciss_free_drive_info(h, drv_index);
2065			dev_warn(&h->pdev->dev, "could not update disk %d\n",
2066				drv_index);
2067			--h->num_luns;
2068		}
2069	}
2070
2071freeret:
2072	kfree(inq_buff);
2073	kfree(drvinfo);
2074	return;
2075mem_msg:
2076	dev_err(&h->pdev->dev, "out of memory\n");
2077	goto freeret;
2078}
2079
2080/* This function will find the first index of the controllers drive array
2081 * that has a null drv pointer and allocate the drive info struct and
2082 * will return that index   This is where new drives will be added.
2083 * If the index to be returned is greater than the highest_lun index for
2084 * the controller then highest_lun is set * to this new index.
2085 * If there are no available indexes or if tha allocation fails, then -1
2086 * is returned.  * "controller_node" is used to know if this is a real
2087 * logical drive, or just the controller node, which determines if this
2088 * counts towards highest_lun.
2089 */
2090static int cciss_alloc_drive_info(ctlr_info_t *h, int controller_node)
2091{
2092	int i;
2093	drive_info_struct *drv;
2094
2095	/* Search for an empty slot for our drive info */
2096	for (i = 0; i < CISS_MAX_LUN; i++) {
2097
2098		/* if not cxd0 case, and it's occupied, skip it. */
2099		if (h->drv[i] && i != 0)
2100			continue;
2101		/*
2102		 * If it's cxd0 case, and drv is alloc'ed already, and a
2103		 * disk is configured there, skip it.
2104		 */
2105		if (i == 0 && h->drv[i] && h->drv[i]->raid_level != -1)
2106			continue;
2107
2108		/*
2109		 * We've found an empty slot.  Update highest_lun
2110		 * provided this isn't just the fake cxd0 controller node.
2111		 */
2112		if (i > h->highest_lun && !controller_node)
2113			h->highest_lun = i;
2114
2115		/* If adding a real disk at cxd0, and it's already alloc'ed */
2116		if (i == 0 && h->drv[i] != NULL)
2117			return i;
2118
2119		/*
2120		 * Found an empty slot, not already alloc'ed.  Allocate it.
2121		 * Mark it with raid_level == -1, so we know it's new later on.
2122		 */
2123		drv = kzalloc(sizeof(*drv), GFP_KERNEL);
2124		if (!drv)
2125			return -1;
2126		drv->raid_level = -1; /* so we know it's new */
2127		h->drv[i] = drv;
2128		return i;
2129	}
2130	return -1;
2131}
2132
2133static void cciss_free_drive_info(ctlr_info_t *h, int drv_index)
2134{
2135	kfree(h->drv[drv_index]);
2136	h->drv[drv_index] = NULL;
2137}
2138
2139static void cciss_free_gendisk(ctlr_info_t *h, int drv_index)
2140{
2141	put_disk(h->gendisk[drv_index]);
2142	h->gendisk[drv_index] = NULL;
2143}
2144
2145/* cciss_add_gendisk finds a free hba[]->drv structure
2146 * and allocates a gendisk if needed, and sets the lunid
2147 * in the drvinfo structure.   It returns the index into
2148 * the ->drv[] array, or -1 if none are free.
2149 * is_controller_node indicates whether highest_lun should
2150 * count this disk, or if it's only being added to provide
2151 * a means to talk to the controller in case no logical
2152 * drives have yet been configured.
2153 */
2154static int cciss_add_gendisk(ctlr_info_t *h, unsigned char lunid[],
2155	int controller_node)
2156{
2157	int drv_index;
2158
2159	drv_index = cciss_alloc_drive_info(h, controller_node);
2160	if (drv_index == -1)
2161		return -1;
2162
2163	/*Check if the gendisk needs to be allocated */
2164	if (!h->gendisk[drv_index]) {
2165		h->gendisk[drv_index] =
2166			alloc_disk(1 << NWD_SHIFT);
2167		if (!h->gendisk[drv_index]) {
2168			dev_err(&h->pdev->dev,
2169				"could not allocate a new disk %d\n",
2170				drv_index);
2171			goto err_free_drive_info;
2172		}
2173	}
2174	memcpy(h->drv[drv_index]->LunID, lunid,
2175		sizeof(h->drv[drv_index]->LunID));
2176	if (cciss_create_ld_sysfs_entry(h, drv_index))
2177		goto err_free_disk;
2178	/* Don't need to mark this busy because nobody */
2179	/* else knows about this disk yet to contend */
2180	/* for access to it. */
2181	h->drv[drv_index]->busy_configuring = 0;
2182	wmb();
2183	return drv_index;
2184
2185err_free_disk:
2186	cciss_free_gendisk(h, drv_index);
2187err_free_drive_info:
2188	cciss_free_drive_info(h, drv_index);
2189	return -1;
2190}
2191
2192/* This is for the special case of a controller which
2193 * has no logical drives.  In this case, we still need
2194 * to register a disk so the controller can be accessed
2195 * by the Array Config Utility.
2196 */
2197static void cciss_add_controller_node(ctlr_info_t *h)
2198{
2199	struct gendisk *disk;
2200	int drv_index;
2201
2202	if (h->gendisk[0] != NULL) /* already did this? Then bail. */
2203		return;
2204
2205	drv_index = cciss_add_gendisk(h, CTLR_LUNID, 1);
2206	if (drv_index == -1)
2207		goto error;
2208	h->drv[drv_index]->block_size = 512;
2209	h->drv[drv_index]->nr_blocks = 0;
2210	h->drv[drv_index]->heads = 0;
2211	h->drv[drv_index]->sectors = 0;
2212	h->drv[drv_index]->cylinders = 0;
2213	h->drv[drv_index]->raid_level = -1;
2214	memset(h->drv[drv_index]->serial_no, 0, 16);
2215	disk = h->gendisk[drv_index];
2216	if (cciss_add_disk(h, disk, drv_index) == 0)
2217		return;
2218	cciss_free_gendisk(h, drv_index);
2219	cciss_free_drive_info(h, drv_index);
2220error:
2221	dev_warn(&h->pdev->dev, "could not add disk 0.\n");
2222	return;
2223}
2224
2225/* This function will add and remove logical drives from the Logical
2226 * drive array of the controller and maintain persistency of ordering
2227 * so that mount points are preserved until the next reboot.  This allows
2228 * for the removal of logical drives in the middle of the drive array
2229 * without a re-ordering of those drives.
2230 * INPUT
2231 * h		= The controller to perform the operations on
2232 */
2233static int rebuild_lun_table(ctlr_info_t *h, int first_time,
2234	int via_ioctl)
2235{
2236	int num_luns;
2237	ReportLunData_struct *ld_buff = NULL;
2238	int return_code;
2239	int listlength = 0;
2240	int i;
2241	int drv_found;
2242	int drv_index = 0;
2243	unsigned char lunid[8] = CTLR_LUNID;
2244	unsigned long flags;
2245
2246	if (!capable(CAP_SYS_RAWIO))
2247		return -EPERM;
2248
2249	/* Set busy_configuring flag for this operation */
2250	spin_lock_irqsave(&h->lock, flags);
2251	if (h->busy_configuring) {
2252		spin_unlock_irqrestore(&h->lock, flags);
2253		return -EBUSY;
2254	}
2255	h->busy_configuring = 1;
2256	spin_unlock_irqrestore(&h->lock, flags);
2257
2258	ld_buff = kzalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
2259	if (ld_buff == NULL)
2260		goto mem_msg;
2261
2262	return_code = sendcmd_withirq(h, CISS_REPORT_LOG, ld_buff,
2263				      sizeof(ReportLunData_struct),
2264				      0, CTLR_LUNID, TYPE_CMD);
2265
2266	if (return_code == IO_OK)
2267		listlength = be32_to_cpu(*(__be32 *) ld_buff->LUNListLength);
2268	else {	/* reading number of logical volumes failed */
2269		dev_warn(&h->pdev->dev,
2270			"report logical volume command failed\n");
2271		listlength = 0;
2272		goto freeret;
2273	}
2274
2275	num_luns = listlength / 8;	/* 8 bytes per entry */
2276	if (num_luns > CISS_MAX_LUN) {
2277		num_luns = CISS_MAX_LUN;
2278		dev_warn(&h->pdev->dev, "more luns configured"
2279		       " on controller than can be handled by"
2280		       " this driver.\n");
2281	}
2282
2283	if (num_luns == 0)
2284		cciss_add_controller_node(h);
2285
2286	/* Compare controller drive array to driver's drive array
2287	 * to see if any drives are missing on the controller due
2288	 * to action of Array Config Utility (user deletes drive)
2289	 * and deregister logical drives which have disappeared.
2290	 */
2291	for (i = 0; i <= h->highest_lun; i++) {
2292		int j;
2293		drv_found = 0;
2294
2295		/* skip holes in the array from already deleted drives */
2296		if (h->drv[i] == NULL)
2297			continue;
2298
2299		for (j = 0; j < num_luns; j++) {
2300			memcpy(lunid, &ld_buff->LUN[j][0], sizeof(lunid));
2301			if (memcmp(h->drv[i]->LunID, lunid,
2302				sizeof(lunid)) == 0) {
2303				drv_found = 1;
2304				break;
2305			}
2306		}
2307		if (!drv_found) {
2308			/* Deregister it from the OS, it's gone. */
2309			spin_lock_irqsave(&h->lock, flags);
2310			h->drv[i]->busy_configuring = 1;
2311			spin_unlock_irqrestore(&h->lock, flags);
2312			return_code = deregister_disk(h, i, 1, via_ioctl);
2313			if (h->drv[i] != NULL)
2314				h->drv[i]->busy_configuring = 0;
2315		}
2316	}
2317
2318	/* Compare controller drive array to driver's drive array.
2319	 * Check for updates in the drive information and any new drives
2320	 * on the controller due to ACU adding logical drives, or changing
2321	 * a logical drive's size, etc.  Reregister any new/changed drives
2322	 */
2323	for (i = 0; i < num_luns; i++) {
2324		int j;
2325
2326		drv_found = 0;
2327
2328		memcpy(lunid, &ld_buff->LUN[i][0], sizeof(lunid));
2329		/* Find if the LUN is already in the drive array
2330		 * of the driver.  If so then update its info
2331		 * if not in use.  If it does not exist then find
2332		 * the first free index and add it.
2333		 */
2334		for (j = 0; j <= h->highest_lun; j++) {
2335			if (h->drv[j] != NULL &&
2336				memcmp(h->drv[j]->LunID, lunid,
2337					sizeof(h->drv[j]->LunID)) == 0) {
2338				drv_index = j;
2339				drv_found = 1;
2340				break;
2341			}
2342		}
2343
2344		/* check if the drive was found already in the array */
2345		if (!drv_found) {
2346			drv_index = cciss_add_gendisk(h, lunid, 0);
2347			if (drv_index == -1)
2348				goto freeret;
2349		}
2350		cciss_update_drive_info(h, drv_index, first_time, via_ioctl);
2351	}		/* end for */
2352
2353freeret:
2354	kfree(ld_buff);
2355	h->busy_configuring = 0;
2356	/* We return -1 here to tell the ACU that we have registered/updated
2357	 * all of the drives that we can and to keep it from calling us
2358	 * additional times.
2359	 */
2360	return -1;
2361mem_msg:
2362	dev_err(&h->pdev->dev, "out of memory\n");
2363	h->busy_configuring = 0;
2364	goto freeret;
2365}
2366
2367static void cciss_clear_drive_info(drive_info_struct *drive_info)
2368{
2369	/* zero out the disk size info */
2370	drive_info->nr_blocks = 0;
2371	drive_info->block_size = 0;
2372	drive_info->heads = 0;
2373	drive_info->sectors = 0;
2374	drive_info->cylinders = 0;
2375	drive_info->raid_level = -1;
2376	memset(drive_info->serial_no, 0, sizeof(drive_info->serial_no));
2377	memset(drive_info->model, 0, sizeof(drive_info->model));
2378	memset(drive_info->rev, 0, sizeof(drive_info->rev));
2379	memset(drive_info->vendor, 0, sizeof(drive_info->vendor));
2380	/*
2381	 * don't clear the LUNID though, we need to remember which
2382	 * one this one is.
2383	 */
2384}
2385
2386/* This function will deregister the disk and it's queue from the
2387 * kernel.  It must be called with the controller lock held and the
2388 * drv structures busy_configuring flag set.  It's parameters are:
2389 *
2390 * disk = This is the disk to be deregistered
2391 * drv  = This is the drive_info_struct associated with the disk to be
2392 *        deregistered.  It contains information about the disk used
2393 *        by the driver.
2394 * clear_all = This flag determines whether or not the disk information
2395 *             is going to be completely cleared out and the highest_lun
2396 *             reset.  Sometimes we want to clear out information about
2397 *             the disk in preparation for re-adding it.  In this case
2398 *             the highest_lun should be left unchanged and the LunID
2399 *             should not be cleared.
2400 * via_ioctl
2401 *    This indicates whether we've reached this path via ioctl.
2402 *    This affects the maximum usage count allowed for c0d0 to be messed with.
2403 *    If this path is reached via ioctl(), then the max_usage_count will
2404 *    be 1, as the process calling ioctl() has got to have the device open.
2405 *    If we get here via sysfs, then the max usage count will be zero.
2406*/
2407static int deregister_disk(ctlr_info_t *h, int drv_index,
2408			   int clear_all, int via_ioctl)
2409{
2410	int i;
2411	struct gendisk *disk;
2412	drive_info_struct *drv;
2413	int recalculate_highest_lun;
2414
2415	if (!capable(CAP_SYS_RAWIO))
2416		return -EPERM;
2417
2418	drv = h->drv[drv_index];
2419	disk = h->gendisk[drv_index];
2420
2421	/* make sure logical volume is NOT is use */
2422	if (clear_all || (h->gendisk[0] == disk)) {
2423		if (drv->usage_count > via_ioctl)
2424			return -EBUSY;
2425	} else if (drv->usage_count > 0)
2426		return -EBUSY;
2427
2428	recalculate_highest_lun = (drv == h->drv[h->highest_lun]);
2429
2430	/* invalidate the devices and deregister the disk.  If it is disk
2431	 * zero do not deregister it but just zero out it's values.  This
2432	 * allows us to delete disk zero but keep the controller registered.
2433	 */
2434	if (h->gendisk[0] != disk) {
2435		struct request_queue *q = disk->queue;
2436		if (disk->flags & GENHD_FL_UP) {
2437			cciss_destroy_ld_sysfs_entry(h, drv_index, 0);
2438			del_gendisk(disk);
2439		}
2440		if (q)
2441			blk_cleanup_queue(q);
2442		/* If clear_all is set then we are deleting the logical
2443		 * drive, not just refreshing its info.  For drives
2444		 * other than disk 0 we will call put_disk.  We do not
2445		 * do this for disk 0 as we need it to be able to
2446		 * configure the controller.
2447		 */
2448		if (clear_all){
2449			/* This isn't pretty, but we need to find the
2450			 * disk in our array and NULL our the pointer.
2451			 * This is so that we will call alloc_disk if
2452			 * this index is used again later.
2453			 */
2454			for (i=0; i < CISS_MAX_LUN; i++){
2455				if (h->gendisk[i] == disk) {
2456					h->gendisk[i] = NULL;
2457					break;
2458				}
2459			}
2460			put_disk(disk);
2461		}
2462	} else {
2463		set_capacity(disk, 0);
2464		cciss_clear_drive_info(drv);
2465	}
2466
2467	--h->num_luns;
2468
2469	/* if it was the last disk, find the new hightest lun */
2470	if (clear_all && recalculate_highest_lun) {
2471		int newhighest = -1;
2472		for (i = 0; i <= h->highest_lun; i++) {
2473			/* if the disk has size > 0, it is available */
2474			if (h->drv[i] && h->drv[i]->heads)
2475				newhighest = i;
2476		}
2477		h->highest_lun = newhighest;
2478	}
2479	return 0;
2480}
2481
2482static int fill_cmd(ctlr_info_t *h, CommandList_struct *c, __u8 cmd, void *buff,
2483		size_t size, __u8 page_code, unsigned char *scsi3addr,
2484		int cmd_type)
2485{
2486	u64bit buff_dma_handle;
2487	int status = IO_OK;
2488
2489	c->cmd_type = CMD_IOCTL_PEND;
2490	c->Header.ReplyQueue = 0;
2491	if (buff != NULL) {
2492		c->Header.SGList = 1;
2493		c->Header.SGTotal = 1;
2494	} else {
2495		c->Header.SGList = 0;
2496		c->Header.SGTotal = 0;
2497	}
2498	c->Header.Tag.lower = c->busaddr;
2499	memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
2500
2501	c->Request.Type.Type = cmd_type;
2502	if (cmd_type == TYPE_CMD) {
2503		switch (cmd) {
2504		case CISS_INQUIRY:
2505			/* are we trying to read a vital product page */
2506			if (page_code != 0) {
2507				c->Request.CDB[1] = 0x01;
2508				c->Request.CDB[2] = page_code;
2509			}
2510			c->Request.CDBLen = 6;
2511			c->Request.Type.Attribute = ATTR_SIMPLE;
2512			c->Request.Type.Direction = XFER_READ;
2513			c->Request.Timeout = 0;
2514			c->Request.CDB[0] = CISS_INQUIRY;
2515			c->Request.CDB[4] = size & 0xFF;
2516			break;
2517		case CISS_REPORT_LOG:
2518		case CISS_REPORT_PHYS:
2519			/* Talking to controller so It's a physical command
2520			   mode = 00 target = 0.  Nothing to write.
2521			 */
2522			c->Request.CDBLen = 12;
2523			c->Request.Type.Attribute = ATTR_SIMPLE;
2524			c->Request.Type.Direction = XFER_READ;
2525			c->Request.Timeout = 0;
2526			c->Request.CDB[0] = cmd;
2527			c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
2528			c->Request.CDB[7] = (size >> 16) & 0xFF;
2529			c->Request.CDB[8] = (size >> 8) & 0xFF;
2530			c->Request.CDB[9] = size & 0xFF;
2531			break;
2532
2533		case CCISS_READ_CAPACITY:
2534			c->Request.CDBLen = 10;
2535			c->Request.Type.Attribute = ATTR_SIMPLE;
2536			c->Request.Type.Direction = XFER_READ;
2537			c->Request.Timeout = 0;
2538			c->Request.CDB[0] = cmd;
2539			break;
2540		case CCISS_READ_CAPACITY_16:
2541			c->Request.CDBLen = 16;
2542			c->Request.Type.Attribute = ATTR_SIMPLE;
2543			c->Request.Type.Direction = XFER_READ;
2544			c->Request.Timeout = 0;
2545			c->Request.CDB[0] = cmd;
2546			c->Request.CDB[1] = 0x10;
2547			c->Request.CDB[10] = (size >> 24) & 0xFF;
2548			c->Request.CDB[11] = (size >> 16) & 0xFF;
2549			c->Request.CDB[12] = (size >> 8) & 0xFF;
2550			c->Request.CDB[13] = size & 0xFF;
2551			c->Request.Timeout = 0;
2552			c->Request.CDB[0] = cmd;
2553			break;
2554		case CCISS_CACHE_FLUSH:
2555			c->Request.CDBLen = 12;
2556			c->Request.Type.Attribute = ATTR_SIMPLE;
2557			c->Request.Type.Direction = XFER_WRITE;
2558			c->Request.Timeout = 0;
2559			c->Request.CDB[0] = BMIC_WRITE;
2560			c->Request.CDB[6] = BMIC_CACHE_FLUSH;
2561			break;
2562		case TEST_UNIT_READY:
2563			c->Request.CDBLen = 6;
2564			c->Request.Type.Attribute = ATTR_SIMPLE;
2565			c->Request.Type.Direction = XFER_NONE;
2566			c->Request.Timeout = 0;
2567			break;
2568		default:
2569			dev_warn(&h->pdev->dev, "Unknown Command 0x%c\n", cmd);
2570			return IO_ERROR;
2571		}
2572	} else if (cmd_type == TYPE_MSG) {
2573		switch (cmd) {
2574		case 0:	/* ABORT message */
2575			c->Request.CDBLen = 12;
2576			c->Request.Type.Attribute = ATTR_SIMPLE;
2577			c->Request.Type.Direction = XFER_WRITE;
2578			c->Request.Timeout = 0;
2579			c->Request.CDB[0] = cmd;	/* abort */
2580			c->Request.CDB[1] = 0;	/* abort a command */
2581			/* buff contains the tag of the command to abort */
2582			memcpy(&c->Request.CDB[4], buff, 8);
2583			break;
2584		case 1:	/* RESET message */
2585			c->Request.CDBLen = 16;
2586			c->Request.Type.Attribute = ATTR_SIMPLE;
2587			c->Request.Type.Direction = XFER_NONE;
2588			c->Request.Timeout = 0;
2589			memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
2590			c->Request.CDB[0] = cmd;	/* reset */
2591			c->Request.CDB[1] = 0x03;	/* reset a target */
2592			break;
2593		case 3:	/* No-Op message */
2594			c->Request.CDBLen = 1;
2595			c->Request.Type.Attribute = ATTR_SIMPLE;
2596			c->Request.Type.Direction = XFER_WRITE;
2597			c->Request.Timeout = 0;
2598			c->Request.CDB[0] = cmd;
2599			break;
2600		default:
2601			dev_warn(&h->pdev->dev,
2602				"unknown message type %d\n", cmd);
2603			return IO_ERROR;
2604		}
2605	} else {
2606		dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
2607		return IO_ERROR;
2608	}
2609	/* Fill in the scatter gather information */
2610	if (size > 0) {
2611		buff_dma_handle.val = (__u64) pci_map_single(h->pdev,
2612							     buff, size,
2613							     PCI_DMA_BIDIRECTIONAL);
2614		c->SG[0].Addr.lower = buff_dma_handle.val32.lower;
2615		c->SG[0].Addr.upper = buff_dma_handle.val32.upper;
2616		c->SG[0].Len = size;
2617		c->SG[0].Ext = 0;	/* we are not chaining */
2618	}
2619	return status;
2620}
2621
2622static int check_target_status(ctlr_info_t *h, CommandList_struct *c)
2623{
2624	switch (c->err_info->ScsiStatus) {
2625	case SAM_STAT_GOOD:
2626		return IO_OK;
2627	case SAM_STAT_CHECK_CONDITION:
2628		switch (0xf & c->err_info->SenseInfo[2]) {
2629		case 0: return IO_OK; /* no sense */
2630		case 1: return IO_OK; /* recovered error */
2631		default:
2632			if (check_for_unit_attention(h, c))
2633				return IO_NEEDS_RETRY;
2634			dev_warn(&h->pdev->dev, "cmd 0x%02x "
2635				"check condition, sense key = 0x%02x\n",
2636				c->Request.CDB[0], c->err_info->SenseInfo[2]);
2637		}
2638		break;
2639	default:
2640		dev_warn(&h->pdev->dev, "cmd 0x%02x"
2641			"scsi status = 0x%02x\n",
2642			c->Request.CDB[0], c->err_info->ScsiStatus);
2643		break;
2644	}
2645	return IO_ERROR;
2646}
2647
2648static int process_sendcmd_error(ctlr_info_t *h, CommandList_struct *c)
2649{
2650	int return_status = IO_OK;
2651
2652	if (c->err_info->CommandStatus == CMD_SUCCESS)
2653		return IO_OK;
2654
2655	switch (c->err_info->CommandStatus) {
2656	case CMD_TARGET_STATUS:
2657		return_status = check_target_status(h, c);
2658		break;
2659	case CMD_DATA_UNDERRUN:
2660	case CMD_DATA_OVERRUN:
2661		/* expected for inquiry and report lun commands */
2662		break;
2663	case CMD_INVALID:
2664		dev_warn(&h->pdev->dev, "cmd 0x%02x is "
2665		       "reported invalid\n", c->Request.CDB[0]);
2666		return_status = IO_ERROR;
2667		break;
2668	case CMD_PROTOCOL_ERR:
2669		dev_warn(&h->pdev->dev, "cmd 0x%02x has "
2670		       "protocol error\n", c->Request.CDB[0]);
2671		return_status = IO_ERROR;
2672		break;
2673	case CMD_HARDWARE_ERR:
2674		dev_warn(&h->pdev->dev, "cmd 0x%02x had "
2675		       " hardware error\n", c->Request.CDB[0]);
2676		return_status = IO_ERROR;
2677		break;
2678	case CMD_CONNECTION_LOST:
2679		dev_warn(&h->pdev->dev, "cmd 0x%02x had "
2680		       "connection lost\n", c->Request.CDB[0]);
2681		return_status = IO_ERROR;
2682		break;
2683	case CMD_ABORTED:
2684		dev_warn(&h->pdev->dev, "cmd 0x%02x was "
2685		       "aborted\n", c->Request.CDB[0]);
2686		return_status = IO_ERROR;
2687		break;
2688	case CMD_ABORT_FAILED:
2689		dev_warn(&h->pdev->dev, "cmd 0x%02x reports "
2690		       "abort failed\n", c->Request.CDB[0]);
2691		return_status = IO_ERROR;
2692		break;
2693	case CMD_UNSOLICITED_ABORT:
2694		dev_warn(&h->pdev->dev, "unsolicited abort 0x%02x\n",
2695			c->Request.CDB[0]);
2696		return_status = IO_NEEDS_RETRY;
2697		break;
2698	default:
2699		dev_warn(&h->pdev->dev, "cmd 0x%02x returned "
2700		       "unknown status %x\n", c->Request.CDB[0],
2701		       c->err_info->CommandStatus);
2702		return_status = IO_ERROR;
2703	}
2704	return return_status;
2705}
2706
2707static int sendcmd_withirq_core(ctlr_info_t *h, CommandList_struct *c,
2708	int attempt_retry)
2709{
2710	DECLARE_COMPLETION_ONSTACK(wait);
2711	u64bit buff_dma_handle;
2712	int return_status = IO_OK;
2713
2714resend_cmd2:
2715	c->waiting = &wait;
2716	enqueue_cmd_and_start_io(h, c);
2717
2718	wait_for_completion(&wait);
2719
2720	if (c->err_info->CommandStatus == 0 || !attempt_retry)
2721		goto command_done;
2722
2723	return_status = process_sendcmd_error(h, c);
2724
2725	if (return_status == IO_NEEDS_RETRY &&
2726		c->retry_count < MAX_CMD_RETRIES) {
2727		dev_warn(&h->pdev->dev, "retrying 0x%02x\n",
2728			c->Request.CDB[0]);
2729		c->retry_count++;
2730		/* erase the old error information */
2731		memset(c->err_info, 0, sizeof(ErrorInfo_struct));
2732		return_status = IO_OK;
2733		INIT_COMPLETION(wait);
2734		goto resend_cmd2;
2735	}
2736
2737command_done:
2738	/* unlock the buffers from DMA */
2739	buff_dma_handle.val32.lower = c->SG[0].Addr.lower;
2740	buff_dma_handle.val32.upper = c->SG[0].Addr.upper;
2741	pci_unmap_single(h->pdev, (dma_addr_t) buff_dma_handle.val,
2742			 c->SG[0].Len, PCI_DMA_BIDIRECTIONAL);
2743	return return_status;
2744}
2745
2746static int sendcmd_withirq(ctlr_info_t *h, __u8 cmd, void *buff, size_t size,
2747			   __u8 page_code, unsigned char scsi3addr[],
2748			int cmd_type)
2749{
2750	CommandList_struct *c;
2751	int return_status;
2752
2753	c = cmd_special_alloc(h);
2754	if (!c)
2755		return -ENOMEM;
2756	return_status = fill_cmd(h, c, cmd, buff, size, page_code,
2757		scsi3addr, cmd_type);
2758	if (return_status == IO_OK)
2759		return_status = sendcmd_withirq_core(h, c, 1);
2760
2761	cmd_special_free(h, c);
2762	return return_status;
2763}
2764
2765static void cciss_geometry_inquiry(ctlr_info_t *h, int logvol,
2766				   sector_t total_size,
2767				   unsigned int block_size,
2768				   InquiryData_struct *inq_buff,
2769				   drive_info_struct *drv)
2770{
2771	int return_code;
2772	unsigned long t;
2773	unsigned char scsi3addr[8];
2774
2775	memset(inq_buff, 0, sizeof(InquiryData_struct));
2776	log_unit_to_scsi3addr(h, scsi3addr, logvol);
2777	return_code = sendcmd_withirq(h, CISS_INQUIRY, inq_buff,
2778			sizeof(*inq_buff), 0xC1, scsi3addr, TYPE_CMD);
2779	if (return_code == IO_OK) {
2780		if (inq_buff->data_byte[8] == 0xFF) {
2781			dev_warn(&h->pdev->dev,
2782			       "reading geometry failed, volume "
2783			       "does not support reading geometry\n");
2784			drv->heads = 255;
2785			drv->sectors = 32;	/* Sectors per track */
2786			drv->cylinders = total_size + 1;
2787			drv->raid_level = RAID_UNKNOWN;
2788		} else {
2789			drv->heads = inq_buff->data_byte[6];
2790			drv->sectors = inq_buff->data_byte[7];
2791			drv->cylinders = (inq_buff->data_byte[4] & 0xff) << 8;
2792			drv->cylinders += inq_buff->data_byte[5];
2793			drv->raid_level = inq_buff->data_byte[8];
2794		}
2795		drv->block_size = block_size;
2796		drv->nr_blocks = total_size + 1;
2797		t = drv->heads * drv->sectors;
2798		if (t > 1) {
2799			sector_t real_size = total_size + 1;
2800			unsigned long rem = sector_div(real_size, t);
2801			if (rem)
2802				real_size++;
2803			drv->cylinders = real_size;
2804		}
2805	} else {		/* Get geometry failed */
2806		dev_warn(&h->pdev->dev, "reading geometry failed\n");
2807	}
2808}
2809
2810static void
2811cciss_read_capacity(ctlr_info_t *h, int logvol, sector_t *total_size,
2812		    unsigned int *block_size)
2813{
2814	ReadCapdata_struct *buf;
2815	int return_code;
2816	unsigned char scsi3addr[8];
2817
2818	buf = kzalloc(sizeof(ReadCapdata_struct), GFP_KERNEL);
2819	if (!buf) {
2820		dev_warn(&h->pdev->dev, "out of memory\n");
2821		return;
2822	}
2823
2824	log_unit_to_scsi3addr(h, scsi3addr, logvol);
2825	return_code = sendcmd_withirq(h, CCISS_READ_CAPACITY, buf,
2826		sizeof(ReadCapdata_struct), 0, scsi3addr, TYPE_CMD);
2827	if (return_code == IO_OK) {
2828		*total_size = be32_to_cpu(*(__be32 *) buf->total_size);
2829		*block_size = be32_to_cpu(*(__be32 *) buf->block_size);
2830	} else {		/* read capacity command failed */
2831		dev_warn(&h->pdev->dev, "read capacity failed\n");
2832		*total_size = 0;
2833		*block_size = BLOCK_SIZE;
2834	}
2835	kfree(buf);
2836}
2837
2838static void cciss_read_capacity_16(ctlr_info_t *h, int logvol,
2839	sector_t *total_size, unsigned int *block_size)
2840{
2841	ReadCapdata_struct_16 *buf;
2842	int return_code;
2843	unsigned char scsi3addr[8];
2844
2845	buf = kzalloc(sizeof(ReadCapdata_struct_16), GFP_KERNEL);
2846	if (!buf) {
2847		dev_warn(&h->pdev->dev, "out of memory\n");
2848		return;
2849	}
2850
2851	log_unit_to_scsi3addr(h, scsi3addr, logvol);
2852	return_code = sendcmd_withirq(h, CCISS_READ_CAPACITY_16,
2853		buf, sizeof(ReadCapdata_struct_16),
2854			0, scsi3addr, TYPE_CMD);
2855	if (return_code == IO_OK) {
2856		*total_size = be64_to_cpu(*(__be64 *) buf->total_size);
2857		*block_size = be32_to_cpu(*(__be32 *) buf->block_size);
2858	} else {		/* read capacity command failed */
2859		dev_warn(&h->pdev->dev, "read capacity failed\n");
2860		*total_size = 0;
2861		*block_size = BLOCK_SIZE;
2862	}
2863	dev_info(&h->pdev->dev, "      blocks= %llu block_size= %d\n",
2864	       (unsigned long long)*total_size+1, *block_size);
2865	kfree(buf);
2866}
2867
2868static int cciss_revalidate(struct gendisk *disk)
2869{
2870	ctlr_info_t *h = get_host(disk);
2871	drive_info_struct *drv = get_drv(disk);
2872	int logvol;
2873	int FOUND = 0;
2874	unsigned int block_size;
2875	sector_t total_size;
2876	InquiryData_struct *inq_buff = NULL;
2877
2878	for (logvol = 0; logvol < CISS_MAX_LUN; logvol++) {
2879		if (memcmp(h->drv[logvol]->LunID, drv->LunID,
2880			sizeof(drv->LunID)) == 0) {
2881			FOUND = 1;
2882			break;
2883		}
2884	}
2885
2886	if (!FOUND)
2887		return 1;
2888
2889	inq_buff = kmalloc(sizeof(InquiryData_struct), GFP_KERNEL);
2890	if (inq_buff == NULL) {
2891		dev_warn(&h->pdev->dev, "out of memory\n");
2892		return 1;
2893	}
2894	if (h->cciss_read == CCISS_READ_10) {
2895		cciss_read_capacity(h, logvol,
2896					&total_size, &block_size);
2897	} else {
2898		cciss_read_capacity_16(h, logvol,
2899					&total_size, &block_size);
2900	}
2901	cciss_geometry_inquiry(h, logvol, total_size, block_size,
2902			       inq_buff, drv);
2903
2904	blk_queue_logical_block_size(drv->queue, drv->block_size);
2905	set_capacity(disk, drv->nr_blocks);
2906
2907	kfree(inq_buff);
2908	return 0;
2909}
2910
2911/*
2912 * Map (physical) PCI mem into (virtual) kernel space
2913 */
2914static void __iomem *remap_pci_mem(ulong base, ulong size)
2915{
2916	ulong page_base = ((ulong) base) & PAGE_MASK;
2917	ulong page_offs = ((ulong) base) - page_base;
2918	void __iomem *page_remapped = ioremap(page_base, page_offs + size);
2919
2920	return page_remapped ? (page_remapped + page_offs) : NULL;
2921}
2922
2923/*
2924 * Takes jobs of the Q and sends them to the hardware, then puts it on
2925 * the Q to wait for completion.
2926 */
2927static void start_io(ctlr_info_t *h)
2928{
2929	CommandList_struct *c;
2930
2931	while (!hlist_empty(&h->reqQ)) {
2932		c = hlist_entry(h->reqQ.first, CommandList_struct, list);
2933		/* can't do anything if fifo is full */
2934		if ((h->access.fifo_full(h))) {
2935			dev_warn(&h->pdev->dev, "fifo full\n");
2936			break;
2937		}
2938
2939		/* Get the first entry from the Request Q */
2940		removeQ(c);
2941		h->Qdepth--;
2942
2943		/* Tell the controller execute command */
2944		h->access.submit_command(h, c);
2945
2946		/* Put job onto the completed Q */
2947		addQ(&h->cmpQ, c);
2948	}
2949}
2950
2951/* Assumes that h->lock is held. */
2952/* Zeros out the error record and then resends the command back */
2953/* to the controller */
2954static inline void resend_cciss_cmd(ctlr_info_t *h, CommandList_struct *c)
2955{
2956	/* erase the old error information */
2957	memset(c->err_info, 0, sizeof(ErrorInfo_struct));
2958
2959	/* add it to software queue and then send it to the controller */
2960	addQ(&h->reqQ, c);
2961	h->Qdepth++;
2962	if (h->Qdepth > h->maxQsinceinit)
2963		h->maxQsinceinit = h->Qdepth;
2964
2965	start_io(h);
2966}
2967
2968static inline unsigned int make_status_bytes(unsigned int scsi_status_byte,
2969	unsigned int msg_byte, unsigned int host_byte,
2970	unsigned int driver_byte)
2971{
2972	/* inverse of macros in scsi.h */
2973	return (scsi_status_byte & 0xff) |
2974		((msg_byte & 0xff) << 8) |
2975		((host_byte & 0xff) << 16) |
2976		((driver_byte & 0xff) << 24);
2977}
2978
2979static inline int evaluate_target_status(ctlr_info_t *h,
2980			CommandList_struct *cmd, int *retry_cmd)
2981{
2982	unsigned char sense_key;
2983	unsigned char status_byte, msg_byte, host_byte, driver_byte;
2984	int error_value;
2985
2986	*retry_cmd = 0;
2987	/* If we get in here, it means we got "target status", that is, scsi status */
2988	status_byte = cmd->err_info->ScsiStatus;
2989	driver_byte = DRIVER_OK;
2990	msg_byte = cmd->err_info->CommandStatus; /* correct?  seems too device specific */
2991
2992	if (cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC)
2993		host_byte = DID_PASSTHROUGH;
2994	else
2995		host_byte = DID_OK;
2996
2997	error_value = make_status_bytes(status_byte, msg_byte,
2998		host_byte, driver_byte);
2999
3000	if (cmd->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION) {
3001		if (cmd->rq->cmd_type != REQ_TYPE_BLOCK_PC)
3002			dev_warn(&h->pdev->dev, "cmd %p "
3003			       "has SCSI Status 0x%x\n",
3004			       cmd, cmd->err_info->ScsiStatus);
3005		return error_value;
3006	}
3007
3008	/* check the sense key */
3009	sense_key = 0xf & cmd->err_info->SenseInfo[2];
3010	/* no status or recovered error */
3011	if (((sense_key == 0x0) || (sense_key == 0x1)) &&
3012	    (cmd->rq->cmd_type != REQ_TYPE_BLOCK_PC))
3013		error_value = 0;
3014
3015	if (check_for_unit_attention(h, cmd)) {
3016		*retry_cmd = !(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC);
3017		return 0;
3018	}
3019
3020	/* Not SG_IO or similar? */
3021	if (cmd->rq->cmd_type != REQ_TYPE_BLOCK_PC) {
3022		if (error_value != 0)
3023			dev_warn(&h->pdev->dev, "cmd %p has CHECK CONDITION"
3024			       " sense key = 0x%x\n", cmd, sense_key);
3025		return error_value;
3026	}
3027
3028	/* SG_IO or similar, copy sense data back */
3029	if (cmd->rq->sense) {
3030		if (cmd->rq->sense_len > cmd->err_info->SenseLen)
3031			cmd->rq->sense_len = cmd->err_info->SenseLen;
3032		memcpy(cmd->rq->sense, cmd->err_info->SenseInfo,
3033			cmd->rq->sense_len);
3034	} else
3035		cmd->rq->sense_len = 0;
3036
3037	return error_value;
3038}
3039
3040/* checks the status of the job and calls complete buffers to mark all
3041 * buffers for the completed job. Note that this function does not need
3042 * to hold the hba/queue lock.
3043 */
3044static inline void complete_command(ctlr_info_t *h, CommandList_struct *cmd,
3045				    int timeout)
3046{
3047	int retry_cmd = 0;
3048	struct request *rq = cmd->rq;
3049
3050	rq->errors = 0;
3051
3052	if (timeout)
3053		rq->errors = make_status_bytes(0, 0, 0, DRIVER_TIMEOUT);
3054
3055	if (cmd->err_info->CommandStatus == 0)	/* no error has occurred */
3056		goto after_error_processing;
3057
3058	switch (cmd->err_info->CommandStatus) {
3059	case CMD_TARGET_STATUS:
3060		rq->errors = evaluate_target_status(h, cmd, &retry_cmd);
3061		break;
3062	case CMD_DATA_UNDERRUN:
3063		if (cmd->rq->cmd_type == REQ_TYPE_FS) {
3064			dev_warn(&h->pdev->dev, "cmd %p has"
3065			       " completed with data underrun "
3066			       "reported\n", cmd);
3067			cmd->rq->resid_len = cmd->err_info->ResidualCnt;
3068		}
3069		break;
3070	case CMD_DATA_OVERRUN:
3071		if (cmd->rq->cmd_type == REQ_TYPE_FS)
3072			dev_warn(&h->pdev->dev, "cciss: cmd %p has"
3073			       " completed with data overrun "
3074			       "reported\n", cmd);
3075		break;
3076	case CMD_INVALID:
3077		dev_warn(&h->pdev->dev, "cciss: cmd %p is "
3078		       "reported invalid\n", cmd);
3079		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3080			cmd->err_info->CommandStatus, DRIVER_OK,
3081			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3082				DID_PASSTHROUGH : DID_ERROR);
3083		break;
3084	case CMD_PROTOCOL_ERR:
3085		dev_warn(&h->pdev->dev, "cciss: cmd %p has "
3086		       "protocol error\n", cmd);
3087		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3088			cmd->err_info->CommandStatus, DRIVER_OK,
3089			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3090				DID_PASSTHROUGH : DID_ERROR);
3091		break;
3092	case CMD_HARDWARE_ERR:
3093		dev_warn(&h->pdev->dev, "cciss: cmd %p had "
3094		       " hardware error\n", cmd);
3095		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3096			cmd->err_info->CommandStatus, DRIVER_OK,
3097			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3098				DID_PASSTHROUGH : DID_ERROR);
3099		break;
3100	case CMD_CONNECTION_LOST:
3101		dev_warn(&h->pdev->dev, "cciss: cmd %p had "
3102		       "connection lost\n", cmd);
3103		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3104			cmd->err_info->CommandStatus, DRIVER_OK,
3105			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3106				DID_PASSTHROUGH : DID_ERROR);
3107		break;
3108	case CMD_ABORTED:
3109		dev_warn(&h->pdev->dev, "cciss: cmd %p was "
3110		       "aborted\n", cmd);
3111		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3112			cmd->err_info->CommandStatus, DRIVER_OK,
3113			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3114				DID_PASSTHROUGH : DID_ABORT);
3115		break;
3116	case CMD_ABORT_FAILED:
3117		dev_warn(&h->pdev->dev, "cciss: cmd %p reports "
3118		       "abort failed\n", cmd);
3119		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3120			cmd->err_info->CommandStatus, DRIVER_OK,
3121			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3122				DID_PASSTHROUGH : DID_ERROR);
3123		break;
3124	case CMD_UNSOLICITED_ABORT:
3125		dev_warn(&h->pdev->dev, "cciss%d: unsolicited "
3126		       "abort %p\n", h->ctlr, cmd);
3127		if (cmd->retry_count < MAX_CMD_RETRIES) {
3128			retry_cmd = 1;
3129			dev_warn(&h->pdev->dev, "retrying %p\n", cmd);
3130			cmd->retry_count++;
3131		} else
3132			dev_warn(&h->pdev->dev,
3133				"%p retried too many times\n", cmd);
3134		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3135			cmd->err_info->CommandStatus, DRIVER_OK,
3136			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3137				DID_PASSTHROUGH : DID_ABORT);
3138		break;
3139	case CMD_TIMEOUT:
3140		dev_warn(&h->pdev->dev, "cmd %p timedout\n", cmd);
3141		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3142			cmd->err_info->CommandStatus, DRIVER_OK,
3143			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3144				DID_PASSTHROUGH : DID_ERROR);
3145		break;
3146	default:
3147		dev_warn(&h->pdev->dev, "cmd %p returned "
3148		       "unknown status %x\n", cmd,
3149		       cmd->err_info->CommandStatus);
3150		rq->errors = make_status_bytes(SAM_STAT_GOOD,
3151			cmd->err_info->CommandStatus, DRIVER_OK,
3152			(cmd->rq->cmd_type == REQ_TYPE_BLOCK_PC) ?
3153				DID_PASSTHROUGH : DID_ERROR);
3154	}
3155
3156after_error_processing:
3157
3158	/* We need to return this command */
3159	if (retry_cmd) {
3160		resend_cciss_cmd(h, cmd);
3161		return;
3162	}
3163	cmd->rq->completion_data = cmd;
3164	blk_complete_request(cmd->rq);
3165}
3166
3167static inline u32 cciss_tag_contains_index(u32 tag)
3168{
3169#define DIRECT_LOOKUP_BIT 0x10
3170	return tag & DIRECT_LOOKUP_BIT;
3171}
3172
3173static inline u32 cciss_tag_to_index(u32 tag)
3174{
3175#define DIRECT_LOOKUP_SHIFT 5
3176	return tag >> DIRECT_LOOKUP_SHIFT;
3177}
3178
3179static inline u32 cciss_tag_discard_error_bits(u32 tag)
3180{
3181#define CCISS_ERROR_BITS 0x03
3182	return tag & ~CCISS_ERROR_BITS;
3183}
3184
3185static inline void cciss_mark_tag_indexed(u32 *tag)
3186{
3187	*tag |= DIRECT_LOOKUP_BIT;
3188}
3189
3190static inline void cciss_set_tag_index(u32 *tag, u32 index)
3191{
3192	*tag |= (index << DIRECT_LOOKUP_SHIFT);
3193}
3194
3195/*
3196 * Get a request and submit it to the controller.
3197 */
3198static void do_cciss_request(struct request_queue *q)
3199{
3200	ctlr_info_t *h = q->queuedata;
3201	CommandList_struct *c;
3202	sector_t start_blk;
3203	int seg;
3204	struct request *creq;
3205	u64bit temp64;
3206	struct scatterlist *tmp_sg;
3207	SGDescriptor_struct *curr_sg;
3208	drive_info_struct *drv;
3209	int i, dir;
3210	int sg_index = 0;
3211	int chained = 0;
3212
3213	/* We call start_io here in case there is a command waiting on the
3214	 * queue that has not been sent.
3215	 */
3216	if (blk_queue_plugged(q))
3217		goto startio;
3218
3219      queue:
3220	creq = blk_peek_request(q);
3221	if (!creq)
3222		goto startio;
3223
3224	BUG_ON(creq->nr_phys_segments > h->maxsgentries);
3225
3226	c = cmd_alloc(h);
3227	if (!c)
3228		goto full;
3229
3230	blk_start_request(creq);
3231
3232	tmp_sg = h->scatter_list[c->cmdindex];
3233	spin_unlock_irq(q->queue_lock);
3234
3235	c->cmd_type = CMD_RWREQ;
3236	c->rq = creq;
3237
3238	/* fill in the request */
3239	drv = creq->rq_disk->private_data;
3240	c->Header.ReplyQueue = 0;	/* unused in simple mode */
3241	/* got command from pool, so use the command block index instead */
3242	/* for direct lookups. */
3243	/* The first 2 bits are reserved for controller error reporting. */
3244	cciss_set_tag_index(&c->Header.Tag.lower, c->cmdindex);
3245	cciss_mark_tag_indexed(&c->Header.Tag.lower);
3246	memcpy(&c->Header.LUN, drv->LunID, sizeof(drv->LunID));
3247	c->Request.CDBLen = 10;	/* 12 byte commands not in FW yet; */
3248	c->Request.Type.Type = TYPE_CMD;	/* It is a command. */
3249	c->Request.Type.Attribute = ATTR_SIMPLE;
3250	c->Request.Type.Direction =
3251	    (rq_data_dir(creq) == READ) ? XFER_READ : XFER_WRITE;
3252	c->Request.Timeout = 0;	/* Don't time out */
3253	c->Request.CDB[0] =
3254	    (rq_data_dir(creq) == READ) ? h->cciss_read : h->cciss_write;
3255	start_blk = blk_rq_pos(creq);
3256	dev_dbg(&h->pdev->dev, "sector =%d nr_sectors=%d\n",
3257	       (int)blk_rq_pos(creq), (int)blk_rq_sectors(creq));
3258	sg_init_table(tmp_sg, h->maxsgentries);
3259	seg = blk_rq_map_sg(q, creq, tmp_sg);
3260
3261	/* get the DMA records for the setup */
3262	if (c->Request.Type.Direction == XFER_READ)
3263		dir = PCI_DMA_FROMDEVICE;
3264	else
3265		dir = PCI_DMA_TODEVICE;
3266
3267	curr_sg = c->SG;
3268	sg_index = 0;
3269	chained = 0;
3270
3271	for (i = 0; i < seg; i++) {
3272		if (((sg_index+1) == (h->max_cmd_sgentries)) &&
3273			!chained && ((seg - i) > 1)) {
3274			/* Point to next chain block. */
3275			curr_sg = h->cmd_sg_list[c->cmdindex];
3276			sg_index = 0;
3277			chained = 1;
3278		}
3279		curr_sg[sg_index].Len = tmp_sg[i].length;
3280		temp64.val = (__u64) pci_map_page(h->pdev, sg_page(&tmp_sg[i]),
3281						tmp_sg[i].offset,
3282						tmp_sg[i].length, dir);
3283		curr_sg[sg_index].Addr.lower = temp64.val32.lower;
3284		curr_sg[sg_index].Addr.upper = temp64.val32.upper;
3285		curr_sg[sg_index].Ext = 0;  /* we are not chaining */
3286		++sg_index;
3287	}
3288	if (chained)
3289		cciss_map_sg_chain_block(h, c, h->cmd_sg_list[c->cmdindex],
3290			(seg - (h->max_cmd_sgentries - 1)) *
3291				sizeof(SGDescriptor_struct));
3292
3293	/* track how many SG entries we are using */
3294	if (seg > h->maxSG)
3295		h->maxSG = seg;
3296
3297	dev_dbg(&h->pdev->dev, "Submitting %u sectors in %d segments "
3298			"chained[%d]\n",
3299			blk_rq_sectors(creq), seg, chained);
3300
3301	c->Header.SGTotal = seg + chained;
3302	if (seg <= h->max_cmd_sgentries)
3303		c->Header.SGList = c->Header.SGTotal;
3304	else
3305		c->Header.SGList = h->max_cmd_sgentries;
3306	set_performant_mode(h, c);
3307
3308	if (likely(creq->cmd_type == REQ_TYPE_FS)) {
3309		if(h->cciss_read == CCISS_READ_10) {
3310			c->Request.CDB[1] = 0;
3311			c->Request.CDB[2] = (start_blk >> 24) & 0xff; /* MSB */
3312			c->Request.CDB[3] = (start_blk >> 16) & 0xff;
3313			c->Request.CDB[4] = (start_blk >> 8) & 0xff;
3314			c->Request.CDB[5] = start_blk & 0xff;
3315			c->Request.CDB[6] = 0; /* (sect >> 24) & 0xff; MSB */
3316			c->Request.CDB[7] = (blk_rq_sectors(creq) >> 8) & 0xff;
3317			c->Request.CDB[8] = blk_rq_sectors(creq) & 0xff;
3318			c->Request.CDB[9] = c->Request.CDB[11] = c->Request.CDB[12] = 0;
3319		} else {
3320			u32 upper32 = upper_32_bits(start_blk);
3321
3322			c->Request.CDBLen = 16;
3323			c->Request.CDB[1]= 0;
3324			c->Request.CDB[2]= (upper32 >> 24) & 0xff; /* MSB */
3325			c->Request.CDB[3]= (upper32 >> 16) & 0xff;
3326			c->Request.CDB[4]= (upper32 >>  8) & 0xff;
3327			c->Request.CDB[5]= upper32 & 0xff;
3328			c->Request.CDB[6]= (start_blk >> 24) & 0xff;
3329			c->Request.CDB[7]= (start_blk >> 16) & 0xff;
3330			c->Request.CDB[8]= (start_blk >>  8) & 0xff;
3331			c->Request.CDB[9]= start_blk & 0xff;
3332			c->Request.CDB[10]= (blk_rq_sectors(creq) >> 24) & 0xff;
3333			c->Request.CDB[11]= (blk_rq_sectors(creq) >> 16) & 0xff;
3334			c->Request.CDB[12]= (blk_rq_sectors(creq) >>  8) & 0xff;
3335			c->Request.CDB[13]= blk_rq_sectors(creq) & 0xff;
3336			c->Request.CDB[14] = c->Request.CDB[15] = 0;
3337		}
3338	} else if (creq->cmd_type == REQ_TYPE_BLOCK_PC) {
3339		c->Request.CDBLen = creq->cmd_len;
3340		memcpy(c->Request.CDB, creq->cmd, BLK_MAX_CDB);
3341	} else {
3342		dev_warn(&h->pdev->dev, "bad request type %d\n",
3343			creq->cmd_type);
3344		BUG();
3345	}
3346
3347	spin_lock_irq(q->queue_lock);
3348
3349	addQ(&h->reqQ, c);
3350	h->Qdepth++;
3351	if (h->Qdepth > h->maxQsinceinit)
3352		h->maxQsinceinit = h->Qdepth;
3353
3354	goto queue;
3355full:
3356	blk_stop_queue(q);
3357startio:
3358	/* We will already have the driver lock here so not need
3359	 * to lock it.
3360	 */
3361	start_io(h);
3362}
3363
3364static inline unsigned long get_next_completion(ctlr_info_t *h)
3365{
3366	return h->access.command_completed(h);
3367}
3368
3369static inline int interrupt_pending(ctlr_info_t *h)
3370{
3371	return h->access.intr_pending(h);
3372}
3373
3374static inline long interrupt_not_for_us(ctlr_info_t *h)
3375{
3376	return ((h->access.intr_pending(h) == 0) ||
3377		(h->interrupts_enabled == 0));
3378}
3379
3380static inline int bad_tag(ctlr_info_t *h, u32 tag_index,
3381			u32 raw_tag)
3382{
3383	if (unlikely(tag_index >= h->nr_cmds)) {
3384		dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
3385		return 1;
3386	}
3387	return 0;
3388}
3389
3390static inline void finish_cmd(ctlr_info_t *h, CommandList_struct *c,
3391				u32 raw_tag)
3392{
3393	removeQ(c);
3394	if (likely(c->cmd_type == CMD_RWREQ))
3395		complete_command(h, c, 0);
3396	else if (c->cmd_type == CMD_IOCTL_PEND)
3397		complete(c->waiting);
3398#ifdef CONFIG_CISS_SCSI_TAPE
3399	else if (c->cmd_type == CMD_SCSI)
3400		complete_scsi_command(c, 0, raw_tag);
3401#endif
3402}
3403
3404static inline u32 next_command(ctlr_info_t *h)
3405{
3406	u32 a;
3407
3408	if (unlikely(h->transMethod != CFGTBL_Trans_Performant))
3409		return h->access.command_completed(h);
3410
3411	if ((*(h->reply_pool_head) & 1) == (h->reply_pool_wraparound)) {
3412		a = *(h->reply_pool_head); /* Next cmd in ring buffer */
3413		(h->reply_pool_head)++;
3414		h->commands_outstanding--;
3415	} else {
3416		a = FIFO_EMPTY;
3417	}
3418	/* Check for wraparound */
3419	if (h->reply_pool_head == (h->reply_pool + h->max_commands)) {
3420		h->reply_pool_head = h->reply_pool;
3421		h->reply_pool_wraparound ^= 1;
3422	}
3423	return a;
3424}
3425
3426/* process completion of an indexed ("direct lookup") command */
3427static inline u32 process_indexed_cmd(ctlr_info_t *h, u32 raw_tag)
3428{
3429	u32 tag_index;
3430	CommandList_struct *c;
3431
3432	tag_index = cciss_tag_to_index(raw_tag);
3433	if (bad_tag(h, tag_index, raw_tag))
3434		return next_command(h);
3435	c = h->cmd_pool + tag_index;
3436	finish_cmd(h, c, raw_tag);
3437	return next_command(h);
3438}
3439
3440/* process completion of a non-indexed command */
3441static inline u32 process_nonindexed_cmd(ctlr_info_t *h, u32 raw_tag)
3442{
3443	u32 tag;
3444	CommandList_struct *c = NULL;
3445	struct hlist_node *tmp;
3446	__u32 busaddr_masked, tag_masked;
3447
3448	tag = cciss_tag_discard_error_bits(raw_tag);
3449	hlist_for_each_entry(c, tmp, &h->cmpQ, list) {
3450		busaddr_masked = cciss_tag_discard_error_bits(c->busaddr);
3451		tag_masked = cciss_tag_discard_error_bits(tag);
3452		if (busaddr_masked == tag_masked) {
3453			finish_cmd(h, c, raw_tag);
3454			return next_command(h);
3455		}
3456	}
3457	bad_tag(h, h->nr_cmds + 1, raw_tag);
3458	return next_command(h);
3459}
3460
3461static irqreturn_t do_cciss_intx(int irq, void *dev_id)
3462{
3463	ctlr_info_t *h = dev_id;
3464	unsigned long flags;
3465	u32 raw_tag;
3466
3467	if (interrupt_not_for_us(h))
3468		return IRQ_NONE;
3469	spin_lock_irqsave(&h->lock, flags);
3470	while (interrupt_pending(h)) {
3471		raw_tag = get_next_completion(h);
3472		while (raw_tag != FIFO_EMPTY) {
3473			if (cciss_tag_contains_index(raw_tag))
3474				raw_tag = process_indexed_cmd(h, raw_tag);
3475			else
3476				raw_tag = process_nonindexed_cmd(h, raw_tag);
3477		}
3478	}
3479	spin_unlock_irqrestore(&h->lock, flags);
3480	return IRQ_HANDLED;
3481}
3482
3483/* Add a second interrupt handler for MSI/MSI-X mode. In this mode we never
3484 * check the interrupt pending register because it is not set.
3485 */
3486static irqreturn_t do_cciss_msix_intr(int irq, void *dev_id)
3487{
3488	ctlr_info_t *h = dev_id;
3489	unsigned long flags;
3490	u32 raw_tag;
3491
3492	spin_lock_irqsave(&h->lock, flags);
3493	raw_tag = get_next_completion(h);
3494	while (raw_tag != FIFO_EMPTY) {
3495		if (cciss_tag_contains_index(raw_tag))
3496			raw_tag = process_indexed_cmd(h, raw_tag);
3497		else
3498			raw_tag = process_nonindexed_cmd(h, raw_tag);
3499	}
3500	spin_unlock_irqrestore(&h->lock, flags);
3501	return IRQ_HANDLED;
3502}
3503
3504/**
3505 * add_to_scan_list() - add controller to rescan queue
3506 * @h:		      Pointer to the controller.
3507 *
3508 * Adds the controller to the rescan queue if not already on the queue.
3509 *
3510 * returns 1 if added to the queue, 0 if skipped (could be on the
3511 * queue already, or the controller could be initializing or shutting
3512 * down).
3513 **/
3514static int add_to_scan_list(struct ctlr_info *h)
3515{
3516	struct ctlr_info *test_h;
3517	int found = 0;
3518	int ret = 0;
3519
3520	if (h->busy_initializing)
3521		return 0;
3522
3523	if (!mutex_trylock(&h->busy_shutting_down))
3524		return 0;
3525
3526	mutex_lock(&scan_mutex);
3527	list_for_each_entry(test_h, &scan_q, scan_list) {
3528		if (test_h == h) {
3529			found = 1;
3530			break;
3531		}
3532	}
3533	if (!found && !h->busy_scanning) {
3534		INIT_COMPLETION(h->scan_wait);
3535		list_add_tail(&h->scan_list, &scan_q);
3536		ret = 1;
3537	}
3538	mutex_unlock(&scan_mutex);
3539	mutex_unlock(&h->busy_shutting_down);
3540
3541	return ret;
3542}
3543
3544/**
3545 * remove_from_scan_list() - remove controller from rescan queue
3546 * @h:			   Pointer to the controller.
3547 *
3548 * Removes the controller from the rescan queue if present. Blocks if
3549 * the controller is currently conducting a rescan.  The controller
3550 * can be in one of three states:
3551 * 1. Doesn't need a scan
3552 * 2. On the scan list, but not scanning yet (we remove it)
3553 * 3. Busy scanning (and not on the list). In this case we want to wait for
3554 *    the scan to complete to make sure the scanning thread for this
3555 *    controller is completely idle.
3556 **/
3557static void remove_from_scan_list(struct ctlr_info *h)
3558{
3559	struct ctlr_info *test_h, *tmp_h;
3560
3561	mutex_lock(&scan_mutex);
3562	list_for_each_entry_safe(test_h, tmp_h, &scan_q, scan_list) {
3563		if (test_h == h) { /* state 2. */
3564			list_del(&h->scan_list);
3565			complete_all(&h->scan_wait);
3566			mutex_unlock(&scan_mutex);
3567			return;
3568		}
3569	}
3570	if (h->busy_scanning) { /* state 3. */
3571		mutex_unlock(&scan_mutex);
3572		wait_for_completion(&h->scan_wait);
3573	} else { /* state 1, nothing to do. */
3574		mutex_unlock(&scan_mutex);
3575	}
3576}
3577
3578/**
3579 * scan_thread() - kernel thread used to rescan controllers
3580 * @data:	 Ignored.
3581 *
3582 * A kernel thread used scan for drive topology changes on
3583 * controllers. The thread processes only one controller at a time
3584 * using a queue.  Controllers are added to the queue using
3585 * add_to_scan_list() and removed from the queue either after done
3586 * processing or using remove_from_scan_list().
3587 *
3588 * returns 0.
3589 **/
3590static int scan_thread(void *data)
3591{
3592	struct ctlr_info *h;
3593
3594	while (1) {
3595		set_current_state(TASK_INTERRUPTIBLE);
3596		schedule();
3597		if (kthread_should_stop())
3598			break;
3599
3600		while (1) {
3601			mutex_lock(&scan_mutex);
3602			if (list_empty(&scan_q)) {
3603				mutex_unlock(&scan_mutex);
3604				break;
3605			}
3606
3607			h = list_entry(scan_q.next,
3608				       struct ctlr_info,
3609				       scan_list);
3610			list_del(&h->scan_list);
3611			h->busy_scanning = 1;
3612			mutex_unlock(&scan_mutex);
3613
3614			rebuild_lun_table(h, 0, 0);
3615			complete_all(&h->scan_wait);
3616			mutex_lock(&scan_mutex);
3617			h->busy_scanning = 0;
3618			mutex_unlock(&scan_mutex);
3619		}
3620	}
3621
3622	return 0;
3623}
3624
3625static int check_for_unit_attention(ctlr_info_t *h, CommandList_struct *c)
3626{
3627	if (c->err_info->SenseInfo[2] != UNIT_ATTENTION)
3628		return 0;
3629
3630	switch (c->err_info->SenseInfo[12]) {
3631	case STATE_CHANGED:
3632		dev_warn(&h->pdev->dev, "a state change "
3633			"detected, command retried\n");
3634		return 1;
3635	break;
3636	case LUN_FAILED:
3637		dev_warn(&h->pdev->dev, "LUN failure "
3638			"detected, action required\n");
3639		return 1;
3640	break;
3641	case REPORT_LUNS_CHANGED:
3642		dev_warn(&h->pdev->dev, "report LUN data changed\n");
3643	/*
3644	 * Here, we could call add_to_scan_list and wake up the scan thread,
3645	 * except that it's quite likely that we will get more than one
3646	 * REPORT_LUNS_CHANGED condition in quick succession, which means
3647	 * that those which occur after the first one will likely happen
3648	 * *during* the scan_thread's rescan.  And the rescan code is not
3649	 * robust enough to restart in the middle, undoing what it has already
3650	 * done, and it's not clear that it's even possible to do this, since
3651	 * part of what it does is notify the block layer, which starts
3652	 * doing it's own i/o to read partition tables and so on, and the
3653	 * driver doesn't have visibility to know what might need undoing.
3654	 * In any event, if possible, it is horribly complicated to get right
3655	 * so we just don't do it for now.
3656	 *
3657	 * Note: this REPORT_LUNS_CHANGED condition only occurs on the MSA2012.
3658	 */
3659		return 1;
3660	break;
3661	case POWER_OR_RESET:
3662		dev_warn(&h->pdev->dev,
3663			"a power on or device reset detected\n");
3664		return 1;
3665	break;
3666	case UNIT_ATTENTION_CLEARED:
3667		dev_warn(&h->pdev->dev,
3668			"unit attention cleared by another initiator\n");
3669		return 1;
3670	break;
3671	default:
3672		dev_warn(&h->pdev->dev, "unknown unit attention detected\n");
3673		return 1;
3674	}
3675}
3676
3677/*
3678 *  We cannot read the structure directly, for portability we must use
3679 *   the io functions.
3680 *   This is for debug only.
3681 */
3682static void print_cfg_table(ctlr_info_t *h)
3683{
3684	int i;
3685	char temp_name[17];
3686	CfgTable_struct *tb = h->cfgtable;
3687
3688	dev_dbg(&h->pdev->dev, "Controller Configuration information\n");
3689	dev_dbg(&h->pdev->dev, "------------------------------------\n");
3690	for (i = 0; i < 4; i++)
3691		temp_name[i] = readb(&(tb->Signature[i]));
3692	temp_name[4] = '\0';
3693	dev_dbg(&h->pdev->dev, "   Signature = %s\n", temp_name);
3694	dev_dbg(&h->pdev->dev, "   Spec Number = %d\n",
3695		readl(&(tb->SpecValence)));
3696	dev_dbg(&h->pdev->dev, "   Transport methods supported = 0x%x\n",
3697	       readl(&(tb->TransportSupport)));
3698	dev_dbg(&h->pdev->dev, "   Transport methods active = 0x%x\n",
3699	       readl(&(tb->TransportActive)));
3700	dev_dbg(&h->pdev->dev, "   Requested transport Method = 0x%x\n",
3701	       readl(&(tb->HostWrite.TransportRequest)));
3702	dev_dbg(&h->pdev->dev, "   Coalesce Interrupt Delay = 0x%x\n",
3703	       readl(&(tb->HostWrite.CoalIntDelay)));
3704	dev_dbg(&h->pdev->dev, "   Coalesce Interrupt Count = 0x%x\n",
3705	       readl(&(tb->HostWrite.CoalIntCount)));
3706	dev_dbg(&h->pdev->dev, "   Max outstanding commands = 0x%d\n",
3707	       readl(&(tb->CmdsOutMax)));
3708	dev_dbg(&h->pdev->dev, "   Bus Types = 0x%x\n",
3709		readl(&(tb->BusTypes)));
3710	for (i = 0; i < 16; i++)
3711		temp_name[i] = readb(&(tb->ServerName[i]));
3712	temp_name[16] = '\0';
3713	dev_dbg(&h->pdev->dev, "   Server Name = %s\n", temp_name);
3714	dev_dbg(&h->pdev->dev, "   Heartbeat Counter = 0x%x\n\n\n",
3715		readl(&(tb->HeartBeat)));
3716}
3717
3718static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
3719{
3720	int i, offset, mem_type, bar_type;
3721	if (pci_bar_addr == PCI_BASE_ADDRESS_0)	/* looking for BAR zero? */
3722		return 0;
3723	offset = 0;
3724	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3725		bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
3726		if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
3727			offset += 4;
3728		else {
3729			mem_type = pci_resource_flags(pdev, i) &
3730			    PCI_BASE_ADDRESS_MEM_TYPE_MASK;
3731			switch (mem_type) {
3732			case PCI_BASE_ADDRESS_MEM_TYPE_32:
3733			case PCI_BASE_ADDRESS_MEM_TYPE_1M:
3734				offset += 4;	/* 32 bit */
3735				break;
3736			case PCI_BASE_ADDRESS_MEM_TYPE_64:
3737				offset += 8;
3738				break;
3739			default:	/* reserved in PCI 2.2 */
3740				dev_warn(&pdev->dev,
3741				       "Base address is invalid\n");
3742				return -1;
3743				break;
3744			}
3745		}
3746		if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
3747			return i + 1;
3748	}
3749	return -1;
3750}
3751
3752/* Fill in bucket_map[], given nsgs (the max number of
3753 * scatter gather elements supported) and bucket[],
3754 * which is an array of 8 integers.  The bucket[] array
3755 * contains 8 different DMA transfer sizes (in 16
3756 * byte increments) which the controller uses to fetch
3757 * commands.  This function fills in bucket_map[], which
3758 * maps a given number of scatter gather elements to one of
3759 * the 8 DMA transfer sizes.  The point of it is to allow the
3760 * controller to only do as much DMA as needed to fetch the
3761 * command, with the DMA transfer size encoded in the lower
3762 * bits of the command address.
3763 */
3764static void  calc_bucket_map(int bucket[], int num_buckets,
3765	int nsgs, int *bucket_map)
3766{
3767	int i, j, b, size;
3768
3769	/* even a command with 0 SGs requires 4 blocks */
3770#define MINIMUM_TRANSFER_BLOCKS 4
3771#define NUM_BUCKETS 8
3772	/* Note, bucket_map must have nsgs+1 entries. */
3773	for (i = 0; i <= nsgs; i++) {
3774		/* Compute size of a command with i SG entries */
3775		size = i + MINIMUM_TRANSFER_BLOCKS;
3776		b = num_buckets; /* Assume the biggest bucket */
3777		/* Find the bucket that is just big enough */
3778		for (j = 0; j < 8; j++) {
3779			if (bucket[j] >= size) {
3780				b = j;
3781				break;
3782			}
3783		}
3784		/* for a command with i SG entries, use bucket b. */
3785		bucket_map[i] = b;
3786	}
3787}
3788
3789static void __devinit cciss_wait_for_mode_change_ack(ctlr_info_t *h)
3790{
3791	int i;
3792
3793	/* under certain very rare conditions, this can take awhile.
3794	 * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
3795	 * as we enter this code.) */
3796	for (i = 0; i < MAX_CONFIG_WAIT; i++) {
3797		if (!(readl(h->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
3798			break;
3799		msleep(10);
3800	}
3801}
3802
3803static __devinit void cciss_enter_performant_mode(ctlr_info_t *h)
3804{
3805	/* This is a bit complicated.  There are 8 registers on
3806	 * the controller which we write to to tell it 8 different
3807	 * sizes of commands which there may be.  It's a way of
3808	 * reducing the DMA done to fetch each command.  Encoded into
3809	 * each command's tag are 3 bits which communicate to the controller
3810	 * which of the eight sizes that command fits within.  The size of
3811	 * each command depends on how many scatter gather entries there are.
3812	 * Each SG entry requires 16 bytes.  The eight registers are programmed
3813	 * with the number of 16-byte blocks a command of that size requires.
3814	 * The smallest command possible requires 5 such 16 byte blocks.
3815	 * the largest command possible requires MAXSGENTRIES + 4 16-byte
3816	 * blocks.  Note, this only extends to the SG entries contained
3817	 * within the command block, and does not extend to chained blocks
3818	 * of SG elements.   bft[] contains the eight values we write to
3819	 * the registers.  They are not evenly distributed, but have more
3820	 * sizes for small commands, and fewer sizes for larger commands.
3821	 */
3822	__u32 trans_offset;
3823	int bft[8] = { 5, 6, 8, 10, 12, 20, 28, MAXSGENTRIES + 4};
3824			/*
3825			 *  5 = 1 s/g entry or 4k
3826			 *  6 = 2 s/g entry or 8k
3827			 *  8 = 4 s/g entry or 16k
3828			 * 10 = 6 s/g entry or 24k
3829			 */
3830	unsigned long register_value;
3831	BUILD_BUG_ON(28 > MAXSGENTRIES + 4);
3832
3833	h->reply_pool_wraparound = 1; /* spec: init to 1 */
3834
3835	/* Controller spec: zero out this buffer. */
3836	memset(h->reply_pool, 0, h->max_commands * sizeof(__u64));
3837	h->reply_pool_head = h->reply_pool;
3838
3839	trans_offset = readl(&(h->cfgtable->TransMethodOffset));
3840	calc_bucket_map(bft, ARRAY_SIZE(bft), h->maxsgentries,
3841				h->blockFetchTable);
3842	writel(bft[0], &h->transtable->BlockFetch0);
3843	writel(bft[1], &h->transtable->BlockFetch1);
3844	writel(bft[2], &h->transtable->BlockFetch2);
3845	writel(bft[3], &h->transtable->BlockFetch3);
3846	writel(bft[4], &h->transtable->BlockFetch4);
3847	writel(bft[5], &h->transtable->BlockFetch5);
3848	writel(bft[6], &h->transtable->BlockFetch6);
3849	writel(bft[7], &h->transtable->BlockFetch7);
3850
3851	/* size of controller ring buffer */
3852	writel(h->max_commands, &h->transtable->RepQSize);
3853	writel(1, &h->transtable->RepQCount);
3854	writel(0, &h->transtable->RepQCtrAddrLow32);
3855	writel(0, &h->transtable->RepQCtrAddrHigh32);
3856	writel(h->reply_pool_dhandle, &h->transtable->RepQAddr0Low32);
3857	writel(0, &h->transtable->RepQAddr0High32);
3858	writel(CFGTBL_Trans_Performant,
3859			&(h->cfgtable->HostWrite.TransportRequest));
3860
3861	writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
3862	cciss_wait_for_mode_change_ack(h);
3863	register_value = readl(&(h->cfgtable->TransportActive));
3864	if (!(register_value & CFGTBL_Trans_Performant))
3865		dev_warn(&h->pdev->dev, "cciss: unable to get board into"
3866					" performant mode\n");
3867}
3868
3869static void __devinit cciss_put_controller_into_performant_mode(ctlr_info_t *h)
3870{
3871	__u32 trans_support;
3872
3873	dev_dbg(&h->pdev->dev, "Trying to put board into Performant mode\n");
3874	/* Attempt to put controller into performant mode if supported */
3875	/* Does board support performant mode? */
3876	trans_support = readl(&(h->cfgtable->TransportSupport));
3877	if (!(trans_support & PERFORMANT_MODE))
3878		return;
3879
3880	dev_dbg(&h->pdev->dev, "Placing controller into performant mode\n");
3881	/* Performant mode demands commands on a 32 byte boundary
3882	 * pci_alloc_consistent aligns on page boundarys already.
3883	 * Just need to check if divisible by 32
3884	 */
3885	if ((sizeof(CommandList_struct) % 32) != 0) {
3886		dev_warn(&h->pdev->dev, "%s %d %s\n",
3887			"cciss info: command size[",
3888			(int)sizeof(CommandList_struct),
3889			"] not divisible by 32, no performant mode..\n");
3890		return;
3891	}
3892
3893	/* Performant mode ring buffer and supporting data structures */
3894	h->reply_pool = (__u64 *)pci_alloc_consistent(
3895		h->pdev, h->max_commands * sizeof(__u64),
3896		&(h->reply_pool_dhandle));
3897
3898	/* Need a block fetch table for performant mode */
3899	h->blockFetchTable = kmalloc(((h->maxsgentries+1) *
3900		sizeof(__u32)), GFP_KERNEL);
3901
3902	if ((h->reply_pool == NULL) || (h->blockFetchTable == NULL))
3903		goto clean_up;
3904
3905	cciss_enter_performant_mode(h);
3906
3907	/* Change the access methods to the performant access methods */
3908	h->access = SA5_performant_access;
3909	h->transMethod = CFGTBL_Trans_Performant;
3910
3911	return;
3912clean_up:
3913	kfree(h->blockFetchTable);
3914	if (h->reply_pool)
3915		pci_free_consistent(h->pdev,
3916				h->max_commands * sizeof(__u64),
3917				h->reply_pool,
3918				h->reply_pool_dhandle);
3919	return;
3920
3921} /* cciss_put_controller_into_performant_mode */
3922
3923/* If MSI/MSI-X is supported by the kernel we will try to enable it on
3924 * controllers that are capable. If not, we use IO-APIC mode.
3925 */
3926
3927static void __devinit cciss_interrupt_mode(ctlr_info_t *h)
3928{
3929#ifdef CONFIG_PCI_MSI
3930	int err;
3931	struct msix_entry cciss_msix_entries[4] = { {0, 0}, {0, 1},
3932	{0, 2}, {0, 3}
3933	};
3934
3935	/* Some boards advertise MSI but don't really support it */
3936	if ((h->board_id == 0x40700E11) || (h->board_id == 0x40800E11) ||
3937	    (h->board_id == 0x40820E11) || (h->board_id == 0x40830E11))
3938		goto default_int_mode;
3939
3940	if (pci_find_capability(h->pdev, PCI_CAP_ID_MSIX)) {
3941		err = pci_enable_msix(h->pdev, cciss_msix_entries, 4);
3942		if (!err) {
3943			h->intr[0] = cciss_msix_entries[0].vector;
3944			h->intr[1] = cciss_msix_entries[1].vector;
3945			h->intr[2] = cciss_msix_entries[2].vector;
3946			h->intr[3] = cciss_msix_entries[3].vector;
3947			h->msix_vector = 1;
3948			return;
3949		}
3950		if (err > 0) {
3951			dev_warn(&h->pdev->dev,
3952				"only %d MSI-X vectors available\n", err);
3953			goto default_int_mode;
3954		} else {
3955			dev_warn(&h->pdev->dev,
3956				"MSI-X init failed %d\n", err);
3957			goto default_int_mode;
3958		}
3959	}
3960	if (pci_find_capability(h->pdev, PCI_CAP_ID_MSI)) {
3961		if (!pci_enable_msi(h->pdev))
3962			h->msi_vector = 1;
3963		else
3964			dev_warn(&h->pdev->dev, "MSI init failed\n");
3965	}
3966default_int_mode:
3967#endif				/* CONFIG_PCI_MSI */
3968	/* if we get here we're going to use the default interrupt mode */
3969	h->intr[PERF_MODE_INT] = h->pdev->irq;
3970	return;
3971}
3972
3973static int __devinit cciss_lookup_board_id(struct pci_dev *pdev, u32 *board_id)
3974{
3975	int i;
3976	u32 subsystem_vendor_id, subsystem_device_id;
3977
3978	subsystem_vendor_id = pdev->subsystem_vendor;
3979	subsystem_device_id = pdev->subsystem_device;
3980	*board_id = ((subsystem_device_id << 16) & 0xffff0000) |
3981			subsystem_vendor_id;
3982
3983	for (i = 0; i < ARRAY_SIZE(products); i++) {
3984		/* Stand aside for hpsa driver on request */
3985		if (cciss_allow_hpsa && products[i].board_id == HPSA_BOUNDARY)
3986			return -ENODEV;
3987		if (*board_id == products[i].board_id)
3988			return i;
3989	}
3990	dev_warn(&pdev->dev, "unrecognized board ID: 0x%08x, ignoring.\n",
3991		*board_id);
3992	return -ENODEV;
3993}
3994
3995static inline bool cciss_board_disabled(ctlr_info_t *h)
3996{
3997	u16 command;
3998
3999	(void) pci_read_config_word(h->pdev, PCI_COMMAND, &command);
4000	return ((command & PCI_COMMAND_MEMORY) == 0);
4001}
4002
4003static int __devinit cciss_pci_find_memory_BAR(struct pci_dev *pdev,
4004	unsigned long *memory_bar)
4005{
4006	int i;
4007
4008	for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
4009		if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
4010			/* addressing mode bits already removed */
4011			*memory_bar = pci_resource_start(pdev, i);
4012			dev_dbg(&pdev->dev, "memory BAR = %lx\n",
4013				*memory_bar);
4014			return 0;
4015		}
4016	dev_warn(&pdev->dev, "no memory BAR found\n");
4017	return -ENODEV;
4018}
4019
4020static int __devinit cciss_wait_for_board_ready(ctlr_info_t *h)
4021{
4022	int i;
4023	u32 scratchpad;
4024
4025	for (i = 0; i < CCISS_BOARD_READY_ITERATIONS; i++) {
4026		scratchpad = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
4027		if (scratchpad == CCISS_FIRMWARE_READY)
4028			return 0;
4029		msleep(CCISS_BOARD_READY_POLL_INTERVAL_MSECS);
4030	}
4031	dev_warn(&h->pdev->dev, "board not ready, timed out.\n");
4032	return -ENODEV;
4033}
4034
4035static int __devinit cciss_find_cfg_addrs(struct pci_dev *pdev,
4036	void __iomem *vaddr, u32 *cfg_base_addr, u64 *cfg_base_addr_index,
4037	u64 *cfg_offset)
4038{
4039	*cfg_base_addr = readl(vaddr + SA5_CTCFG_OFFSET);
4040	*cfg_offset = readl(vaddr + SA5_CTMEM_OFFSET);
4041	*cfg_base_addr &= (u32) 0x0000ffff;
4042	*cfg_base_addr_index = find_PCI_BAR_index(pdev, *cfg_base_addr);
4043	if (*cfg_base_addr_index == -1) {
4044		dev_warn(&pdev->dev, "cannot find cfg_base_addr_index, "
4045			"*cfg_base_addr = 0x%08x\n", *cfg_base_addr);
4046		return -ENODEV;
4047	}
4048	return 0;
4049}
4050
4051static int __devinit cciss_find_cfgtables(ctlr_info_t *h)
4052{
4053	u64 cfg_offset;
4054	u32 cfg_base_addr;
4055	u64 cfg_base_addr_index;
4056	u32 trans_offset;
4057	int rc;
4058
4059	rc = cciss_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
4060		&cfg_base_addr_index, &cfg_offset);
4061	if (rc)
4062		return rc;
4063	h->cfgtable = remap_pci_mem(pci_resource_start(h->pdev,
4064		cfg_base_addr_index) + cfg_offset, sizeof(h->cfgtable));
4065	if (!h->cfgtable)
4066		return -ENOMEM;
4067	/* Find performant mode table. */
4068	trans_offset = readl(&h->cfgtable->TransMethodOffset);
4069	h->transtable = remap_pci_mem(pci_resource_start(h->pdev,
4070				cfg_base_addr_index)+cfg_offset+trans_offset,
4071				sizeof(*h->transtable));
4072	if (!h->transtable)
4073		return -ENOMEM;
4074	return 0;
4075}
4076
4077static void __devinit cciss_get_max_perf_mode_cmds(struct ctlr_info *h)
4078{
4079	h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
4080	if (h->max_commands < 16) {
4081		dev_warn(&h->pdev->dev, "Controller reports "
4082			"max supported commands of %d, an obvious lie. "
4083			"Using 16.  Ensure that firmware is up to date.\n",
4084			h->max_commands);
4085		h->max_commands = 16;
4086	}
4087}
4088
4089/* Interrogate the hardware for some limits:
4090 * max commands, max SG elements without chaining, and with chaining,
4091 * SG chain block size, etc.
4092 */
4093static void __devinit cciss_find_board_params(ctlr_info_t *h)
4094{
4095	cciss_get_max_perf_mode_cmds(h);
4096	h->nr_cmds = h->max_commands - 4; /* Allow room for some ioctls */
4097	h->maxsgentries = readl(&(h->cfgtable->MaxSGElements));
4098	/*
4099	 * Limit in-command s/g elements to 32 save dma'able memory.
4100	 * Howvever spec says if 0, use 31
4101	 */
4102	h->max_cmd_sgentries = 31;
4103	if (h->maxsgentries > 512) {
4104		h->max_cmd_sgentries = 32;
4105		h->chainsize = h->maxsgentries - h->max_cmd_sgentries + 1;
4106		h->maxsgentries--; /* save one for chain pointer */
4107	} else {
4108		h->maxsgentries = 31; /* default to traditional values */
4109		h->chainsize = 0;
4110	}
4111}
4112
4113static inline bool CISS_signature_present(ctlr_info_t *h)
4114{
4115	if ((readb(&h->cfgtable->Signature[0]) != 'C') ||
4116	    (readb(&h->cfgtable->Signature[1]) != 'I') ||
4117	    (readb(&h->cfgtable->Signature[2]) != 'S') ||
4118	    (readb(&h->cfgtable->Signature[3]) != 'S')) {
4119		dev_warn(&h->pdev->dev, "not a valid CISS config table\n");
4120		return false;
4121	}
4122	return true;
4123}
4124
4125/* Need to enable prefetch in the SCSI core for 6400 in x86 */
4126static inline void cciss_enable_scsi_prefetch(ctlr_info_t *h)
4127{
4128#ifdef CONFIG_X86
4129	u32 prefetch;
4130
4131	prefetch = readl(&(h->cfgtable->SCSI_Prefetch));
4132	prefetch |= 0x100;
4133	writel(prefetch, &(h->cfgtable->SCSI_Prefetch));
4134#endif
4135}
4136
4137/* Disable DMA prefetch for the P600.  Otherwise an ASIC bug may result
4138 * in a prefetch beyond physical memory.
4139 */
4140static inline void cciss_p600_dma_prefetch_quirk(ctlr_info_t *h)
4141{
4142	u32 dma_prefetch;
4143	__u32 dma_refetch;
4144
4145	if (h->board_id != 0x3225103C)
4146		return;
4147	dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
4148	dma_prefetch |= 0x8000;
4149	writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
4150	pci_read_config_dword(h->pdev, PCI_COMMAND_PARITY, &dma_refetch);
4151	dma_refetch |= 0x1;
4152	pci_write_config_dword(h->pdev, PCI_COMMAND_PARITY, dma_refetch);
4153}
4154
4155static int __devinit cciss_pci_init(ctlr_info_t *h)
4156{
4157	int prod_index, err;
4158
4159	prod_index = cciss_lookup_board_id(h->pdev, &h->board_id);
4160	if (prod_index < 0)
4161		return -ENODEV;
4162	h->product_name = products[prod_index].product_name;
4163	h->access = *(products[prod_index].access);
4164
4165	if (cciss_board_disabled(h)) {
4166		dev_warn(&h->pdev->dev, "controller appears to be disabled\n");
4167		return -ENODEV;
4168	}
4169	err = pci_enable_device(h->pdev);
4170	if (err) {
4171		dev_warn(&h->pdev->dev, "Unable to Enable PCI device\n");
4172		return err;
4173	}
4174
4175	err = pci_request_regions(h->pdev, "cciss");
4176	if (err) {
4177		dev_warn(&h->pdev->dev,
4178			"Cannot obtain PCI resources, aborting\n");
4179		return err;
4180	}
4181
4182	dev_dbg(&h->pdev->dev, "irq = %x\n", h->pdev->irq);
4183	dev_dbg(&h->pdev->dev, "board_id = %x\n", h->board_id);
4184
4185/* If the kernel supports MSI/MSI-X we will try to enable that functionality,
4186 * else we use the IO-APIC interrupt assigned to us by system ROM.
4187 */
4188	cciss_interrupt_mode(h);
4189	err = cciss_pci_find_memory_BAR(h->pdev, &h->paddr);
4190	if (err)
4191		goto err_out_free_res;
4192	h->vaddr = remap_pci_mem(h->paddr, 0x250);
4193	if (!h->vaddr) {
4194		err = -ENOMEM;
4195		goto err_out_free_res;
4196	}
4197	err = cciss_wait_for_board_ready(h);
4198	if (err)
4199		goto err_out_free_res;
4200	err = cciss_find_cfgtables(h);
4201	if (err)
4202		goto err_out_free_res;
4203	print_cfg_table(h);
4204	cciss_find_board_params(h);
4205
4206	if (!CISS_signature_present(h)) {
4207		err = -ENODEV;
4208		goto err_out_free_res;
4209	}
4210	cciss_enable_scsi_prefetch(h);
4211	cciss_p600_dma_prefetch_quirk(h);
4212	cciss_put_controller_into_performant_mode(h);
4213	return 0;
4214
4215err_out_free_res:
4216	/*
4217	 * Deliberately omit pci_disable_device(): it does something nasty to
4218	 * Smart Array controllers that pci_enable_device does not undo
4219	 */
4220	if (h->transtable)
4221		iounmap(h->transtable);
4222	if (h->cfgtable)
4223		iounmap(h->cfgtable);
4224	if (h->vaddr)
4225		iounmap(h->vaddr);
4226	pci_release_regions(h->pdev);
4227	return err;
4228}
4229
4230/* Function to find the first free pointer into our hba[] array
4231 * Returns -1 if no free entries are left.
4232 */
4233static int alloc_cciss_hba(struct pci_dev *pdev)
4234{
4235	int i;
4236
4237	for (i = 0; i < MAX_CTLR; i++) {
4238		if (!hba[i]) {
4239			ctlr_info_t *h;
4240
4241			h = kzalloc(sizeof(ctlr_info_t), GFP_KERNEL);
4242			if (!h)
4243				goto Enomem;
4244			hba[i] = h;
4245			return i;
4246		}
4247	}
4248	dev_warn(&pdev->dev, "This driver supports a maximum"
4249	       " of %d controllers.\n", MAX_CTLR);
4250	return -1;
4251Enomem:
4252	dev_warn(&pdev->dev, "out of memory.\n");
4253	return -1;
4254}
4255
4256static void free_hba(ctlr_info_t *h)
4257{
4258	int i;
4259
4260	hba[h->ctlr] = NULL;
4261	for (i = 0; i < h->highest_lun + 1; i++)
4262		if (h->gendisk[i] != NULL)
4263			put_disk(h->gendisk[i]);
4264	kfree(h);
4265}
4266
4267/* Send a message CDB to the firmware. */
4268static __devinit int cciss_message(struct pci_dev *pdev, unsigned char opcode, unsigned char type)
4269{
4270	typedef struct {
4271		CommandListHeader_struct CommandHeader;
4272		RequestBlock_struct Request;
4273		ErrDescriptor_struct ErrorDescriptor;
4274	} Command;
4275	static const size_t cmd_sz = sizeof(Command) + sizeof(ErrorInfo_struct);
4276	Command *cmd;
4277	dma_addr_t paddr64;
4278	uint32_t paddr32, tag;
4279	void __iomem *vaddr;
4280	int i, err;
4281
4282	vaddr = ioremap_nocache(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0));
4283	if (vaddr == NULL)
4284		return -ENOMEM;
4285
4286	/* The Inbound Post Queue only accepts 32-bit physical addresses for the
4287	   CCISS commands, so they must be allocated from the lower 4GiB of
4288	   memory. */
4289	err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
4290	if (err) {
4291		iounmap(vaddr);
4292		return -ENOMEM;
4293	}
4294
4295	cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
4296	if (cmd == NULL) {
4297		iounmap(vaddr);
4298		return -ENOMEM;
4299	}
4300
4301	/* This must fit, because of the 32-bit consistent DMA mask.  Also,
4302	   although there's no guarantee, we assume that the address is at
4303	   least 4-byte aligned (most likely, it's page-aligned). */
4304	paddr32 = paddr64;
4305
4306	cmd->CommandHeader.ReplyQueue = 0;
4307	cmd->CommandHeader.SGList = 0;
4308	cmd->CommandHeader.SGTotal = 0;
4309	cmd->CommandHeader.Tag.lower = paddr32;
4310	cmd->CommandHeader.Tag.upper = 0;
4311	memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
4312
4313	cmd->Request.CDBLen = 16;
4314	cmd->Request.Type.Type = TYPE_MSG;
4315	cmd->Request.Type.Attribute = ATTR_HEADOFQUEUE;
4316	cmd->Request.Type.Direction = XFER_NONE;
4317	cmd->Request.Timeout = 0; /* Don't time out */
4318	cmd->Request.CDB[0] = opcode;
4319	cmd->Request.CDB[1] = type;
4320	memset(&cmd->Request.CDB[2], 0, 14); /* the rest of the CDB is reserved */
4321
4322	cmd->ErrorDescriptor.Addr.lower = paddr32 + sizeof(Command);
4323	cmd->ErrorDescriptor.Addr.upper = 0;
4324	cmd->ErrorDescriptor.Len = sizeof(ErrorInfo_struct);
4325
4326	writel(paddr32, vaddr + SA5_REQUEST_PORT_OFFSET);
4327
4328	for (i = 0; i < 10; i++) {
4329		tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
4330		if ((tag & ~3) == paddr32)
4331			break;
4332		schedule_timeout_uninterruptible(HZ);
4333	}
4334
4335	iounmap(vaddr);
4336
4337	/* we leak the DMA buffer here ... no choice since the controller could
4338	   still complete the command. */
4339	if (i == 10) {
4340		dev_err(&pdev->dev,
4341			"controller message %02x:%02x timed out\n",
4342			opcode, type);
4343		return -ETIMEDOUT;
4344	}
4345
4346	pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
4347
4348	if (tag & 2) {
4349		dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
4350			opcode, type);
4351		return -EIO;
4352	}
4353
4354	dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
4355		opcode, type);
4356	return 0;
4357}
4358
4359#define cciss_soft_reset_controller(p) cciss_message(p, 1, 0)
4360#define cciss_noop(p) cciss_message(p, 3, 0)
4361
4362static __devinit int cciss_reset_msi(struct pci_dev *pdev)
4363{
4364/* the #defines are stolen from drivers/pci/msi.h. */
4365#define msi_control_reg(base)		(base + PCI_MSI_FLAGS)
4366#define PCI_MSIX_FLAGS_ENABLE		(1 << 15)
4367
4368	int pos;
4369	u16 control = 0;
4370
4371	pos = pci_find_capability(pdev, PCI_CAP_ID_MSI);
4372	if (pos) {
4373		pci_read_config_word(pdev, msi_control_reg(pos), &control);
4374		if (control & PCI_MSI_FLAGS_ENABLE) {
4375			dev_info(&pdev->dev, "resetting MSI\n");
4376			pci_write_config_word(pdev, msi_control_reg(pos), control & ~PCI_MSI_FLAGS_ENABLE);
4377		}
4378	}
4379
4380	pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
4381	if (pos) {
4382		pci_read_config_word(pdev, msi_control_reg(pos), &control);
4383		if (control & PCI_MSIX_FLAGS_ENABLE) {
4384			dev_info(&pdev->dev, "resetting MSI-X\n");
4385			pci_write_config_word(pdev, msi_control_reg(pos), control & ~PCI_MSIX_FLAGS_ENABLE);
4386		}
4387	}
4388
4389	return 0;
4390}
4391
4392static int cciss_controller_hard_reset(struct pci_dev *pdev,
4393	void * __iomem vaddr, bool use_doorbell)
4394{
4395	u16 pmcsr;
4396	int pos;
4397
4398	if (use_doorbell) {
4399		/* For everything after the P600, the PCI power state method
4400		 * of resetting the controller doesn't work, so we have this
4401		 * other way using the doorbell register.
4402		 */
4403		dev_info(&pdev->dev, "using doorbell to reset controller\n");
4404		writel(DOORBELL_CTLR_RESET, vaddr + SA5_DOORBELL);
4405		msleep(1000);
4406	} else { /* Try to do it the PCI power state way */
4407
4408		/* Quoting from the Open CISS Specification: "The Power
4409		 * Management Control/Status Register (CSR) controls the power
4410		 * state of the device.  The normal operating state is D0,
4411		 * CSR=00h.  The software off state is D3, CSR=03h.  To reset
4412		 * the controller, place the interface device in D3 then to D0,
4413		 * this causes a secondary PCI reset which will reset the
4414		 * controller." */
4415
4416		pos = pci_find_capability(pdev, PCI_CAP_ID_PM);
4417		if (pos == 0) {
4418			dev_err(&pdev->dev,
4419				"cciss_controller_hard_reset: "
4420				"PCI PM not supported\n");
4421			return -ENODEV;
4422		}
4423		dev_info(&pdev->dev, "using PCI PM to reset controller\n");
4424		/* enter the D3hot power management state */
4425		pci_read_config_word(pdev, pos + PCI_PM_CTRL, &pmcsr);
4426		pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
4427		pmcsr |= PCI_D3hot;
4428		pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
4429
4430		msleep(500);
4431
4432		/* enter the D0 power management state */
4433		pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
4434		pmcsr |= PCI_D0;
4435		pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
4436
4437		msleep(500);
4438	}
4439	return 0;
4440}
4441
4442/* This does a hard reset of the controller using PCI power management
4443 * states or using the doorbell register. */
4444static __devinit int cciss_kdump_hard_reset_controller(struct pci_dev *pdev)
4445{
4446	u16 saved_config_space[32];
4447	u64 cfg_offset;
4448	u32 cfg_base_addr;
4449	u64 cfg_base_addr_index;
4450	void __iomem *vaddr;
4451	unsigned long paddr;
4452	u32 misc_fw_support, active_transport;
4453	int rc, i;
4454	CfgTable_struct __iomem *cfgtable;
4455	bool use_doorbell;
4456	u32 board_id;
4457
4458	/* For controllers as old a the p600, this is very nearly
4459	 * the same thing as
4460	 *
4461	 * pci_save_state(pci_dev);
4462	 * pci_set_power_state(pci_dev, PCI_D3hot);
4463	 * pci_set_power_state(pci_dev, PCI_D0);
4464	 * pci_restore_state(pci_dev);
4465	 *
4466	 * but we can't use these nice canned kernel routines on
4467	 * kexec, because they also check the MSI/MSI-X state in PCI
4468	 * configuration space and do the wrong thing when it is
4469	 * set/cleared.  Also, the pci_save/restore_state functions
4470	 * violate the ordering requirements for restoring the
4471	 * configuration space from the CCISS document (see the
4472	 * comment below).  So we roll our own ....
4473	 *
4474	 * For controllers newer than the P600, the pci power state
4475	 * method of resetting doesn't work so we have another way
4476	 * using the doorbell register.
4477	 */
4478
4479	/* Exclude 640x boards.  These are two pci devices in one slot
4480	 * which share a battery backed cache module.  One controls the
4481	 * cache, the other accesses the cache through the one that controls
4482	 * it.  If we reset the one controlling the cache, the other will
4483	 * likely not be happy.  Just forbid resetting this conjoined mess.
4484	 */
4485	cciss_lookup_board_id(pdev, &board_id);
4486	if (board_id == 0x409C0E11 || board_id == 0x409D0E11) {
4487		dev_warn(&pdev->dev, "Cannot reset Smart Array 640x "
4488				"due to shared cache module.");
4489		return -ENODEV;
4490	}
4491
4492	for (i = 0; i < 32; i++)
4493		pci_read_config_word(pdev, 2*i, &saved_config_space[i]);
4494
4495	/* find the first memory BAR, so we can find the cfg table */
4496	rc = cciss_pci_find_memory_BAR(pdev, &paddr);
4497	if (rc)
4498		return rc;
4499	vaddr = remap_pci_mem(paddr, 0x250);
4500	if (!vaddr)
4501		return -ENOMEM;
4502
4503	/* find cfgtable in order to check if reset via doorbell is supported */
4504	rc = cciss_find_cfg_addrs(pdev, vaddr, &cfg_base_addr,
4505					&cfg_base_addr_index, &cfg_offset);
4506	if (rc)
4507		goto unmap_vaddr;
4508	cfgtable = remap_pci_mem(pci_resource_start(pdev,
4509		       cfg_base_addr_index) + cfg_offset, sizeof(*cfgtable));
4510	if (!cfgtable) {
4511		rc = -ENOMEM;
4512		goto unmap_vaddr;
4513	}
4514
4515	/* If reset via doorbell register is supported, use that. */
4516	misc_fw_support = readl(&cfgtable->misc_fw_support);
4517	use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET;
4518
4519	/* The doorbell reset seems to cause lockups on some Smart
4520	 * Arrays (e.g. P410, P410i, maybe others).  Until this is
4521	 * fixed or at least isolated, avoid the doorbell reset.
4522	 */
4523	use_doorbell = 0;
4524
4525	rc = cciss_controller_hard_reset(pdev, vaddr, use_doorbell);
4526	if (rc)
4527		goto unmap_cfgtable;
4528
4529	/* Restore the PCI configuration space.  The Open CISS
4530	 * Specification says, "Restore the PCI Configuration
4531	 * Registers, offsets 00h through 60h. It is important to
4532	 * restore the command register, 16-bits at offset 04h,
4533	 * last. Do not restore the configuration status register,
4534	 * 16-bits at offset 06h."  Note that the offset is 2*i.
4535	 */
4536	for (i = 0; i < 32; i++) {
4537		if (i == 2 || i == 3)
4538			continue;
4539		pci_write_config_word(pdev, 2*i, saved_config_space[i]);
4540	}
4541	wmb();
4542	pci_write_config_word(pdev, 4, saved_config_space[2]);
4543
4544	/* Some devices (notably the HP Smart Array 5i Controller)
4545	   need a little pause here */
4546	msleep(CCISS_POST_RESET_PAUSE_MSECS);
4547
4548	/* Controller should be in simple mode at this point.  If it's not,
4549	 * It means we're on one of those controllers which doesn't support
4550	 * the doorbell reset method and on which the PCI power management reset
4551	 * method doesn't work (P800, for example.)
4552	 * In those cases, don't try to proceed, as it generally doesn't work.
4553	 */
4554	active_transport = readl(&cfgtable->TransportActive);
4555	if (active_transport & PERFORMANT_MODE) {
4556		dev_warn(&pdev->dev, "Unable to successfully reset controller,"
4557			" Ignoring controller.\n");
4558		rc = -ENODEV;
4559	}
4560
4561unmap_cfgtable:
4562	iounmap(cfgtable);
4563
4564unmap_vaddr:
4565	iounmap(vaddr);
4566	return rc;
4567}
4568
4569static __devinit int cciss_init_reset_devices(struct pci_dev *pdev)
4570{
4571	int rc, i;
4572
4573	if (!reset_devices)
4574		return 0;
4575
4576	/* Reset the controller with a PCI power-cycle or via doorbell */
4577	rc = cciss_kdump_hard_reset_controller(pdev);
4578
4579	/* -ENOTSUPP here means we cannot reset the controller
4580	 * but it's already (and still) up and running in
4581	 * "performant mode".  Or, it might be 640x, which can't reset
4582	 * due to concerns about shared bbwc between 6402/6404 pair.
4583	 */
4584	if (rc == -ENOTSUPP)
4585		return 0; /* just try to do the kdump anyhow. */
4586	if (rc)
4587		return -ENODEV;
4588	if (cciss_reset_msi(pdev))
4589		return -ENODEV;
4590
4591	/* Now try to get the controller to respond to a no-op */
4592	for (i = 0; i < CCISS_POST_RESET_NOOP_RETRIES; i++) {
4593		if (cciss_noop(pdev) == 0)
4594			break;
4595		else
4596			dev_warn(&pdev->dev, "no-op failed%s\n",
4597				(i < CCISS_POST_RESET_NOOP_RETRIES - 1 ?
4598					"; re-trying" : ""));
4599		msleep(CCISS_POST_RESET_NOOP_INTERVAL_MSECS);
4600	}
4601	return 0;
4602}
4603
4604/*
4605 *  This is it.  Find all the controllers and register them.  I really hate
4606 *  stealing all these major device numbers.
4607 *  returns the number of block devices registered.
4608 */
4609static int __devinit cciss_init_one(struct pci_dev *pdev,
4610				    const struct pci_device_id *ent)
4611{
4612	int i;
4613	int j = 0;
4614	int k = 0;
4615	int rc;
4616	int dac, return_code;
4617	InquiryData_struct *inq_buff;
4618	ctlr_info_t *h;
4619
4620	rc = cciss_init_reset_devices(pdev);
4621	if (rc)
4622		return rc;
4623	i = alloc_cciss_hba(pdev);
4624	if (i < 0)
4625		return -1;
4626
4627	h = hba[i];
4628	h->pdev = pdev;
4629	h->busy_initializing = 1;
4630	INIT_HLIST_HEAD(&h->cmpQ);
4631	INIT_HLIST_HEAD(&h->reqQ);
4632	mutex_init(&h->busy_shutting_down);
4633
4634	if (cciss_pci_init(h) != 0)
4635		goto clean_no_release_regions;
4636
4637	sprintf(h->devname, "cciss%d", i);
4638	h->ctlr = i;
4639
4640	init_completion(&h->scan_wait);
4641
4642	if (cciss_create_hba_sysfs_entry(h))
4643		goto clean0;
4644
4645	/* configure PCI DMA stuff */
4646	if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64)))
4647		dac = 1;
4648	else if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32)))
4649		dac = 0;
4650	else {
4651		dev_err(&h->pdev->dev, "no suitable DMA available\n");
4652		goto clean1;
4653	}
4654
4655	/*
4656	 * register with the major number, or get a dynamic major number
4657	 * by passing 0 as argument.  This is done for greater than
4658	 * 8 controller support.
4659	 */
4660	if (i < MAX_CTLR_ORIG)
4661		h->major = COMPAQ_CISS_MAJOR + i;
4662	rc = register_blkdev(h->major, h->devname);
4663	if (rc == -EBUSY || rc == -EINVAL) {
4664		dev_err(&h->pdev->dev,
4665		       "Unable to get major number %d for %s "
4666		       "on hba %d\n", h->major, h->devname, i);
4667		goto clean1;
4668	} else {
4669		if (i >= MAX_CTLR_ORIG)
4670			h->major = rc;
4671	}
4672
4673	/* make sure the board interrupts are off */
4674	h->access.set_intr_mask(h, CCISS_INTR_OFF);
4675	if (h->msi_vector || h->msix_vector) {
4676		if (request_irq(h->intr[PERF_MODE_INT],
4677				do_cciss_msix_intr,
4678				IRQF_DISABLED, h->devname, h)) {
4679			dev_err(&h->pdev->dev, "Unable to get irq %d for %s\n",
4680			       h->intr[PERF_MODE_INT], h->devname);
4681			goto clean2;
4682		}
4683	} else {
4684		if (request_irq(h->intr[PERF_MODE_INT], do_cciss_intx,
4685				IRQF_DISABLED, h->devname, h)) {
4686			dev_err(&h->pdev->dev, "Unable to get irq %d for %s\n",
4687			       h->intr[PERF_MODE_INT], h->devname);
4688			goto clean2;
4689		}
4690	}
4691
4692	dev_info(&h->pdev->dev, "%s: <0x%x> at PCI %s IRQ %d%s using DAC\n",
4693	       h->devname, pdev->device, pci_name(pdev),
4694	       h->intr[PERF_MODE_INT], dac ? "" : " not");
4695
4696	h->cmd_pool_bits =
4697	    kmalloc(DIV_ROUND_UP(h->nr_cmds, BITS_PER_LONG)
4698			* sizeof(unsigned long), GFP_KERNEL);
4699	h->cmd_pool = (CommandList_struct *)
4700	    pci_alloc_consistent(h->pdev,
4701		    h->nr_cmds * sizeof(CommandList_struct),
4702		    &(h->cmd_pool_dhandle));
4703	h->errinfo_pool = (ErrorInfo_struct *)
4704	    pci_alloc_consistent(h->pdev,
4705		    h->nr_cmds * sizeof(ErrorInfo_struct),
4706		    &(h->errinfo_pool_dhandle));
4707	if ((h->cmd_pool_bits == NULL)
4708	    || (h->cmd_pool == NULL)
4709	    || (h->errinfo_pool == NULL)) {
4710		dev_err(&h->pdev->dev, "out of memory");
4711		goto clean4;
4712	}
4713
4714	/* Need space for temp scatter list */
4715	h->scatter_list = kmalloc(h->max_commands *
4716						sizeof(struct scatterlist *),
4717						GFP_KERNEL);
4718	if (!h->scatter_list)
4719		goto clean4;
4720
4721	for (k = 0; k < h->nr_cmds; k++) {
4722		h->scatter_list[k] = kmalloc(sizeof(struct scatterlist) *
4723							h->maxsgentries,
4724							GFP_KERNEL);
4725		if (h->scatter_list[k] == NULL) {
4726			dev_err(&h->pdev->dev,
4727				"could not allocate s/g lists\n");
4728			goto clean4;
4729		}
4730	}
4731	h->cmd_sg_list = cciss_allocate_sg_chain_blocks(h,
4732		h->chainsize, h->nr_cmds);
4733	if (!h->cmd_sg_list && h->chainsize > 0)
4734		goto clean4;
4735
4736	spin_lock_init(&h->lock);
4737
4738	/* Initialize the pdev driver private data.
4739	   have it point to h.  */
4740	pci_set_drvdata(pdev, h);
4741	/* command and error info recs zeroed out before
4742	   they are used */
4743	memset(h->cmd_pool_bits, 0,
4744	       DIV_ROUND_UP(h->nr_cmds, BITS_PER_LONG)
4745			* sizeof(unsigned long));
4746
4747	h->num_luns = 0;
4748	h->highest_lun = -1;
4749	for (j = 0; j < CISS_MAX_LUN; j++) {
4750		h->drv[j] = NULL;
4751		h->gendisk[j] = NULL;
4752	}
4753
4754	cciss_scsi_setup(h);
4755
4756	/* Turn the interrupts on so we can service requests */
4757	h->access.set_intr_mask(h, CCISS_INTR_ON);
4758
4759	/* Get the firmware version */
4760	inq_buff = kzalloc(sizeof(InquiryData_struct), GFP_KERNEL);
4761	if (inq_buff == NULL) {
4762		dev_err(&h->pdev->dev, "out of memory\n");
4763		goto clean4;
4764	}
4765
4766	return_code = sendcmd_withirq(h, CISS_INQUIRY, inq_buff,
4767		sizeof(InquiryData_struct), 0, CTLR_LUNID, TYPE_CMD);
4768	if (return_code == IO_OK) {
4769		h->firm_ver[0] = inq_buff->data_byte[32];
4770		h->firm_ver[1] = inq_buff->data_byte[33];
4771		h->firm_ver[2] = inq_buff->data_byte[34];
4772		h->firm_ver[3] = inq_buff->data_byte[35];
4773	} else {	 /* send command failed */
4774		dev_warn(&h->pdev->dev, "unable to determine firmware"
4775			" version of controller\n");
4776	}
4777	kfree(inq_buff);
4778
4779	cciss_procinit(h);
4780
4781	h->cciss_max_sectors = 8192;
4782
4783	rebuild_lun_table(h, 1, 0);
4784	h->busy_initializing = 0;
4785	return 1;
4786
4787clean4:
4788	kfree(h->cmd_pool_bits);
4789	/* Free up sg elements */
4790	for (k-- ; k >= 0; k--)
4791		kfree(h->scatter_list[k]);
4792	kfree(h->scatter_list);
4793	cciss_free_sg_chain_blocks(h->cmd_sg_list, h->nr_cmds);
4794	if (h->cmd_pool)
4795		pci_free_consistent(h->pdev,
4796				    h->nr_cmds * sizeof(CommandList_struct),
4797				    h->cmd_pool, h->cmd_pool_dhandle);
4798	if (h->errinfo_pool)
4799		pci_free_consistent(h->pdev,
4800				    h->nr_cmds * sizeof(ErrorInfo_struct),
4801				    h->errinfo_pool,
4802				    h->errinfo_pool_dhandle);
4803	free_irq(h->intr[PERF_MODE_INT], h);
4804clean2:
4805	unregister_blkdev(h->major, h->devname);
4806clean1:
4807	cciss_destroy_hba_sysfs_entry(h);
4808clean0:
4809	pci_release_regions(pdev);
4810clean_no_release_regions:
4811	h->busy_initializing = 0;
4812
4813	/*
4814	 * Deliberately omit pci_disable_device(): it does something nasty to
4815	 * Smart Array controllers that pci_enable_device does not undo
4816	 */
4817	pci_set_drvdata(pdev, NULL);
4818	free_hba(h);
4819	return -1;
4820}
4821
4822static void cciss_shutdown(struct pci_dev *pdev)
4823{
4824	ctlr_info_t *h;
4825	char *flush_buf;
4826	int return_code;
4827
4828	h = pci_get_drvdata(pdev);
4829	flush_buf = kzalloc(4, GFP_KERNEL);
4830	if (!flush_buf) {
4831		dev_warn(&h->pdev->dev, "cache not flushed, out of memory.\n");
4832		return;
4833	}
4834	/* write all data in the battery backed cache to disk */
4835	memset(flush_buf, 0, 4);
4836	return_code = sendcmd_withirq(h, CCISS_CACHE_FLUSH, flush_buf,
4837		4, 0, CTLR_LUNID, TYPE_CMD);
4838	kfree(flush_buf);
4839	if (return_code != IO_OK)
4840		dev_warn(&h->pdev->dev, "Error flushing cache\n");
4841	h->access.set_intr_mask(h, CCISS_INTR_OFF);
4842	free_irq(h->intr[PERF_MODE_INT], h);
4843}
4844
4845static void __devexit cciss_remove_one(struct pci_dev *pdev)
4846{
4847	ctlr_info_t *h;
4848	int i, j;
4849
4850	if (pci_get_drvdata(pdev) == NULL) {
4851		dev_err(&pdev->dev, "Unable to remove device\n");
4852		return;
4853	}
4854
4855	h = pci_get_drvdata(pdev);
4856	i = h->ctlr;
4857	if (hba[i] == NULL) {
4858		dev_err(&pdev->dev, "device appears to already be removed\n");
4859		return;
4860	}
4861
4862	mutex_lock(&h->busy_shutting_down);
4863
4864	remove_from_scan_list(h);
4865	remove_proc_entry(h->devname, proc_cciss);
4866	unregister_blkdev(h->major, h->devname);
4867
4868	/* remove it from the disk list */
4869	for (j = 0; j < CISS_MAX_LUN; j++) {
4870		struct gendisk *disk = h->gendisk[j];
4871		if (disk) {
4872			struct request_queue *q = disk->queue;
4873
4874			if (disk->flags & GENHD_FL_UP) {
4875				cciss_destroy_ld_sysfs_entry(h, j, 1);
4876				del_gendisk(disk);
4877			}
4878			if (q)
4879				blk_cleanup_queue(q);
4880		}
4881	}
4882
4883#ifdef CONFIG_CISS_SCSI_TAPE
4884	cciss_unregister_scsi(h);	/* unhook from SCSI subsystem */
4885#endif
4886
4887	cciss_shutdown(pdev);
4888
4889#ifdef CONFIG_PCI_MSI
4890	if (h->msix_vector)
4891		pci_disable_msix(h->pdev);
4892	else if (h->msi_vector)
4893		pci_disable_msi(h->pdev);
4894#endif				/* CONFIG_PCI_MSI */
4895
4896	iounmap(h->transtable);
4897	iounmap(h->cfgtable);
4898	iounmap(h->vaddr);
4899
4900	pci_free_consistent(h->pdev, h->nr_cmds * sizeof(CommandList_struct),
4901			    h->cmd_pool, h->cmd_pool_dhandle);
4902	pci_free_consistent(h->pdev, h->nr_cmds * sizeof(ErrorInfo_struct),
4903			    h->errinfo_pool, h->errinfo_pool_dhandle);
4904	kfree(h->cmd_pool_bits);
4905	/* Free up sg elements */
4906	for (j = 0; j < h->nr_cmds; j++)
4907		kfree(h->scatter_list[j]);
4908	kfree(h->scatter_list);
4909	cciss_free_sg_chain_blocks(h->cmd_sg_list, h->nr_cmds);
4910	/*
4911	 * Deliberately omit pci_disable_device(): it does something nasty to
4912	 * Smart Array controllers that pci_enable_device does not undo
4913	 */
4914	pci_release_regions(pdev);
4915	pci_set_drvdata(pdev, NULL);
4916	cciss_destroy_hba_sysfs_entry(h);
4917	mutex_unlock(&h->busy_shutting_down);
4918	free_hba(h);
4919}
4920
4921static struct pci_driver cciss_pci_driver = {
4922	.name = "cciss",
4923	.probe = cciss_init_one,
4924	.remove = __devexit_p(cciss_remove_one),
4925	.id_table = cciss_pci_device_id,	/* id_table */
4926	.shutdown = cciss_shutdown,
4927};
4928
4929/*
4930 *  This is it.  Register the PCI driver information for the cards we control
4931 *  the OS will call our registered routines when it finds one of our cards.
4932 */
4933static int __init cciss_init(void)
4934{
4935	int err;
4936
4937	/*
4938	 * The hardware requires that commands are aligned on a 64-bit
4939	 * boundary. Given that we use pci_alloc_consistent() to allocate an
4940	 * array of them, the size must be a multiple of 8 bytes.
4941	 */
4942	BUILD_BUG_ON(sizeof(CommandList_struct) % COMMANDLIST_ALIGNMENT);
4943	printk(KERN_INFO DRIVER_NAME "\n");
4944
4945	err = bus_register(&cciss_bus_type);
4946	if (err)
4947		return err;
4948
4949	/* Start the scan thread */
4950	cciss_scan_thread = kthread_run(scan_thread, NULL, "cciss_scan");
4951	if (IS_ERR(cciss_scan_thread)) {
4952		err = PTR_ERR(cciss_scan_thread);
4953		goto err_bus_unregister;
4954	}
4955
4956	/* Register for our PCI devices */
4957	err = pci_register_driver(&cciss_pci_driver);
4958	if (err)
4959		goto err_thread_stop;
4960
4961	return err;
4962
4963err_thread_stop:
4964	kthread_stop(cciss_scan_thread);
4965err_bus_unregister:
4966	bus_unregister(&cciss_bus_type);
4967
4968	return err;
4969}
4970
4971static void __exit cciss_cleanup(void)
4972{
4973	int i;
4974
4975	pci_unregister_driver(&cciss_pci_driver);
4976	/* double check that all controller entrys have been removed */
4977	for (i = 0; i < MAX_CTLR; i++) {
4978		if (hba[i] != NULL) {
4979			dev_warn(&hba[i]->pdev->dev,
4980				"had to remove controller\n");
4981			cciss_remove_one(hba[i]->pdev);
4982		}
4983	}
4984	kthread_stop(cciss_scan_thread);
4985	remove_proc_entry("driver/cciss", NULL);
4986	bus_unregister(&cciss_bus_type);
4987}
4988
4989module_init(cciss_init);
4990module_exit(cciss_cleanup);
4991