1 /*
2  *    Disk Array driver for HP SA 5xxx and 6xxx Controllers
3  *    Copyright 2000, 2005 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; either version 2 of the License, or
8  *    (at your option) any later version.
9  *
10  *    This program is distributed in the hope that it will be useful,
11  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
13  *    NON INFRINGEMENT.  See the GNU General Public License for more details.
14  *
15  *    You should have received a copy of the GNU General Public License
16  *    along with this program; if not, write to the Free Software
17  *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  *    Questions/Comments/Bugfixes to Cciss-discuss@lists.sourceforge.net
20  *
21  */
22 
23 #include <linux/config.h>	/* CONFIG_PROC_FS */
24 #include <linux/module.h>
25 #include <linux/version.h>
26 #include <linux/types.h>
27 #include <linux/pci.h>
28 #include <linux/kernel.h>
29 #include <linux/slab.h>
30 #include <linux/delay.h>
31 #include <linux/major.h>
32 #include <linux/fs.h>
33 #include <linux/blkpg.h>
34 #include <linux/timer.h>
35 #include <linux/proc_fs.h>
36 #include <linux/init.h>
37 #include <linux/hdreg.h>
38 #include <linux/spinlock.h>
39 #include <asm/uaccess.h>
40 #include <asm/io.h>
41 #include <linux/smp_lock.h>
42 
43 #include <linux/blk.h>
44 #include <linux/blkdev.h>
45 #include <linux/genhd.h>
46 
47 #define CCISS_DRIVER_VERSION(maj,min,submin) ((maj<<16)|(min<<8)|(submin))
48 #define DRIVER_NAME "HP CISS Driver (v 2.4.60)"
49 #define DRIVER_VERSION CCISS_DRIVER_VERSION(2,4,60)
50 
51 /* Embedded module documentation macros - see modules.h */
52 MODULE_AUTHOR("Hewlett-Packard Company");
53 MODULE_DESCRIPTION("Driver for HP SA5xxx SA6xxx Controllers version 2.4.52");
54 MODULE_SUPPORTED_DEVICE("HP SA5i SA5i+ SA532 SA5300 SA5312 SA641 SA642 SA6400 6i SA6422 P600 P400 P400i E200i E200");
55 MODULE_LICENSE("GPL");
56 
57 #include "cciss_cmd.h"
58 #include "cciss.h"
59 #include <linux/cciss_ioctl.h>
60 
61 /* define the PCI info for the cards we can control */
62 const struct pci_device_id cciss_pci_device_id[] = {
63 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISS,
64 			0x0E11, 0x4070, 0, 0, 0},
65 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB,
66                         0x0E11, 0x4080, 0, 0, 0},
67 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB,
68                         0x0E11, 0x4082, 0, 0, 0},
69 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB,
70                         0x0E11, 0x4083, 0, 0, 0},
71 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
72                         0x0E11, 0x409A, 0, 0, 0},
73 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
74                         0x0E11, 0x409B, 0, 0, 0},
75 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
76                         0x0E11, 0x409C, 0, 0, 0},
77 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
78                         0x0E11, 0x409D, 0, 0, 0},
79 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
80                         0x0E11, 0x4091, 0, 0, 0},
81 	{ PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC,
82                         0x0E11, 0x409E, 0, 0, 0},
83 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSA,
84                         0x103C, 0x3225, 0, 0, 0},
85 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSC,
86                         0x103C, 0x3234, 0, 0, 0},
87 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSC,
88                         0x103C, 0x3235, 0, 0, 0},
89 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSD,
90                         0x103C, 0x3211, 0, 0, 0},
91 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSD,
92                         0x103C, 0x3212, 0, 0, 0},
93 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSD,
94                         0x103C, 0x3213, 0, 0, 0},
95 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSD,
96                         0x103C, 0x3214, 0, 0, 0},
97 	{ PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSD,
98                         0x103C, 0x3215, 0, 0, 0},
99 	{ PCI_VENDOR_ID_HP, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID,
100 		PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
101 	{0,}
102 };
103 MODULE_DEVICE_TABLE(pci, cciss_pci_device_id);
104 
105 #define NR_PRODUCTS (sizeof(products)/sizeof(struct board_type))
106 
107 /*  board_id = Subsystem Device ID & Vendor ID
108  *  product = Marketing Name for the board
109  *  access = Address of the struct of function pointers
110  */
111 static struct board_type products[] = {
112 	{ 0x40700E11, "Smart Array 5300", &SA5_access},
113 	{ 0x40800E11, "Smart Array 5i", &SA5B_access},
114 	{ 0x40820E11, "Smart Array 532", &SA5B_access},
115 	{ 0x40830E11, "Smart Array 5312", &SA5B_access},
116 	{ 0x409A0E11, "Smart Array 641", &SA5_access},
117 	{ 0x409B0E11, "Smart Array 642", &SA5_access},
118 	{ 0x409C0E11, "Smart Array 6400", &SA5_access},
119 	{ 0x409D0E11, "Smart Array 6400 EM", &SA5_access},
120 	{ 0x40910E11, "Smart Array 6i", &SA5_access},
121 	{ 0x409E0E11, "Smart Array 6422", &SA5_access},
122 	{ 0x3234103c, "Smart Array P400", &SA5_access},
123 	{ 0x3235103c, "Smart Array P400i", &SA5_access},
124 	{ 0x3211103c, "Smart Array E200i", &SA5_access},
125 	{ 0x3212103c, "Smart Array E200", &SA5_access},
126 	{ 0x3213103c, "Smart Array E200i", &SA5_access},
127 	{ 0x3214103c, "Smart Array E200i", &SA5_access},
128 	{ 0x3215103c, "Smart Array E200i", &SA5_access},
129 	{ 0xFFFF103C, "Unknown Smart Array", &SA5_access},
130 };
131 
132 /* How long to wait (in millesconds) for board to go into simple mode */
133 #define MAX_CONFIG_WAIT 30000
134 #define MAX_IOCTL_CONFIG_WAIT 1000
135 
136 /*define how many times we will try a command because of bus resets */
137 #define MAX_CMD_RETRIES 3
138 
139 #define READ_AHEAD 	 128
140 #define NR_CMDS		 128 /* #commands that can be outstanding */
141 #define MAX_CTLR	 32
142 
143 /* No sense in giving up our preallocated major numbers */
144 #if MAX_CTLR < 8
145 #error"cciss.c: MAX_CTLR must be 8 or greater"
146 #endif
147 
148 /* Originally cciss driver only supports 8 major number */
149 #define MAX_CTLR_ORIG  COMPAQ_CISS_MAJOR7 - COMPAQ_CISS_MAJOR + 1
150 
151 #define CCISS_DMA_MASK 0xFFFFFFFFFFFFFFFFULL /* 64 bit DMA */
152 
153 #ifdef CONFIG_CISS_MONITOR_THREAD
154 static int cciss_monitor(void *ctlr);
155 static int start_monitor_thread(ctlr_info_t *h, unsigned char *cmd,
156 		unsigned long count, int (*cciss_monitor)(void *), int *rc);
157 static u32 heartbeat_timer = 0;
158 #else
159 #define cciss_monitor(x)
160 #define kill_monitor_thead(x)
161 #endif
162 
163 static ctlr_info_t *hba[MAX_CTLR];
164 static int map_major_to_ctlr[MAX_BLKDEV] = {0}; /* gets ctlr num from maj num */
165 static struct proc_dir_entry *proc_cciss;
166 
167 static void do_cciss_request(request_queue_t *q);
168 static int cciss_open(struct inode *inode, struct file *filep);
169 static int cciss_release(struct inode *inode, struct file *filep);
170 static int cciss_ioctl(struct inode *inode, struct file *filep,
171 		unsigned int cmd, unsigned long arg);
172 
173 static int revalidate_logvol(kdev_t dev, int maxusage);
174 static int frevalidate_logvol(kdev_t dev);
175 static int deregister_disk(int ctlr, int logvol);
176 static int register_new_disk(int cltr, int opened_vol, __u64 requested_lun);
177 static int cciss_rescan_disk(int cltr, int logvol);
178 
179 static void cciss_getgeometry(int cntl_num);
180 
181 static inline void addQ(CommandList_struct **Qptr, CommandList_struct *c);
182 static void start_io( ctlr_info_t *h);
183 
184 #ifdef CONFIG_PROC_FS
185 static int cciss_proc_get_info(char *buffer, char **start, off_t offset,
186 		int length, int *eof, void *data);
187 static void cciss_procinit(int i);
188 #else
cciss_proc_get_info(char * buffer,char ** start,off_t offset,int length,int * eof,void * data)189 static int cciss_proc_get_info(char *buffer, char **start, off_t offset,
190 		int length, int *eof, void *data) { return 0;}
cciss_procinit(int i)191 static void cciss_procinit(int i) {}
192 #endif /* CONFIG_PROC_FS */
193 
194 /*
195  * Enqueuing and dequeuing functions for cmdlists.
196  */
addQ(CommandList_struct ** Qptr,CommandList_struct * c)197 static inline void addQ(CommandList_struct **Qptr, CommandList_struct *c)
198 {
199         if (*Qptr == NULL) {
200                 *Qptr = c;
201                 c->next = c->prev = c;
202         } else {
203                 c->prev = (*Qptr)->prev;
204                 c->next = (*Qptr);
205                 (*Qptr)->prev->next = c;
206                 (*Qptr)->prev = c;
207         }
208 }
209 
removeQ(CommandList_struct ** Qptr,CommandList_struct * c)210 static inline CommandList_struct *removeQ(CommandList_struct **Qptr,
211 						CommandList_struct *c)
212 {
213         if (c && c->next != c) {
214                 if (*Qptr == c) *Qptr = c->next;
215                 c->prev->next = c->next;
216                 c->next->prev = c->prev;
217         } else {
218                 *Qptr = NULL;
219         }
220         return c;
221 }
222 
223 static struct block_device_operations cciss_fops  = {
224 	owner:			THIS_MODULE,
225 	open:			cciss_open,
226 	release:        	cciss_release,
227         ioctl:			cciss_ioctl,
228 	revalidate:		frevalidate_logvol,
229 };
230 
231 #include "cciss_scsi.c"		/* For SCSI tape support */
232 
233 #define ENG_GIG	1048576000
234 #define ENG_GIG_FACTOR (ENG_GIG/512)
235 #define	RAID_UNKNOWN 6
236 static const char *raid_label[] = {"0","4","1(0+1)","5","5+1","ADG",
237 				   "UNKNOWN"};
238 /*
239  * Report information about this controller.
240  */
241 #ifdef CONFIG_PROC_FS
cciss_proc_get_info(char * buffer,char ** start,off_t offset,int length,int * eof,void * data)242 static int cciss_proc_get_info(char *buffer, char **start, off_t offset,
243 		int length, int *eof, void *data)
244 {
245 	off_t pos = 0;
246 	off_t len = 0;
247 	int size, i, ctlr;
248 	ctlr_info_t *h = (ctlr_info_t*)data;
249 	drive_info_struct *drv;
250 	unsigned long flags;
251 	unsigned int vol_sz, vol_sz_frac;
252 
253 	spin_lock_irqsave(&io_request_lock, flags);
254 	if (h->busy_configuring) {
255 		spin_unlock_irqrestore(&io_request_lock, flags);
256 		return -EBUSY;
257 	}
258 	h->busy_configuring = 1;
259 	spin_unlock_irqrestore(&io_request_lock, flags);
260 
261 	ctlr = h->ctlr;
262 	size = sprintf(buffer, "%s: HP %s Controller\n"
263  		"Board ID: 0x%08lx\n"
264 		"Firmware Version: %c%c%c%c\n"
265  		"IRQ: %d\n"
266  		"Logical drives: %d\n"
267  		"Current Q depth: %d\n"
268  		"Current # commands on controller: %d\n"
269  		"Max Q depth since init: %d\n"
270 		"Max # commands on controller since init: %d\n"
271 		"Max SG entries since init: %d\n"
272 		MONITOR_PERIOD_PATTERN
273 		MONITOR_DEADLINE_PATTERN
274 		MONITOR_STATUS_PATTERN
275 		"\n",
276   		h->devname,
277   		h->product_name,
278   		(unsigned long)h->board_id,
279   		h->firm_ver[0], h->firm_ver[1], h->firm_ver[2], h->firm_ver[3],
280   		(unsigned int)h->intr,
281   		h->num_luns,
282   		h->Qdepth, h->commands_outstanding,
283 		h->maxQsinceinit, h->max_outstanding, h->maxSG,
284 		MONITOR_PERIOD_VALUE(h),
285 		MONITOR_DEADLINE_VALUE(h),
286 		CTLR_STATUS(h));
287 
288 	pos += size; len += size;
289 	cciss_proc_tape_report(ctlr, buffer, &pos, &len);
290 	for(i=0; i<=h->highest_lun; i++) {
291 		drv = &h->drv[i];
292 		if (drv->nr_blocks == 0)
293 			continue;
294 		vol_sz = drv->nr_blocks/ENG_GIG_FACTOR;
295 		vol_sz_frac = (drv->nr_blocks%ENG_GIG_FACTOR)*100/ENG_GIG_FACTOR;
296 
297 		if (drv->raid_level > 5)
298 			drv->raid_level = RAID_UNKNOWN;
299 		size = sprintf(buffer+len, "cciss/c%dd%d:"
300 				"\t%4d.%02dGB\tRAID %s\n",
301 		       		 ctlr, i, vol_sz,vol_sz_frac,
302 				 raid_label[drv->raid_level]);
303 		pos += size, len += size;
304         }
305 
306 	*eof = 1;
307 	*start = buffer+offset;
308 	len -= offset;
309 	if (len>length)
310 		len = length;
311 	h->busy_configuring = 0;
312 	return len;
313 }
314 
315 static int
cciss_proc_write(struct file * file,const char * buffer,unsigned long count,void * data)316 cciss_proc_write(struct file *file, const char *buffer,
317 			unsigned long count, void *data)
318 {
319 	unsigned char cmd[80];
320 	int len;
321 	ctlr_info_t *h = (ctlr_info_t *) data;
322 	int rc;
323 
324 	if (count > sizeof(cmd)-1)
325 		return -EINVAL;
326 	if (copy_from_user(cmd, buffer, count))
327 		return -EFAULT;
328 	cmd[count] = '\0';
329 	len = strlen(cmd);
330 	if (cmd[len-1] == '\n')
331 		cmd[--len] = '\0';
332 
333 #	ifdef CONFIG_CISS_SCSI_TAPE
334 		if (strcmp("engage scsi", cmd)==0) {
335 			rc = cciss_engage_scsi(h->ctlr);
336 			if (rc != 0)
337 				return -rc;
338 			return count;
339 		}
340 		/* might be nice to have "disengage" too, but it's not
341 		   safely possible. (only 1 module use count, lock issues.) */
342 #	endif
343 
344 	if (START_MONITOR_THREAD(h, cmd, count, cciss_monitor, &rc) == 0)
345 		return rc;
346 
347 	return -EINVAL;
348 }
349 
350 /*
351  * Get us a file in /proc/cciss that says something about each controller.
352  * Create /proc/cciss if it doesn't exist yet.
353  */
cciss_procinit(int i)354 static void __init cciss_procinit(int i)
355 {
356 	struct proc_dir_entry *pde;
357 
358 	if (proc_cciss == NULL) {
359 		proc_cciss = proc_mkdir("cciss", proc_root_driver);
360 		if (!proc_cciss) {
361 			printk("cciss:  proc_mkdir failed\n");
362 			return;
363 		}
364 	}
365 
366 	pde = create_proc_read_entry(hba[i]->devname,
367 		S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH,
368 		proc_cciss, cciss_proc_get_info, hba[i]);
369 	pde->write_proc = cciss_proc_write;
370 }
371 #endif /* CONFIG_PROC_FS */
372 
373 /*
374  * For operations that cannot sleep, a command block is allocated at init,
375  * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
376  * which ones are free or in use.  For operations that can wait for kmalloc
377  * to possible sleep, this routine can be called with get_from_pool set to 0.
378  * cmd_free() MUST be called with a got_from_pool set to 0 if cmd_alloc was.
379  */
cmd_alloc(ctlr_info_t * h,int get_from_pool)380 static CommandList_struct * cmd_alloc(ctlr_info_t *h, int get_from_pool)
381 {
382 	CommandList_struct *c;
383 	int i;
384 	u64bit temp64;
385 	dma_addr_t cmd_dma_handle, err_dma_handle;
386 
387 	if (!get_from_pool) {
388 		c = (CommandList_struct *) pci_alloc_consistent(
389 			h->pdev, sizeof(CommandList_struct), &cmd_dma_handle);
390         	if (c==NULL)
391                  	return NULL;
392 		memset(c, 0, sizeof(CommandList_struct));
393 
394 		c->err_info = (ErrorInfo_struct *)pci_alloc_consistent(
395 					h->pdev, sizeof(ErrorInfo_struct),
396 					&err_dma_handle);
397 
398 		if (c->err_info == NULL)
399 		{
400 			pci_free_consistent(h->pdev,
401 				sizeof(CommandList_struct), c, cmd_dma_handle);
402 			return NULL;
403 		}
404 		memset(c->err_info, 0, sizeof(ErrorInfo_struct));
405 	} else /* get it out of the controllers pool */
406 	{
407 	     	do {
408                 	i = find_first_zero_bit(h->cmd_pool_bits, NR_CMDS);
409                         if (i == NR_CMDS)
410                                 return NULL;
411                 } while(test_and_set_bit(i%32, h->cmd_pool_bits+(i/32)) != 0);
412 #ifdef CCISS_DEBUG
413 		printk(KERN_DEBUG "cciss: using command buffer %d\n", i);
414 #endif
415                 c = h->cmd_pool + i;
416 		memset(c, 0, sizeof(CommandList_struct));
417 		cmd_dma_handle = h->cmd_pool_dhandle
418 					+ i*sizeof(CommandList_struct);
419 		c->err_info = h->errinfo_pool + i;
420 		memset(c->err_info, 0, sizeof(ErrorInfo_struct));
421 		err_dma_handle = h->errinfo_pool_dhandle
422 					+ i*sizeof(ErrorInfo_struct);
423                 h->nr_allocs++;
424         }
425 
426 	c->busaddr = (__u32) cmd_dma_handle;
427 	temp64.val = (__u64) err_dma_handle;
428 	c->ErrDesc.Addr.lower = temp64.val32.lower;
429 	c->ErrDesc.Addr.upper = temp64.val32.upper;
430 	c->ErrDesc.Len = sizeof(ErrorInfo_struct);
431 
432 	c->ctlr = h->ctlr;
433         return c;
434 
435 
436 }
437 
438 /*
439  * Frees a command block that was previously allocated with cmd_alloc().
440  */
cmd_free(ctlr_info_t * h,CommandList_struct * c,int got_from_pool)441 static void cmd_free(ctlr_info_t *h, CommandList_struct *c, int got_from_pool)
442 {
443 	int i;
444 	u64bit temp64;
445 
446 	if (!got_from_pool) {
447 		temp64.val32.lower = c->ErrDesc.Addr.lower;
448 		temp64.val32.upper = c->ErrDesc.Addr.upper;
449 		pci_free_consistent(h->pdev, sizeof(ErrorInfo_struct),
450 			c->err_info, (dma_addr_t) temp64.val);
451 		pci_free_consistent(h->pdev, sizeof(CommandList_struct),
452 			c, (dma_addr_t) c->busaddr);
453 	} else
454 	{
455 		i = c - h->cmd_pool;
456 		clear_bit(i%32, h->cmd_pool_bits+(i/32));
457                 h->nr_frees++;
458         }
459 }
460 
461 /*
462  * fills in the disk information.
463  */
cciss_geninit(int ctlr)464 static void cciss_geninit( int ctlr)
465 {
466 	drive_info_struct *drv;
467 	int i,j;
468 
469 	/* Loop through each real device */
470 	hba[ctlr]->gendisk.nr_real = 0;
471 	for(i=0; i< NWD; i++) {
472 		drv = &(hba[ctlr]->drv[i]);
473 		if (!(drv->nr_blocks))
474 			continue;
475 		hba[ctlr]->hd[i << NWD_SHIFT].nr_sects =
476 		hba[ctlr]->sizes[i << NWD_SHIFT] = drv->nr_blocks;
477 
478 		/* for each partition */
479 		for(j=0; j<MAX_PART; j++) {
480 			hba[ctlr]->blocksizes[(i<<NWD_SHIFT) + j] = 1024;
481 
482 			hba[ctlr]->hardsizes[ (i<<NWD_SHIFT) + j] =
483 				drv->block_size;
484 		}
485 	}
486 	hba[ctlr]->gendisk.nr_real = hba[ctlr]->highest_lun+1;
487 }
488 /*
489  * Open.  Make sure the device is really there.
490  */
cciss_open(struct inode * inode,struct file * filep)491 static int cciss_open(struct inode *inode, struct file *filep)
492 {
493  	int ctlr = map_major_to_ctlr[MAJOR(inode->i_rdev)];
494 	int dsk  = MINOR(inode->i_rdev) >> NWD_SHIFT;
495 
496 #ifdef CCISS_DEBUG
497 	printk(KERN_DEBUG "cciss_open %x (%x:%x)\n", inode->i_rdev, ctlr, dsk);
498 #endif /* CCISS_DEBUG */
499 
500 	if (ctlr > MAX_CTLR || hba[ctlr] == NULL || !CTLR_IS_ALIVE(hba[ctlr]))
501 		return -ENXIO;
502 	/*
503 	 * Root is allowed to open raw volume zero even if its not configured
504 	 * so array config can still work. Root is also allowed to open any
505 	 * volume that has a LUN ID, so it can issue IOCTL to reread the
506 	 * disk information.  I don't think I really like this.
507 	 * but I'm already using way to many device nodes to claim another one
508 	 * for "raw controller".
509 	 */
510 	if (hba[ctlr]->sizes[MINOR(inode->i_rdev)] == 0) { /* not online? */
511 		if (MINOR(inode->i_rdev) != 0) {	 /* not node 0? */
512 			/* if not node 0 make sure it is a partition = 0 */
513 			if (MINOR(inode->i_rdev) & 0x0f) {
514 				return -ENXIO;
515 				/* if it is, make sure we have a LUN ID */
516 			} else if (hba[ctlr]->drv[MINOR(inode->i_rdev)
517 					>> NWD_SHIFT].LunID == 0) {
518 				return -ENXIO;
519 			}
520 		}
521 		if (!capable(CAP_SYS_ADMIN))
522 			return -EPERM;
523 	}
524 
525 	hba[ctlr]->drv[dsk].usage_count++;
526 	hba[ctlr]->usage_count++;
527 	return 0;
528 }
529 /*
530  * Close.  Sync first.
531  */
cciss_release(struct inode * inode,struct file * filep)532 static int cciss_release(struct inode *inode, struct file *filep)
533 {
534 	int ctlr = map_major_to_ctlr[MAJOR(inode->i_rdev)];
535 	int dsk  = MINOR(inode->i_rdev) >> NWD_SHIFT;
536 
537 #ifdef CCISS_DEBUG
538 	printk(KERN_DEBUG "cciss_release %x (%x:%x)\n", inode->i_rdev, ctlr, dsk);
539 #endif /* CCISS_DEBUG */
540 
541 	/* fsync_dev(inode->i_rdev); */
542 
543 	hba[ctlr]->drv[dsk].usage_count--;
544 	hba[ctlr]->usage_count--;
545 	return 0;
546 }
547 
548 #ifdef __x86_64__
549 /* for AMD 64 bit kernel compatibility with 32-bit userland ioctls */
550 extern int sys_ioctl(unsigned int fd, unsigned cmd, unsigned long arg);
551 
552 extern int
553 register_ioctl32_conversion(unsigned int cmd, int (*handler)(unsigned int,
554       unsigned int, unsigned long, struct file *));
555 extern int unregister_ioctl32_conversion(unsigned int cmd);
556 
557 static int cciss_ioctl32_passthru(unsigned int fd, unsigned cmd, unsigned long arg, struct file *file);
558 static int cciss_ioctl32_big_passthru(unsigned int fd, unsigned cmd, unsigned long arg, struct file *file);
559 
560 typedef int (*handler_type) (unsigned int, unsigned int, unsigned long,
561 				struct file *);
562 
563 static struct ioctl32_map {
564 	unsigned int cmd;
565 	handler_type handler;
566 	int registered;
567 } cciss_ioctl32_map[] = {
568 	{ CCISS_GETPCIINFO,	(handler_type) sys_ioctl, 0 },
569 	{ CCISS_GETINTINFO,	(handler_type) sys_ioctl, 0 },
570 	{ CCISS_SETINTINFO,	(handler_type) sys_ioctl, 0 },
571 	{ CCISS_GETNODENAME,	(handler_type) sys_ioctl, 0 },
572 	{ CCISS_SETNODENAME,	(handler_type) sys_ioctl, 0 },
573 	{ CCISS_GETHEARTBEAT,	(handler_type) sys_ioctl, 0 },
574 	{ CCISS_GETBUSTYPES,	(handler_type) sys_ioctl, 0 },
575 	{ CCISS_GETFIRMVER,	(handler_type) sys_ioctl, 0 },
576 	{ CCISS_GETDRIVVER,	(handler_type) sys_ioctl, 0 },
577 	{ CCISS_REVALIDVOLS,	(handler_type) sys_ioctl, 0 },
578 	{ CCISS_PASSTHRU32,	cciss_ioctl32_passthru, 0 },
579 	{ CCISS_DEREGDISK,	(handler_type) sys_ioctl, 0 },
580 	{ CCISS_REGNEWDISK,	(handler_type) sys_ioctl, 0 },
581 	{ CCISS_REGNEWD,	(handler_type) sys_ioctl, 0 },
582 	{ CCISS_RESCANDISK,	(handler_type) sys_ioctl, 0 },
583 	{ CCISS_GETLUNINFO,	(handler_type) sys_ioctl, 0 },
584 	{ CCISS_BIG_PASSTHRU32,	cciss_ioctl32_big_passthru, 0 },
585 };
586 #define NCCISS_IOCTL32_ENTRIES (sizeof(cciss_ioctl32_map) / sizeof(cciss_ioctl32_map[0]))
register_cciss_ioctl32(void)587 static void register_cciss_ioctl32(void)
588 {
589 	int i, rc;
590 
591 	for (i=0; i < NCCISS_IOCTL32_ENTRIES; i++) {
592 		rc = register_ioctl32_conversion(
593 			cciss_ioctl32_map[i].cmd,
594 			cciss_ioctl32_map[i].handler);
595 		if (rc != 0) {
596 			printk(KERN_WARNING "cciss: failed to register "
597 				"32 bit compatible ioctl 0x%08x\n",
598 				cciss_ioctl32_map[i].cmd);
599 			cciss_ioctl32_map[i].registered = 0;
600 		} else
601 			cciss_ioctl32_map[i].registered = 1;
602 	}
603 }
unregister_cciss_ioctl32(void)604 static void unregister_cciss_ioctl32(void)
605 {
606 	int i, rc;
607 
608 	for (i=0; i < NCCISS_IOCTL32_ENTRIES; i++) {
609 		if (!cciss_ioctl32_map[i].registered)
610 			continue;
611 		rc = unregister_ioctl32_conversion(
612 			cciss_ioctl32_map[i].cmd);
613 		if (rc == 0) {
614 			cciss_ioctl32_map[i].registered = 0;
615 			continue;
616 		}
617 		printk(KERN_WARNING "cciss: failed to unregister "
618 			"32 bit compatible ioctl 0x%08x\n",
619 			cciss_ioctl32_map[i].cmd);
620 	}
621 }
cciss_ioctl32_passthru(unsigned int fd,unsigned cmd,unsigned long arg,struct file * file)622 int cciss_ioctl32_passthru(unsigned int fd, unsigned cmd, unsigned long arg,
623 				struct file *file)
624 {
625 	IOCTL32_Command_struct *arg32 =
626 		(IOCTL32_Command_struct *) arg;
627 	IOCTL_Command_struct arg64;
628 	mm_segment_t old_fs;
629 	int err;
630 	__u64 tmp_ptr;
631 
632 	err = 0;
633 	err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info, sizeof(arg64.LUN_info));
634 	err |= copy_from_user(&arg64.Request, &arg32->Request, sizeof(arg64.Request));
635 	err |= copy_from_user(&arg64.error_info, &arg32->error_info, sizeof(arg64.error_info));
636 	err |= get_user(arg64.buf_size, &arg32->buf_size);
637 	err |= get_user(tmp_ptr, &arg32->buf);
638 	arg64.buf = (BYTE *) tmp_ptr;
639 	if (err)
640 		return -EFAULT;
641 
642 	old_fs = get_fs();
643 	set_fs(KERNEL_DS);
644 	err = sys_ioctl(fd, CCISS_PASSTHRU, (unsigned long) &arg64);
645 	set_fs(old_fs);
646 	if (err)
647 		return err;
648 	err |= copy_to_user(&arg32->error_info, &arg64.error_info, sizeof(arg32->error_info));
649 	if (err)
650 		return -EFAULT;
651 	return err;
652 }
cciss_ioctl32_big_passthru(unsigned int fd,unsigned cmd,unsigned long arg,struct file * file)653 int cciss_ioctl32_big_passthru(unsigned int fd, unsigned cmd, unsigned long arg,
654 					struct file *file)
655 {
656 	BIG_IOCTL32_Command_struct *arg32 =
657 		(BIG_IOCTL32_Command_struct *) arg;
658 	BIG_IOCTL_Command_struct arg64;
659 	mm_segment_t old_fs;
660 	int err;
661 	__u64 tmp_ptr;
662 
663 	err = 0;
664 	err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info, sizeof(arg64.LUN_info));
665 	err |= copy_from_user(&arg64.Request, &arg32->Request, sizeof(arg64.Request));
666 	err |= copy_from_user(&arg64.error_info, &arg32->error_info, sizeof(arg64.error_info));
667 	err |= get_user(arg64.buf_size, &arg32->buf_size);
668 	err |= get_user(arg64.malloc_size, &arg32->malloc_size);
669 	err |= get_user(tmp_ptr, &arg32->buf);
670 	arg64.buf = (BYTE *) tmp_ptr;
671 	if (err) return -EFAULT;
672 	old_fs = get_fs();
673 	set_fs(KERNEL_DS);
674 	err = sys_ioctl(fd, CCISS_BIG_PASSTHRU, (unsigned long) &arg64);
675 	set_fs(old_fs);
676 	if (err)
677 		return err;
678 	err |= copy_to_user(&arg32->error_info, &arg64.error_info, sizeof(arg32->error_info));
679 	if (err)
680 		return -EFAULT;
681 	return err;
682 }
683 #else
register_cciss_ioctl32(void)684 static inline void register_cciss_ioctl32(void) {}
unregister_cciss_ioctl32(void)685 static inline void unregister_cciss_ioctl32(void) {}
686 #endif
687 
688 /*
689  * ioctl
690  */
cciss_ioctl(struct inode * inode,struct file * filep,unsigned int cmd,unsigned long arg)691 static int cciss_ioctl(struct inode *inode, struct file *filep,
692 		unsigned int cmd, unsigned long arg)
693 {
694 	int ctlr = map_major_to_ctlr[MAJOR(inode->i_rdev)];
695 	int dsk  = MINOR(inode->i_rdev) >> NWD_SHIFT;
696 
697 #ifdef CCISS_DEBUG
698 	printk(KERN_DEBUG "cciss_ioctl: Called with cmd=%x %lx\n", cmd, arg);
699 #endif /* CCISS_DEBUG */
700 
701 	switch(cmd) {
702 	   case HDIO_GETGEO:
703 	   {
704 		struct hd_geometry driver_geo;
705 		if (hba[ctlr]->drv[dsk].cylinders) {
706 			driver_geo.heads = hba[ctlr]->drv[dsk].heads;
707 			driver_geo.sectors = hba[ctlr]->drv[dsk].sectors;
708 			driver_geo.cylinders = hba[ctlr]->drv[dsk].cylinders;
709 		} else
710 			return -ENXIO;
711 		driver_geo.start=
712 			hba[ctlr]->hd[MINOR(inode->i_rdev)].start_sect;
713 		if (copy_to_user((void *) arg, &driver_geo,
714 				sizeof( struct hd_geometry)))
715 			return  -EFAULT;
716 		return 0;
717 	   }
718 	case HDIO_GETGEO_BIG:
719 	{
720 		struct hd_big_geometry driver_geo;
721 		if (hba[ctlr]->drv[dsk].cylinders) {
722 			driver_geo.heads = hba[ctlr]->drv[dsk].heads;
723 			driver_geo.sectors = hba[ctlr]->drv[dsk].sectors;
724 			driver_geo.cylinders = hba[ctlr]->drv[dsk].cylinders;
725 		} else
726 			return -ENXIO;
727 		driver_geo.start=
728 		hba[ctlr]->hd[MINOR(inode->i_rdev)].start_sect;
729 		if (copy_to_user((void *) arg, &driver_geo,
730 				sizeof( struct hd_big_geometry)))
731 			return  -EFAULT;
732 		return 0;
733 	}
734 	case BLKRRPART:
735 		if (!capable(CAP_SYS_ADMIN))
736 			return -EPERM;
737 		return revalidate_logvol(inode->i_rdev, 1);
738 	case BLKGETSIZE:
739 	case BLKGETSIZE64:
740 	case BLKFLSBUF:
741 	case BLKBSZSET:
742 	case BLKBSZGET:
743 	case BLKROSET:
744 	case BLKROGET:
745 	case BLKRASET:
746 	case BLKRAGET:
747 	case BLKPG:
748 	case BLKELVGET:
749 	case BLKELVSET:
750 		return blk_ioctl(inode->i_rdev, cmd, arg);
751 	case CCISS_GETPCIINFO:
752 	{
753 		cciss_pci_info_struct pciinfo;
754 
755 		if (!arg)
756 			return -EINVAL;
757 		pciinfo.bus = hba[ctlr]->pdev->bus->number;
758 		pciinfo.dev_fn = hba[ctlr]->pdev->devfn;
759 		pciinfo.board_id = hba[ctlr]->board_id;
760 		if (copy_to_user((void *) arg, &pciinfo,  sizeof( cciss_pci_info_struct )))
761 			return  -EFAULT;
762 		return 0;
763 	}
764 	case CCISS_GETINTINFO:
765 	{
766 		cciss_coalint_struct intinfo;
767 		ctlr_info_t *c = hba[ctlr];
768 
769 		if (!arg)
770 			return -EINVAL;
771 		intinfo.delay = readl(&c->cfgtable->HostWrite.CoalIntDelay);
772 		intinfo.count = readl(&c->cfgtable->HostWrite.CoalIntCount);
773 		if (copy_to_user((void *) arg, &intinfo, sizeof( cciss_coalint_struct )))
774 			return -EFAULT;
775                 return 0;
776         }
777 	case CCISS_SETINTINFO:
778         {
779                 cciss_coalint_struct intinfo;
780                 ctlr_info_t *c = hba[ctlr];
781 		unsigned long flags;
782 		int i;
783 
784 		if (!arg)
785 			return -EINVAL;
786 		if (!capable(CAP_SYS_ADMIN))
787 			return -EPERM;
788 		if (copy_from_user(&intinfo, (void *) arg, sizeof( cciss_coalint_struct)))
789 			return -EFAULT;
790 		if ( (intinfo.delay == 0 ) && (intinfo.count == 0)) {
791 			return -EINVAL;
792 		}
793 
794 		spin_lock_irqsave(&io_request_lock, flags);
795 		/* Can only safely update if no commands outstanding */
796 		if (c->commands_outstanding > 0 ) {
797 			spin_unlock_irqrestore(&io_request_lock, flags);
798 			return -EINVAL;
799 		}
800 		/* Update the field, and then ring the doorbell */
801 		writel( intinfo.delay,
802 			&(c->cfgtable->HostWrite.CoalIntDelay));
803 		writel( intinfo.count,
804                         &(c->cfgtable->HostWrite.CoalIntCount));
805 		writel( CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
806 
807 		for(i=0;i<MAX_IOCTL_CONFIG_WAIT;i++) {
808 			if (!(readl(c->vaddr + SA5_DOORBELL)
809 					& CFGTBL_ChangeReq))
810 				break;
811 			/* delay and try again */
812 			udelay(1000);
813 		}
814 		spin_unlock_irqrestore(&io_request_lock, flags);
815 		if (i >= MAX_IOCTL_CONFIG_WAIT)
816 			/* there is an unlikely case where this can happen,
817 			 * involving hot replacing a failed 144 GB drive in a
818 			 * RAID 5 set just as we attempt this ioctl. */
819 			return -EAGAIN;
820                 return 0;
821         }
822 	case CCISS_GETNODENAME:
823         {
824                 NodeName_type NodeName;
825                 ctlr_info_t *c = hba[ctlr];
826 		int i;
827 
828 		if (!arg)
829 			return -EINVAL;
830 		for(i=0;i<16;i++)
831 			NodeName[i] = readb(&c->cfgtable->ServerName[i]);
832                 if (copy_to_user((void *) arg, NodeName, sizeof( NodeName_type)))
833                 	return  -EFAULT;
834                 return 0;
835         }
836 	case CCISS_SETNODENAME:
837 	{
838 		NodeName_type NodeName;
839 		ctlr_info_t *c = hba[ctlr];
840 		unsigned long flags;
841 		int i;
842 
843 		if (!arg)
844 			return -EINVAL;
845 		if (!capable(CAP_SYS_ADMIN))
846 			return -EPERM;
847 
848 		if (copy_from_user(NodeName, (void *) arg, sizeof( NodeName_type)))
849 			return -EFAULT;
850 
851 		spin_lock_irqsave(&io_request_lock, flags);
852 
853 			/* Update the field, and then ring the doorbell */
854 		for(i=0;i<16;i++)
855 			writeb( NodeName[i], &c->cfgtable->ServerName[i]);
856 
857 		writel( CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
858 
859 		for(i=0;i<MAX_IOCTL_CONFIG_WAIT;i++) {
860 			if (!(readl(c->vaddr + SA5_DOORBELL)
861 					& CFGTBL_ChangeReq))
862 				break;
863 			/* delay and try again */
864 			udelay(1000);
865 		}
866 		spin_unlock_irqrestore(&io_request_lock, flags);
867 		if (i >= MAX_IOCTL_CONFIG_WAIT)
868 			/* there is an unlikely case where this can happen,
869 			 * involving hot replacing a failed 144 GB drive in a
870 			 * RAID 5 set just as we attempt this ioctl. */
871 			return -EAGAIN;
872                 return 0;
873         }
874 
875 	case CCISS_GETHEARTBEAT:
876         {
877                 Heartbeat_type heartbeat;
878                 ctlr_info_t *c = hba[ctlr];
879 
880 		if (!arg)
881 			return -EINVAL;
882                 heartbeat = readl(&c->cfgtable->HeartBeat);
883                 if (copy_to_user((void *) arg, &heartbeat, sizeof( Heartbeat_type)))
884                 	return -EFAULT;
885                 return 0;
886         }
887 	case CCISS_GETBUSTYPES:
888         {
889                 BusTypes_type BusTypes;
890                 ctlr_info_t *c = hba[ctlr];
891 
892 		if (!arg)
893 			return -EINVAL;
894                 BusTypes = readl(&c->cfgtable->BusTypes);
895                 if (copy_to_user((void *) arg, &BusTypes, sizeof( BusTypes_type) ))
896                 	return  -EFAULT;
897                 return 0;
898         }
899 	case CCISS_GETFIRMVER:
900         {
901 		FirmwareVer_type firmware;
902 
903 		if (!arg)
904 			return -EINVAL;
905 		memcpy(firmware, hba[ctlr]->firm_ver, 4);
906 
907                 if (copy_to_user((void *) arg, firmware, sizeof( FirmwareVer_type)))
908                 	return -EFAULT;
909                 return 0;
910         }
911         case CCISS_GETDRIVVER:
912         {
913 		DriverVer_type DriverVer = DRIVER_VERSION;
914 
915                 if (!arg)
916 			return -EINVAL;
917 
918                 if (copy_to_user((void *) arg, &DriverVer, sizeof( DriverVer_type) ))
919                 	return -EFAULT;
920                 return 0;
921         }
922 	case CCISS_RESCANDISK:
923 	{
924 		return cciss_rescan_disk(ctlr, dsk);
925 	}
926 	case CCISS_DEREGDISK:
927 		return deregister_disk(ctlr,dsk);
928 
929 	case CCISS_REGNEWD:
930 		return register_new_disk(ctlr, dsk, 0);
931 	case CCISS_REGNEWDISK:
932 	{
933 		__u64 new_logvol;
934 
935 		if (!arg)
936 			return -EINVAL;
937 		if (copy_from_user(&new_logvol, (void *) arg,
938 			sizeof( __u64)))
939 			return -EFAULT;
940 		return register_new_disk(ctlr, dsk, new_logvol);
941 	}
942 	case CCISS_GETLUNINFO:
943 	{
944 		LogvolInfo_struct luninfo;
945 		int num_parts = 0;
946 		int i, start;
947 
948 		luninfo.LunID = hba[ctlr]->drv[dsk].LunID;
949 		luninfo.num_opens = hba[ctlr]->drv[dsk].usage_count;
950 
951 		/* count partitions 1 to 15 with sizes > 0 */
952   		start = (dsk << NWD_SHIFT);
953 		for(i=1; i <MAX_PART; i++) {
954 			int minor = start+i;
955 			if (hba[ctlr]->sizes[minor] != 0)
956 				num_parts++;
957 		}
958 		luninfo.num_parts = num_parts;
959 		if (copy_to_user((void *) arg, &luninfo,
960 				sizeof( LogvolInfo_struct) ))
961 			return -EFAULT;
962 		return 0;
963 	}
964 	case CCISS_PASSTHRU:
965 	{
966 		IOCTL_Command_struct iocommand;
967 		ctlr_info_t *h = hba[ctlr];
968 		CommandList_struct *c;
969 		char 	*buff = NULL;
970 		u64bit	temp64;
971 		unsigned long flags;
972 		DECLARE_COMPLETION(wait);
973 
974 		if (!arg)
975 			return -EINVAL;
976 
977 		if (!capable(CAP_SYS_RAWIO))
978 			return -EPERM;
979 
980 		if (copy_from_user(&iocommand, (void *) arg, sizeof( IOCTL_Command_struct) ))
981 			return -EFAULT;
982 		if ((iocommand.buf_size < 1) &&
983 				(iocommand.Request.Type.Direction
984 				 	!= XFER_NONE)) {
985 			return -EINVAL;
986 		}
987 		/* Check kmalloc limits */
988 		if (iocommand.buf_size > 128000)
989 			return -EINVAL;
990 		if (iocommand.buf_size > 0) {
991 			buff =  kmalloc(iocommand.buf_size, GFP_KERNEL);
992 			if (buff == NULL)
993 				return -ENOMEM;
994 		}
995 		if (iocommand.Request.Type.Direction == XFER_WRITE) {
996 			/* Copy the data into the buffer we created */
997 			if (copy_from_user(buff, iocommand.buf, iocommand.buf_size))
998 			{
999 				kfree(buff);
1000 				return -EFAULT;
1001 			}
1002 		}
1003 		else
1004 			memset(buff, 0, iocommand.buf_size);
1005 		if ((c = cmd_alloc(h , 0)) == NULL) {
1006 			kfree(buff);
1007 			return -ENOMEM;
1008 		}
1009 			/* Fill in the command type */
1010 		c->cmd_type = CMD_IOCTL_PEND;
1011 			/* Fill in Command Header */
1012 		c->Header.ReplyQueue = 0;  /* unused in simple mode */
1013 		if (iocommand.buf_size > 0) { 	/* buffer to fill */
1014 			c->Header.SGList = 1;
1015 			c->Header.SGTotal= 1;
1016 		} else	{  /* no buffers to fill  */
1017 			c->Header.SGList = 0;
1018                 	c->Header.SGTotal= 0;
1019 		}
1020 		c->Header.LUN = iocommand.LUN_info;
1021 		c->Header.Tag.lower = c->busaddr;  /* use the kernel address */
1022 						/* the cmd block for tag */
1023 
1024 		/* Fill in Request block */
1025 		c->Request = iocommand.Request;
1026 
1027 		/* Fill in the scatter gather information */
1028 		if (iocommand.buf_size > 0 ) {
1029 			temp64.val = pci_map_single( h->pdev, buff,
1030                                         iocommand.buf_size,
1031                                 PCI_DMA_BIDIRECTIONAL);
1032 			c->SG[0].Addr.lower = temp64.val32.lower;
1033 			c->SG[0].Addr.upper = temp64.val32.upper;
1034 			c->SG[0].Len = iocommand.buf_size;
1035 			c->SG[0].Ext = 0;  /* we are not chaining */
1036 		}
1037 		c->waiting = &wait;
1038 
1039 		/* Put the request on the tail of the request queue */
1040 		spin_lock_irqsave(&io_request_lock, flags);
1041 		addQ(&h->reqQ, c);
1042 		h->Qdepth++;
1043 		start_io(h);
1044 		spin_unlock_irqrestore(&io_request_lock, flags);
1045 
1046 		wait_for_completion(&wait);
1047 
1048 		/* unlock the buffers from DMA */
1049 		temp64.val32.lower = c->SG[0].Addr.lower;
1050                 temp64.val32.upper = c->SG[0].Addr.upper;
1051                 pci_unmap_single( h->pdev, (dma_addr_t) temp64.val,
1052                 	iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
1053 
1054 		/* Copy the error information out */
1055 		iocommand.error_info = *(c->err_info);
1056 		if (copy_to_user((void *) arg, &iocommand,
1057 				sizeof( IOCTL_Command_struct) ) ) {
1058 			kfree(buff);
1059 			cmd_free(h, c, 0);
1060 			return( -EFAULT);
1061 		}
1062 
1063 		if (iocommand.Request.Type.Direction == XFER_READ) {
1064                         /* Copy the data out of the buffer we created */
1065                         if (copy_to_user(iocommand.buf, buff,
1066 						iocommand.buf_size)) {
1067                         	kfree(buff);
1068 				cmd_free(h, c, 0);
1069 				return -EFAULT;
1070 			}
1071                 }
1072                 kfree(buff);
1073 		cmd_free(h, c, 0);
1074                 return 0;
1075 	}
1076 	case CCISS_BIG_PASSTHRU:
1077 	{
1078 		BIG_IOCTL_Command_struct iocommand;
1079 		ctlr_info_t *h = hba[ctlr];
1080 		CommandList_struct *c;
1081 		char 	*buff[MAXSGENTRIES] = {NULL,};
1082 		int	buff_size[MAXSGENTRIES] = {0,};
1083 		u64bit	temp64;
1084 		unsigned long flags;
1085 		BYTE sg_used = 0;
1086 		int status = 0;
1087 		int i;
1088 		DECLARE_COMPLETION(wait);
1089 
1090 		if (!arg)
1091 			return -EINVAL;
1092 
1093 		if (!capable(CAP_SYS_RAWIO))
1094 			return -EPERM;
1095 
1096 		if (copy_from_user(&iocommand, (void *) arg, sizeof( BIG_IOCTL_Command_struct) ))
1097 			return -EFAULT;
1098 		if ((iocommand.buf_size < 1) &&
1099 			(iocommand.Request.Type.Direction != XFER_NONE)) {
1100 			return -EINVAL;
1101 		}
1102 		/* Check kmalloc limits  using all SGs */
1103 		if (iocommand.malloc_size > MAX_KMALLOC_SIZE)
1104 			return -EINVAL;
1105 		if (iocommand.buf_size > iocommand.malloc_size * MAXSGENTRIES)
1106 			return -EINVAL;
1107 		if (iocommand.buf_size > 0) {
1108 			__u32   size_left_alloc = iocommand.buf_size;
1109 			BYTE    *data_ptr = (BYTE *) iocommand.buf;
1110 			while (size_left_alloc > 0) {
1111 				buff_size[sg_used] = (size_left_alloc
1112 							> iocommand.malloc_size)
1113 					? iocommand.malloc_size : size_left_alloc;
1114 				buff[sg_used] = kmalloc( buff_size[sg_used],
1115 						GFP_KERNEL);
1116 				if (buff[sg_used] == NULL) {
1117 					status = -ENOMEM;
1118 					goto cleanup1;
1119 				}
1120 				if (iocommand.Request.Type.Direction ==
1121 						XFER_WRITE) {
1122 				   /* Copy the data into the buffer created */
1123 				   if (copy_from_user(buff[sg_used], data_ptr,
1124 						buff_size[sg_used])) {
1125 					status = -EFAULT;
1126 					goto cleanup1;
1127 				   }
1128 				   }
1129 				else
1130 					memset(buff[sg_used], 0, buff_size[sg_used]);
1131 				size_left_alloc -= buff_size[sg_used];
1132 				data_ptr += buff_size[sg_used];
1133 				sg_used++;
1134 			}
1135 
1136 		}
1137 		if ((c = cmd_alloc(h , 0)) == NULL) {
1138 			status = -ENOMEM;
1139 			goto cleanup1;
1140 		}
1141 		/* Fill in the command type */
1142 		c->cmd_type = CMD_IOCTL_PEND;
1143 		/* Fill in Command Header */
1144 		c->Header.ReplyQueue = 0;  /* unused in simple mode */
1145 
1146 		if (iocommand.buf_size > 0) { 	/* buffer to fill */
1147 			c->Header.SGList = sg_used;
1148 			c->Header.SGTotal= sg_used;
1149 		} else	{	/* no buffers to fill */
1150 			c->Header.SGList = 0;
1151 			c->Header.SGTotal= 0;
1152 		}
1153 		c->Header.LUN = iocommand.LUN_info;
1154 		c->Header.Tag.lower = c->busaddr;  /* use the kernel address */
1155 						/* the cmd block for tag */
1156 
1157 	/* Fill in Request block */
1158 	c->Request = iocommand.Request;
1159 	/* Fill in the scatter gather information */
1160 	if (iocommand.buf_size > 0 ) {
1161 		int i;
1162 		for(i=0; i< sg_used; i++) {
1163 			temp64.val = pci_map_single( h->pdev, buff[i],
1164 					buff_size[i],
1165 					PCI_DMA_BIDIRECTIONAL);
1166 
1167 			c->SG[i].Addr.lower = temp64.val32.lower;
1168 			c->SG[i].Addr.upper = temp64.val32.upper;
1169 			c->SG[i].Len = buff_size[i];
1170 			c->SG[i].Ext = 0;  /* we are not chaining */
1171 		}
1172 	}
1173 	c->waiting = &wait;
1174 	/* Put the request on the tail of the request queue */
1175 	spin_lock_irqsave(&io_request_lock, flags);
1176 	addQ(&h->reqQ, c);
1177 	h->Qdepth++;
1178 	start_io(h);
1179 	spin_unlock_irqrestore(&io_request_lock, flags);
1180 	wait_for_completion(&wait);
1181 	/* unlock the buffers from DMA */
1182 	for(i=0; i< sg_used; i++) {
1183 		temp64.val32.lower = c->SG[i].Addr.lower;
1184 		temp64.val32.upper = c->SG[i].Addr.upper;
1185 		pci_unmap_single( h->pdev, (dma_addr_t) temp64.val,
1186 				buff_size[i], PCI_DMA_BIDIRECTIONAL);
1187 	}
1188 	/* Copy the error information out */
1189 		iocommand.error_info = *(c->err_info);
1190 		if (copy_to_user((void *) arg, &iocommand,
1191 					sizeof( IOCTL_Command_struct) ) ) {
1192 				cmd_free(h, c, 0);
1193 				status = -EFAULT;
1194 				goto cleanup1;
1195 		}
1196 		if (iocommand.Request.Type.Direction == XFER_READ) {
1197 		/* Copy the data out of the buffer we created */
1198 			BYTE *ptr = (BYTE  *) iocommand.buf;
1199 	        	for(i=0; i< sg_used; i++) {
1200 				if (copy_to_user(ptr, buff[i], buff_size[i])) {
1201 					cmd_free(h, c, 0);
1202 					status = -EFAULT;
1203 					goto cleanup1;
1204 
1205 				}
1206 				ptr += buff_size[i];
1207 			}
1208 		}
1209 		cmd_free(h, c, 0);
1210 		status = 0;
1211 
1212 
1213 cleanup1:
1214 		for(i=0; i< sg_used; i++) {
1215 			if (buff[i] != NULL)
1216 				kfree(buff[i]);
1217 		}
1218 		return status;
1219 	}
1220 	default:
1221 		return -EBADRQC;
1222 	}
1223 
1224 }
1225 
1226 /* Borrowed and adapted from sd.c */
revalidate_logvol(kdev_t dev,int maxusage)1227 static int revalidate_logvol(kdev_t dev, int maxusage)
1228 {
1229         int ctlr, target;
1230         struct gendisk *gdev;
1231         unsigned long flags;
1232         int max_p;
1233         int start;
1234         int i;
1235 
1236         target = MINOR(dev) >> NWD_SHIFT;
1237 	ctlr = map_major_to_ctlr[MAJOR(dev)];
1238         gdev = &(hba[ctlr]->gendisk);
1239 
1240         spin_lock_irqsave(&io_request_lock, flags);
1241         if (hba[ctlr]->drv[target].usage_count > maxusage) {
1242                 spin_unlock_irqrestore(&io_request_lock, flags);
1243                 printk(KERN_WARNING "cciss: Device busy for "
1244                         "revalidation (usage=%d)\n",
1245                         hba[ctlr]->drv[target].usage_count);
1246                 return -EBUSY;
1247         }
1248         hba[ctlr]->drv[target].usage_count++;
1249         spin_unlock_irqrestore(&io_request_lock, flags);
1250 
1251         max_p = gdev->max_p;
1252         start = target << gdev->minor_shift;
1253 
1254         for(i=max_p-1; i>=0; i--) {
1255                 int minor = start+i;
1256                 invalidate_device(MKDEV(hba[ctlr]->major, minor), 1);
1257                 gdev->part[minor].start_sect = 0;
1258                 gdev->part[minor].nr_sects = 0;
1259 
1260                 /* reset the blocksize so we can read the partition table */
1261                 blksize_size[hba[ctlr]->major][minor] = 1024;
1262         }
1263 	/* setup partitions per disk */
1264 	grok_partitions(gdev, target, MAX_PART,
1265 			hba[ctlr]->drv[target].nr_blocks);
1266         hba[ctlr]->drv[target].usage_count--;
1267         return 0;
1268 }
1269 
frevalidate_logvol(kdev_t dev)1270 static int frevalidate_logvol(kdev_t dev)
1271 {
1272 #ifdef CCISS_DEBUG
1273 	printk(KERN_DEBUG "cciss: frevalidate has been called\n");
1274 #endif /* CCISS_DEBUG */
1275 	return revalidate_logvol(dev, 0);
1276 }
deregister_disk(int ctlr,int logvol)1277 static int deregister_disk(int ctlr, int logvol)
1278 {
1279 	unsigned long flags;
1280 	struct gendisk *gdev = &(hba[ctlr]->gendisk);
1281 	ctlr_info_t  *h = hba[ctlr];
1282 	int start, max_p, i;
1283 
1284 	if (!capable(CAP_SYS_RAWIO))
1285 		return -EPERM;
1286 
1287 	spin_lock_irqsave(&io_request_lock, flags);
1288 	/* make sure logical volume is NOT is use */
1289 	if (h->drv[logvol].usage_count > 1 || h->busy_configuring) {
1290 		spin_unlock_irqrestore(&io_request_lock, flags);
1291 		return -EBUSY;
1292 	}
1293 	h->busy_configuring = 1;
1294 	spin_unlock_irqrestore(&io_request_lock, flags);
1295 
1296 	/* invalidate the devices and deregister the disk */
1297 	max_p = gdev->max_p;
1298 	start = logvol << gdev->minor_shift;
1299 	for (i=max_p-1; i>=0; i--) {
1300 		int minor = start+i;
1301 		/* printk("invalidating( %d %d)\n", ctlr, minor); */
1302 		invalidate_device(MKDEV(hba[ctlr]->major, minor), 1);
1303 		/* so open will now fail */
1304 		h->sizes[minor] = 0;
1305 		/* so it will no longer appear in /proc/partitions */
1306 		gdev->part[minor].start_sect = 0;
1307 		gdev->part[minor].nr_sects = 0;
1308 	}
1309 	/* check to see if it was the last disk */
1310 	if (logvol == h->highest_lun) {
1311 		/* if so, find the new hightest lun */
1312 		int i, newhighest =-1;
1313 		for(i=0; i<h->highest_lun; i++) {
1314 			/* if the disk has size > 0, it is available */
1315 			if (h->sizes[i << gdev->minor_shift] != 0)
1316 				newhighest = i;
1317 		}
1318 		h->highest_lun = newhighest;
1319 
1320 	}
1321 	--h->num_luns;
1322 	gdev->nr_real = h->highest_lun+1;
1323 	/* zero out the disk size info */
1324 	h->drv[logvol].nr_blocks = 0;
1325 	h->drv[logvol].block_size = 0;
1326 	h->drv[logvol].cylinders = 0;
1327 	h->drv[logvol].LunID = 0;
1328 	h->busy_configuring = 0;
1329 	return 0;
1330 }
sendcmd_withirq(__u8 cmd,int ctlr,void * buff,size_t size,unsigned int use_unit_num,unsigned int log_unit,__u8 page_code,__u8 cmdtype)1331 static int sendcmd_withirq(__u8	cmd,
1332 	int	ctlr,
1333 	void	*buff,
1334 	size_t	size,
1335 	unsigned int use_unit_num,
1336 	unsigned int log_unit,
1337 	__u8	page_code,
1338 	__u8 cmdtype)
1339 {
1340 	ctlr_info_t *h = hba[ctlr];
1341 	CommandList_struct *c;
1342 	u64bit	buff_dma_handle;
1343 	unsigned long flags;
1344 	int return_status = IO_OK;
1345 	DECLARE_COMPLETION(wait);
1346 
1347 	if ((c = cmd_alloc(h , 0)) == NULL)
1348 		return -ENOMEM;
1349 	c->cmd_type = CMD_IOCTL_PEND;
1350 	/* Fill in Command Header */
1351 	c->Header.ReplyQueue = 0;  /* unused in simple mode */
1352 	if (buff != NULL) { 	/* buffer to fill */
1353 		c->Header.SGList = 1;
1354 		c->Header.SGTotal= 1;
1355 	} else {
1356 		/* no buffers to fill */
1357 		c->Header.SGList = 0;
1358 		c->Header.SGTotal= 0;
1359 	}
1360 	c->Header.Tag.lower = c->busaddr;  /* tag is phys addr of cmd */
1361 	/* Fill in Request block */
1362 	c->Request.CDB[0] = cmd;
1363 	c->Request.Type.Type = cmdtype;
1364 	if (cmdtype == TYPE_CMD) {
1365 	switch (cmd) {
1366 		case  CISS_INQUIRY:
1367 			/* If the logical unit number is 0 then, this is going
1368 				to controller so It's a physical command
1369 				mode = 0 target = 0.
1370 				So we have nothing to write.
1371 				Otherwise
1372 				mode = 1  target = LUNID
1373 			*/
1374 			if (use_unit_num != 0) {
1375 				c->Header.LUN.LogDev.VolId =
1376 					hba[ctlr]->drv[log_unit].LunID;
1377 				c->Header.LUN.LogDev.Mode = 1;
1378 			}
1379 			if (page_code != 0) {
1380 				c->Request.CDB[1] = 0x01;
1381 				c->Request.CDB[2] = page_code;
1382 			}
1383 			c->Request.CDBLen = 6;
1384 			c->Request.Type.Attribute = ATTR_SIMPLE;
1385 			c->Request.Type.Direction = XFER_READ; /* Read */
1386 			c->Request.Timeout = 0; /* Don't time out */
1387 			c->Request.CDB[4] = size  & 0xFF;
1388 		break;
1389 		case CISS_REPORT_LOG:
1390 			/* Talking to controller so It's a physical command
1391 				mode = 00 target = 0.
1392 				So we have nothing to write.
1393 			*/
1394 			c->Request.CDBLen = 12;
1395 			c->Request.Type.Attribute = ATTR_SIMPLE;
1396 			c->Request.Type.Direction = XFER_READ; /* Read */
1397 			c->Request.Timeout = 0; /* Don't time out */
1398 			c->Request.CDB[6] = (size >> 24) & 0xFF;  /* MSB */
1399 			c->Request.CDB[7] = (size >> 16) & 0xFF;
1400 			c->Request.CDB[8] = (size >> 8) & 0xFF;
1401 			c->Request.CDB[9] = size & 0xFF;
1402 		break;
1403 		case CCISS_READ_CAPACITY:
1404 			c->Header.LUN.LogDev.VolId=
1405 				hba[ctlr]->drv[log_unit].LunID;
1406 			c->Header.LUN.LogDev.Mode = 1;
1407 			c->Request.CDBLen = 10;
1408 			c->Request.Type.Attribute = ATTR_SIMPLE;
1409 			c->Request.Type.Direction = XFER_READ; /* Read */
1410 			c->Request.Timeout = 0; /* Don't time out */
1411 		break;
1412 		default:
1413 			printk(KERN_WARNING
1414 				"cciss:  Unknown Command 0x%x sent attempted\n",				cmd);
1415 			cmd_free(h, c, 1);
1416 			return IO_ERROR;
1417 		}
1418 	} else if (cmdtype == TYPE_MSG) {
1419 		switch (cmd) {
1420 		case 3: /* No-Op message */
1421 			c->Request.CDBLen = 1;
1422 			c->Request.Type.Attribute = ATTR_SIMPLE;
1423 			c->Request.Type.Direction = XFER_WRITE;
1424 			c->Request.Timeout = 0;
1425 			c->Request.CDB[0] = cmd;
1426 			break;
1427 		default:
1428 			printk(KERN_WARNING
1429 				"cciss%d: unknown message type %d\n",
1430 					ctlr, cmd);
1431 			cmd_free(h, c, 1);
1432 			return IO_ERROR;
1433 		}
1434 	} else {
1435 		printk(KERN_WARNING
1436 			"cciss%d: unknown command type %d\n", ctlr, cmdtype);
1437 		cmd_free(h, c, 1);
1438 		return IO_ERROR;
1439 	}
1440 
1441 	/* Fill in the scatter gather information */
1442 	if (size > 0) {
1443 		buff_dma_handle.val = (__u64) pci_map_single( h->pdev,
1444 			buff, size, PCI_DMA_BIDIRECTIONAL);
1445 		c->SG[0].Addr.lower = buff_dma_handle.val32.lower;
1446 		c->SG[0].Addr.upper = buff_dma_handle.val32.upper;
1447 		c->SG[0].Len = size;
1448 		c->SG[0].Ext = 0;  /* we are not chaining */
1449 	}
1450 
1451 resend_cmd2:
1452 	c->waiting = &wait;
1453 	/* Put the request on the tail of the queue and send it */
1454 	spin_lock_irqsave(&io_request_lock, flags);
1455 	addQ(&h->reqQ, c);
1456 	h->Qdepth++;
1457 	start_io(h);
1458 	spin_unlock_irqrestore(&io_request_lock, flags);
1459 
1460 	wait_for_completion(&wait);
1461 
1462 
1463 	if (c->err_info->CommandStatus != 0) {
1464 		/* an error has occurred */
1465 		switch (c->err_info->CommandStatus) {
1466 			case CMD_TARGET_STATUS:
1467 				printk(KERN_WARNING "cciss: cmd %p has "
1468 					" completed with errors\n", c);
1469 				if (c->err_info->ScsiStatus) {
1470 					printk(KERN_WARNING "cciss: cmd %p "
1471 					"has SCSI Status = %x\n", c,
1472 						c->err_info->ScsiStatus);
1473 				}
1474 			break;
1475 			case CMD_DATA_UNDERRUN:
1476 			case CMD_DATA_OVERRUN:
1477 			/* expected for inquire and report lun commands */
1478 			break;
1479 			case CMD_INVALID:
1480 				printk(KERN_WARNING "cciss: cmd %p is "
1481 					"reported invalid\n", c);
1482 				return_status = IO_ERROR;
1483 			break;
1484 			case CMD_PROTOCOL_ERR:
1485 				printk(KERN_WARNING "cciss: cmd %p has "
1486 					"protocol error \n", c);
1487 				return_status = IO_ERROR;
1488 			break;
1489 			case CMD_HARDWARE_ERR:
1490 				printk(KERN_WARNING "cciss: cmd %p had "
1491 					" hardware error\n", c);
1492 				return_status = IO_ERROR;
1493 				break;
1494 			case CMD_CONNECTION_LOST:
1495 				printk(KERN_WARNING "cciss: cmd %p had "
1496 					"connection lost\n", c);
1497 				return_status = IO_ERROR;
1498 			break;
1499 			case CMD_ABORTED:
1500 				printk(KERN_WARNING "cciss: cmd %p was "
1501 					"aborted\n", c);
1502 				return_status = IO_ERROR;
1503 			break;
1504 			case CMD_ABORT_FAILED:
1505 				printk(KERN_WARNING "cciss: cmd %p reports "
1506 					"abort failed\n", c);
1507 				return_status = IO_ERROR;
1508 			break;
1509 			case CMD_UNSOLICITED_ABORT:
1510 				printk(KERN_WARNING "cciss: cmd %p aborted "
1511 					"do to an unsolicited abort\n", c);
1512 				if (c->retry_count < MAX_CMD_RETRIES)
1513 				{
1514 					printk(KERN_WARNING "retrying cmd\n");
1515 					c->retry_count++;
1516 					/* erase the old error */
1517 					/* information */
1518 					memset(c->err_info, 0,
1519 						sizeof(ErrorInfo_struct));
1520 					return_status = IO_OK;
1521 					INIT_COMPLETION(wait);
1522 					goto resend_cmd2;
1523 
1524 				}
1525 				return_status = IO_ERROR;
1526 			break;
1527 			default:
1528 				printk(KERN_WARNING "cciss: cmd %p returned "
1529 					"unknown status %x\n", c,
1530 						c->err_info->CommandStatus);
1531 				return_status = IO_ERROR;
1532 		}
1533 	}
1534 
1535 	/* unlock the buffers from DMA */
1536 	pci_unmap_single( h->pdev, (dma_addr_t) buff_dma_handle.val,
1537 			size, PCI_DMA_BIDIRECTIONAL);
1538 	cmd_free(h, c, 0);
1539 	return return_status;
1540 }
register_new_disk(int ctlr,int opened_vol,__u64 requested_lun)1541 static int register_new_disk(int ctlr, int opened_vol, __u64 requested_lun)
1542 {
1543 	struct gendisk *gdev = &(hba[ctlr]->gendisk);
1544 	ctlr_info_t  *h = hba[ctlr];
1545 	int start, max_p, i;
1546 	int num_luns;
1547 	int logvol;
1548 	int new_lun_found = 0;
1549 	int new_lun_index = 0;
1550 	int free_index_found = 0;
1551 	int free_index = 0;
1552 	ReportLunData_struct *ld_buff;
1553 	ReadCapdata_struct *size_buff;
1554 	InquiryData_struct *inq_buff;
1555 	int return_code;
1556 	int listlength = 0;
1557 	__u32 lunid = 0;
1558 	unsigned int block_size;
1559 	unsigned int total_size;
1560 	unsigned long flags;
1561 	int req_lunid = (int) (requested_lun & (__u64) 0xffffffff);
1562 
1563 	if (!capable(CAP_SYS_RAWIO))
1564 		return -EPERM;
1565 	/* if we have no space in our disk array left to add anything */
1566 	spin_lock_irqsave(&io_request_lock, flags);
1567 	if (h->num_luns >= CISS_MAX_LUN) {
1568 		spin_unlock_irqrestore(&io_request_lock, flags);
1569 		return -EINVAL;
1570 	}
1571 	if (h->busy_configuring) {
1572 		spin_unlock_irqrestore(&io_request_lock, flags);
1573 		return -EBUSY;
1574 	}
1575 	h->busy_configuring = 1;
1576 	spin_unlock_irqrestore(&io_request_lock, flags);
1577 
1578 	ld_buff = kmalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
1579 	if (ld_buff == NULL) {
1580 		printk(KERN_ERR "cciss: out of memory\n");
1581 		h->busy_configuring = 0;
1582 		return -ENOMEM;
1583 	}
1584 	memset(ld_buff, 0, sizeof(ReportLunData_struct));
1585 	size_buff = kmalloc(sizeof( ReadCapdata_struct), GFP_KERNEL);
1586 	if (size_buff == NULL) {
1587 		printk(KERN_ERR "cciss: out of memory\n");
1588 		kfree(ld_buff);
1589 		h->busy_configuring = 0;
1590 		return -ENOMEM;
1591 	}
1592 	inq_buff = kmalloc(sizeof( InquiryData_struct), GFP_KERNEL);
1593 	if (inq_buff == NULL) {
1594 		printk(KERN_ERR "cciss: out of memory\n");
1595 		kfree(ld_buff);
1596 		kfree(size_buff);
1597 		h->busy_configuring = 0;
1598 		return -ENOMEM;
1599 	}
1600 
1601 	return_code = sendcmd_withirq(CISS_REPORT_LOG, ctlr, ld_buff,
1602 			sizeof(ReportLunData_struct), 0, 0, 0, TYPE_CMD);
1603 
1604 	if (return_code == IO_OK) {
1605 		listlength = be32_to_cpu(*((__u32 *) &ld_buff->LUNListLength[0]));
1606 	} else {
1607 		/* reading number of logical volumes failed */
1608 		printk(KERN_WARNING "cciss: report logical volume"
1609 			" command failed\n");
1610 		listlength = 0;
1611 		h->busy_configuring = 0;
1612 		return -1;
1613 	}
1614 	num_luns = listlength / 8; /* 8 bytes pre entry */
1615 	if (num_luns > CISS_MAX_LUN)
1616 		num_luns = CISS_MAX_LUN;
1617 
1618 #ifdef CCISS_DEBUG
1619 	printk(KERN_DEBUG "Length = %x %x %x %x = %d\n", ld_buff->LUNListLength[0],
1620 		ld_buff->LUNListLength[1], ld_buff->LUNListLength[2],
1621 		ld_buff->LUNListLength[3],  num_luns);
1622 #endif
1623 	for(i=0; i<  num_luns; i++) {
1624 		int j;
1625 		int lunID_found = 0;
1626 
1627 		lunid = (0xff & (unsigned int)(ld_buff->LUN[i][3])) << 24;
1628 		lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][2])) << 16;
1629 		lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][1])) << 8;
1630 		lunid |= 0xff & (unsigned int)(ld_buff->LUN[i][0]);
1631 
1632 		/* check to see if this is a new lun */
1633 		for(j=0; j <= h->highest_lun; j++) {
1634 #ifdef CCISS_DEBUG
1635 			printk("Checking %d %x against %x\n", j,h->drv[j].LunID,
1636 						lunid);
1637 #endif /* CCISS_DEBUG */
1638 			if (h->drv[j].LunID == lunid) {
1639 				lunID_found = 1;
1640 				break;
1641 			}
1642 
1643 		}
1644 		if (lunID_found == 1)
1645 			continue;
1646 		else {	/* new lun found */
1647 
1648 #ifdef CCISS_DEBUG
1649 			printk("new lun found at %d\n", i);
1650 #endif /* CCISS_DEBUG */
1651 			if (req_lunid)  /* we are looking for a specific lun */
1652 			{
1653 				if (lunid != req_lunid)
1654 				{
1655 #ifdef CCISS_DEBUG
1656 					printk("new lun %x is not %x\n",
1657 							lunid, req_lunid);
1658 #endif /* CCISS_DEBUG */
1659 					continue;
1660 				}
1661 			}
1662 			new_lun_index = i;
1663 			new_lun_found = 1;
1664 			break;
1665 		}
1666 	}
1667 	if (!new_lun_found) {
1668 		printk(KERN_DEBUG "cciss:  New Logical Volume not found\n");
1669 		h->busy_configuring = 0;
1670 		return -1;
1671 	}
1672 	/* Now find the free index 	*/
1673 	for(i=0; i <CISS_MAX_LUN; i++) {
1674 #ifdef CCISS_DEBUG
1675 		printk("Checking Index %d\n", i);
1676 #endif /* CCISS_DEBUG */
1677 		if (hba[ctlr]->drv[i].LunID == 0) {
1678 #ifdef CCISS_DEBUG
1679 			printk("free index found at %d\n", i);
1680 #endif /* CCISS_DEBUG */
1681 			free_index_found = 1;
1682 			free_index = i;
1683 			break;
1684 		}
1685 	}
1686 	if (!free_index_found) {
1687 		printk(KERN_WARNING "cciss: unable to find free slot for disk\n");
1688 		h->busy_configuring = 0;
1689 		return -1;
1690 	}
1691 
1692 	logvol = free_index;
1693 	hba[ctlr]->drv[logvol].LunID = lunid;
1694 		/* there could be gaps in lun numbers, track hightest */
1695 	if (hba[ctlr]->highest_lun < logvol)
1696 		hba[ctlr]->highest_lun = logvol;
1697 
1698 	memset(size_buff, 0, sizeof(ReadCapdata_struct));
1699 	return_code = sendcmd_withirq(CCISS_READ_CAPACITY, ctlr,
1700 			size_buff, sizeof(ReadCapdata_struct), 1,
1701 			logvol, 0, TYPE_CMD);
1702 	if (return_code == IO_OK) {
1703 		total_size = (0xff &
1704 			(unsigned int) size_buff->total_size[0]) << 24;
1705 		total_size |= (0xff &
1706 			(unsigned int) size_buff->total_size[1]) << 16;
1707 		total_size |= (0xff &
1708 			(unsigned int) size_buff->total_size[2]) << 8;
1709 		total_size |= (0xff &
1710 			(unsigned int) size_buff->total_size[3]);
1711 		total_size++; /* command returns highest block address */
1712 
1713 		block_size = (0xff &
1714 			(unsigned int) size_buff->block_size[0]) << 24;
1715 		block_size |= (0xff &
1716 			(unsigned int) size_buff->block_size[1]) << 16;
1717 		block_size |= (0xff &
1718 			(unsigned int) size_buff->block_size[2]) << 8;
1719 		block_size |= (0xff &
1720 			(unsigned int) size_buff->block_size[3]);
1721 	} else {
1722 		/* read capacity command failed */
1723 		printk(KERN_WARNING "cciss: read capacity failed\n");
1724 		total_size = 0;
1725 		block_size = BLOCK_SIZE;
1726 	}
1727 	printk(KERN_INFO "      blocks= %d block_size= %d\n",
1728 					total_size, block_size);
1729 	/* Execute the command to read the disk geometry */
1730 	memset(inq_buff, 0, sizeof(InquiryData_struct));
1731 	return_code = sendcmd_withirq(CISS_INQUIRY, ctlr, inq_buff,
1732 		sizeof(InquiryData_struct), 1, logvol ,0xC1, TYPE_CMD);
1733 	if (return_code == IO_OK) {
1734 		if (inq_buff->data_byte[8] == 0xFF) {
1735 			printk(KERN_WARNING
1736 			"cciss: reading geometry failed, "
1737 			"volume does not support reading geometry\n");
1738 
1739 			hba[ctlr]->drv[logvol].block_size = block_size;
1740 			hba[ctlr]->drv[logvol].nr_blocks = total_size;
1741 			hba[ctlr]->drv[logvol].heads = 255;
1742 			hba[ctlr]->drv[logvol].sectors = 32; /* secs/trk */
1743 			hba[ctlr]->drv[logvol].cylinders = total_size / 255 /32;
1744 			hba[ctlr]->drv[logvol].raid_level = RAID_UNKNOWN;
1745 		} else {
1746 			hba[ctlr]->drv[logvol].block_size = block_size;
1747 			hba[ctlr]->drv[logvol].nr_blocks = total_size;
1748 			hba[ctlr]->drv[logvol].heads = inq_buff->data_byte[6];
1749 			hba[ctlr]->drv[logvol].sectors = inq_buff->data_byte[7];
1750 			hba[ctlr]->drv[logvol].cylinders =
1751 				(inq_buff->data_byte[4] & 0xff) << 8;
1752 			hba[ctlr]->drv[logvol].cylinders +=
1753 				inq_buff->data_byte[5];
1754 			hba[ctlr]->drv[logvol].raid_level =
1755 				inq_buff->data_byte[8];
1756 		}
1757 	} else {
1758 		/* Get geometry failed */
1759 		printk(KERN_WARNING "cciss: reading geometry failed, "
1760 			"continuing with default geometry\n");
1761 
1762 		hba[ctlr]->drv[logvol].block_size = block_size;
1763 		hba[ctlr]->drv[logvol].nr_blocks = total_size;
1764 		hba[ctlr]->drv[logvol].heads = 255;
1765 		hba[ctlr]->drv[logvol].sectors = 32; /* Sectors per track */
1766 		hba[ctlr]->drv[logvol].cylinders = total_size / 255 / 32;
1767 	}
1768 	if (hba[ctlr]->drv[logvol].raid_level > 5)
1769 		hba[ctlr]->drv[logvol].raid_level = RAID_UNKNOWN;
1770 	printk(KERN_INFO "      heads= %d, sectors= %d, cylinders= %d RAID %s\n\n",
1771 		hba[ctlr]->drv[logvol].heads,
1772 		hba[ctlr]->drv[logvol].sectors,
1773 		hba[ctlr]->drv[logvol].cylinders,
1774 		raid_label[hba[ctlr]->drv[logvol].raid_level]);
1775 
1776 	/* special case for c?d0, which may be opened even when
1777 	   it does not "exist".  In that case, don't mess with usage count.
1778 	   Also, /dev/c1d1 could be used to re-add c0d0 so we can't just
1779 	   check whether logvol == 0, must check logvol != opened_vol */
1780 	if (logvol != opened_vol)
1781 		hba[ctlr]->drv[logvol].usage_count = 0;
1782 
1783 	max_p = gdev->max_p;
1784 	start = logvol<< gdev->minor_shift;
1785 	hba[ctlr]->hd[start].nr_sects = total_size;
1786 	hba[ctlr]->sizes[start] = total_size;
1787 
1788 	for(i=max_p-1; i>=0; i--) {
1789 		int minor = start+i;
1790 		invalidate_device(MKDEV(hba[ctlr]->major, minor), 1);
1791 		gdev->part[minor].start_sect = 0;
1792 		gdev->part[minor].nr_sects = 0;
1793 
1794 		/* reset the blocksize so we can read the partition table */
1795 		blksize_size[hba[ctlr]->major][minor] = block_size;
1796 		hba[ctlr]->hardsizes[minor] = block_size;
1797 	}
1798 
1799 	++hba[ctlr]->num_luns;
1800 	gdev->nr_real = hba[ctlr]->highest_lun + 1;
1801 	/* setup partitions per disk */
1802 	grok_partitions(gdev, logvol, MAX_PART,
1803 			hba[ctlr]->drv[logvol].nr_blocks);
1804 	kfree(ld_buff);
1805 	kfree(size_buff);
1806 	kfree(inq_buff);
1807 	h->busy_configuring = 0;
1808 	return logvol;
1809 }
1810 
cciss_rescan_disk(int ctlr,int logvol)1811 static int cciss_rescan_disk(int ctlr, int logvol)
1812 {
1813 	struct gendisk *gdev = &(hba[ctlr]->gendisk);
1814 	int start, max_p, i;
1815 	ReadCapdata_struct *size_buff;
1816 	InquiryData_struct *inq_buff;
1817 	int return_code;
1818 	unsigned int block_size;
1819 	unsigned int total_size;
1820 
1821 	if (!capable(CAP_SYS_RAWIO))
1822 		return -EPERM;
1823 	if (hba[ctlr]->sizes[logvol << NWD_SHIFT] != 0) {
1824 		/* disk is possible on line, return just a warning */
1825 		return 1;
1826 	}
1827 	size_buff = kmalloc(sizeof( ReadCapdata_struct), GFP_KERNEL);
1828 	if (size_buff == NULL) {
1829 		printk(KERN_ERR "cciss: out of memory\n");
1830 		return -1;
1831 	}
1832 	inq_buff = kmalloc(sizeof( InquiryData_struct), GFP_KERNEL);
1833 	if (inq_buff == NULL) {
1834 		printk(KERN_ERR "cciss: out of memory\n");
1835 		kfree(size_buff);
1836 		return -1;
1837 	}
1838 	memset(size_buff, 0, sizeof(ReadCapdata_struct));
1839 	return_code = sendcmd_withirq(CCISS_READ_CAPACITY, ctlr, size_buff,
1840 				sizeof( ReadCapdata_struct), 1, logvol, 0,
1841 				TYPE_CMD);
1842 	if (return_code == IO_OK) {
1843 		total_size = (0xff &
1844 			(unsigned int)(size_buff->total_size[0])) << 24;
1845 		total_size |= (0xff &
1846 				(unsigned int)(size_buff->total_size[1])) << 16;
1847 		total_size |= (0xff &
1848 				(unsigned int)(size_buff->total_size[2])) << 8;
1849 		total_size |= (0xff & (unsigned int)
1850 				(size_buff->total_size[3]));
1851 		total_size++; /* command returns highest block address */
1852 
1853 		block_size = (0xff &
1854 				(unsigned int)(size_buff->block_size[0])) << 24;
1855 		block_size |= (0xff &
1856 				(unsigned int)(size_buff->block_size[1])) << 16;
1857 		block_size |= (0xff &
1858 				(unsigned int)(size_buff->block_size[2])) << 8;
1859 		block_size |= (0xff &
1860 				(unsigned int)(size_buff->block_size[3]));
1861 	} else { /* read capacity command failed */
1862 		printk(KERN_WARNING "cciss: read capacity failed\n");
1863 		total_size = block_size = 0;
1864 	}
1865 	printk(KERN_INFO "      blocks= %d block_size= %d\n",
1866 					total_size, block_size);
1867 	/* Execute the command to read the disk geometry */
1868 	memset(inq_buff, 0, sizeof(InquiryData_struct));
1869 	return_code = sendcmd_withirq(CISS_INQUIRY, ctlr, inq_buff,
1870 			sizeof(InquiryData_struct), 1, logvol ,0xC1, TYPE_CMD);
1871 	if (return_code == IO_OK) {
1872 		if (inq_buff->data_byte[8] == 0xFF) {
1873 			printk(KERN_WARNING "cciss: reading geometry failed, "
1874 				"volume does not support reading geometry\n");
1875 
1876 			hba[ctlr]->drv[logvol].nr_blocks = total_size;
1877 			hba[ctlr]->drv[logvol].heads = 255;
1878 			hba[ctlr]->drv[logvol].sectors = 32; /* Sectors/track */
1879 			hba[ctlr]->drv[logvol].cylinders = total_size / 255 /32;
1880 		} else {
1881 			hba[ctlr]->drv[logvol].nr_blocks = total_size;
1882 			hba[ctlr]->drv[logvol].heads = inq_buff->data_byte[6];
1883 			hba[ctlr]->drv[logvol].sectors = inq_buff->data_byte[7];
1884 			hba[ctlr]->drv[logvol].cylinders =
1885 				(inq_buff->data_byte[4] & 0xff) << 8;
1886 			hba[ctlr]->drv[logvol].cylinders +=
1887 				inq_buff->data_byte[5];
1888 		}
1889 	} else { /* Get geometry failed */
1890 		printk(KERN_WARNING "cciss: reading geometry failed, "
1891 				"continuing with default geometry\n");
1892 
1893 		hba[ctlr]->drv[logvol].nr_blocks = total_size;
1894 		hba[ctlr]->drv[logvol].heads = 255;
1895 		hba[ctlr]->drv[logvol].sectors = 32; /* Sectors / track */
1896 		hba[ctlr]->drv[logvol].cylinders = total_size / 255 /32;
1897 	}
1898 
1899 	printk(KERN_INFO "      heads= %d, sectors= %d, cylinders= %d \n\n",
1900 		hba[ctlr]->drv[logvol].heads,
1901 		hba[ctlr]->drv[logvol].sectors,
1902 		hba[ctlr]->drv[logvol].cylinders);
1903 	max_p = gdev->max_p;
1904 	start = logvol<< gdev->minor_shift;
1905 	hba[ctlr]->hd[start].nr_sects = hba[ctlr]->sizes[start]= total_size;
1906 
1907 	for (i=max_p-1; i>=0; i--) {
1908 		int minor = start+i;
1909 		invalidate_device(MKDEV(hba[ctlr]->major, minor), 1);
1910 		gdev->part[minor].start_sect = 0;
1911 		gdev->part[minor].nr_sects = 0;
1912 
1913 		/* reset the blocksize so we can read the partition table */
1914 		blksize_size[hba[ctlr]->major][minor] = block_size;
1915 		hba[ctlr]->hardsizes[minor] = block_size;
1916 	}
1917 
1918 	/* setup partitions per disk */
1919 	grok_partitions(gdev, logvol, MAX_PART,
1920 			hba[ctlr]->drv[logvol].nr_blocks );
1921 
1922 	kfree(size_buff);
1923 	kfree(inq_buff);
1924 	return 0;
1925 }
1926 /*
1927  *   Wait polling for a command to complete.
1928  *   The memory mapped FIFO is polled for the completion.
1929  *   Used only at init time, interrupts disabled.
1930  */
pollcomplete(int ctlr)1931 static unsigned long pollcomplete(int ctlr)
1932 {
1933 	unsigned long done;
1934 	int i;
1935 
1936 	/* Wait (up to 20 seconds) for a command to complete */
1937 
1938         for (i = 20 * HZ; i > 0; i--) {
1939 		done = hba[ctlr]->access.command_completed(hba[ctlr]);
1940 		if (done == FIFO_EMPTY) {
1941 			set_current_state(TASK_UNINTERRUPTIBLE);
1942 			schedule_timeout(1);
1943 		} else
1944 			return done;
1945 	}
1946 	/* Invalid address to tell caller we ran out of time */
1947 	return 1;
1948 }
1949 /*
1950  * Send a command to the controller, and wait for it to complete.
1951  * Only used at init time.
1952  */
sendcmd(__u8 cmd,int ctlr,void * buff,size_t size,unsigned int use_unit_num,unsigned int log_unit,__u8 page_code,unsigned char * scsi3addr)1953 static int sendcmd(
1954 	__u8	cmd,
1955 	int	ctlr,
1956 	void	*buff,
1957 	size_t	size,
1958 	unsigned int use_unit_num, /* 0: address the controller,
1959 				      1: address logical volume log_unit,
1960 				      2: periph device address is scsi3addr */
1961 	unsigned int log_unit,
1962 	__u8	page_code,
1963 	unsigned char *scsi3addr)
1964 {
1965 	CommandList_struct *c;
1966 	int i;
1967 	unsigned long complete;
1968 	ctlr_info_t *info_p= hba[ctlr];
1969 	u64bit buff_dma_handle;
1970 	int status = IO_OK;
1971 
1972 	c = cmd_alloc(info_p, 1);
1973 	if (c == NULL) {
1974 		printk(KERN_WARNING "cciss: unable to get memory");
1975 		return IO_ERROR;
1976 	}
1977 	/* Fill in Command Header */
1978 	c->Header.ReplyQueue = 0;  /* unused in simple mode */
1979 	if (buff != NULL) { 	/* buffer to fill */
1980 		c->Header.SGList = 1;
1981 		c->Header.SGTotal= 1;
1982 	} else	{	/* no buffers to fill  */
1983 		c->Header.SGList = 0;
1984                 c->Header.SGTotal= 0;
1985 	}
1986 	c->Header.Tag.lower = c->busaddr;  /* use the kernel address */
1987 					   /* the cmd block for tag */
1988 	/* Fill in Request block */
1989 	switch (cmd) {
1990 		case  CISS_INQUIRY:
1991 			/* If the logical unit number is 0 then, this is going
1992 				to controller so It's a physical command
1993 				mode = 0 target = 0.
1994 				So we have nothing to write.
1995 				otherwise, if use_unit_num == 1,
1996 				mode = 1(volume set addressing) target = LUNID
1997 				otherwise, if use_unit_num == 2,
1998 				mode = 0(periph dev addr) target = scsi3addr
1999 			*/
2000 			if (use_unit_num == 1) {
2001 				c->Header.LUN.LogDev.VolId=
2002                                 	hba[ctlr]->drv[log_unit].LunID;
2003                         	c->Header.LUN.LogDev.Mode = 1;
2004 			}
2005 			else if (use_unit_num == 2) {
2006 				memcpy(c->Header.LUN.LunAddrBytes,scsi3addr,8);
2007 				c->Header.LUN.LogDev.Mode = 0;
2008 							/* phys dev addr */
2009 			}
2010 
2011 			/* are we trying to read a vital product page */
2012 			if (page_code != 0) {
2013 				c->Request.CDB[1] = 0x01;
2014 				c->Request.CDB[2] = page_code;
2015 			}
2016 			c->Request.CDBLen = 6;
2017 			c->Request.Type.Type =  TYPE_CMD; /* It is a command. */
2018 			c->Request.Type.Attribute = ATTR_SIMPLE;
2019 			c->Request.Type.Direction = XFER_READ; /* Read */
2020 			c->Request.Timeout = 0; /* Don't time out */
2021 			c->Request.CDB[0] =  CISS_INQUIRY;
2022 			c->Request.CDB[4] = size  & 0xFF;
2023 		break;
2024 		case CISS_REPORT_LOG:
2025 		case CISS_REPORT_PHYS:
2026                         /* Talking to controller so It's a physical command
2027                                 mode = 00 target = 0.
2028                                 So we have nothing to write.
2029                         */
2030                         c->Request.CDBLen = 12;
2031                         c->Request.Type.Type =  TYPE_CMD; /* It is a command. */
2032                         c->Request.Type.Attribute = ATTR_SIMPLE;
2033                         c->Request.Type.Direction = XFER_READ; /* Read */
2034                         c->Request.Timeout = 0; /* Don't time out */
2035 			c->Request.CDB[0] = cmd;
2036                         c->Request.CDB[6] = (size >> 24) & 0xFF;  /* MSB */
2037                         c->Request.CDB[7] = (size >> 16) & 0xFF;
2038                         c->Request.CDB[8] = (size >> 8) & 0xFF;
2039                         c->Request.CDB[9] = size & 0xFF;
2040                 break;
2041 
2042 		case CCISS_READ_CAPACITY:
2043 			c->Header.LUN.LogDev.VolId=
2044 				hba[ctlr]->drv[log_unit].LunID;
2045 			c->Header.LUN.LogDev.Mode = 1;
2046 			c->Request.CDBLen = 10;
2047                         c->Request.Type.Type =  TYPE_CMD; /* It is a command. */
2048                         c->Request.Type.Attribute = ATTR_SIMPLE;
2049                         c->Request.Type.Direction = XFER_READ; /* Read */
2050                         c->Request.Timeout = 0; /* Don't time out */
2051                         c->Request.CDB[0] = CCISS_READ_CAPACITY;
2052 		break;
2053 		case CCISS_CACHE_FLUSH:
2054 			c->Request.CDBLen = 12;
2055 			c->Request.Type.Type =  TYPE_CMD; /* It is a command. */
2056 			c->Request.Type.Attribute = ATTR_SIMPLE;
2057 			c->Request.Type.Direction = XFER_WRITE; /* No data */
2058 			c->Request.Timeout = 0; /* Don't time out */
2059 			c->Request.CDB[0] = BMIC_WRITE;  /* BMIC Passthru */
2060 			c->Request.CDB[6] = BMIC_CACHE_FLUSH;
2061 		break;
2062 		default:
2063 			printk(KERN_WARNING
2064 				"cciss:  Unknown Command 0x%x sent attempted\n",
2065 				  cmd);
2066 			cmd_free(info_p, c, 1);
2067 			return IO_ERROR;
2068 	};
2069 	/* Fill in the scatter gather information */
2070 	if (size > 0) {
2071 		buff_dma_handle.val = (__u64) pci_map_single( info_p->pdev,
2072 			buff, size, PCI_DMA_BIDIRECTIONAL);
2073 		c->SG[0].Addr.lower = buff_dma_handle.val32.lower;
2074 		c->SG[0].Addr.upper = buff_dma_handle.val32.upper;
2075 		c->SG[0].Len = size;
2076 		c->SG[0].Ext = 0;  /* we are not chaining */
2077 	}
2078 resend_cmd1:
2079 	/*
2080          * Disable interrupt
2081          */
2082 #ifdef CCISS_DEBUG
2083 	printk(KERN_DEBUG "cciss: turning intr off\n");
2084 #endif /* CCISS_DEBUG */
2085         info_p->access.set_intr_mask(info_p, CCISS_INTR_OFF);
2086 
2087 	/* Make sure there is room in the command FIFO */
2088         /* Actually it should be completely empty at this time. */
2089         for (i = 200000; i > 0; i--) {
2090 		/* if fifo isn't full go */
2091                 if (!(info_p->access.fifo_full(info_p))) {
2092 
2093                         break;
2094                 }
2095                 udelay(10);
2096                 printk(KERN_WARNING "cciss cciss%d: SendCmd FIFO full,"
2097                         " waiting!\n", ctlr);
2098         }
2099         /*
2100          * Send the cmd
2101          */
2102         info_p->access.submit_command(info_p, c);
2103         complete = pollcomplete(ctlr);
2104 
2105 #ifdef CCISS_DEBUG
2106 	printk(KERN_DEBUG "cciss: command completed\n");
2107 #endif /* CCISS_DEBUG */
2108 
2109 	if (complete != 1) {
2110 		if ( (complete & CISS_ERROR_BIT)
2111 		     && (complete & ~CISS_ERROR_BIT) == c->busaddr) {
2112 			/* if data overrun or underun on Report command
2113 				ignore it
2114 			*/
2115 			if (((c->Request.CDB[0] == CISS_REPORT_LOG) ||
2116 			     (c->Request.CDB[0] == CISS_REPORT_PHYS) ||
2117 			     (c->Request.CDB[0] == CISS_INQUIRY)) &&
2118 				((c->err_info->CommandStatus ==
2119 					CMD_DATA_OVERRUN) ||
2120 				 (c->err_info->CommandStatus ==
2121 					CMD_DATA_UNDERRUN)
2122 			 	)) {
2123 				complete = c->busaddr;
2124 			} else {
2125 				if (c->err_info->CommandStatus ==
2126 						CMD_UNSOLICITED_ABORT) {
2127 					printk(KERN_WARNING "cciss: "
2128 						"cmd %p aborted do "
2129 					"to an unsolicited abort \n", c);
2130 					if (c->retry_count < MAX_CMD_RETRIES) {
2131 						printk(KERN_WARNING
2132 						   "retrying cmd\n");
2133 						c->retry_count++;
2134 						/* erase the old error */
2135 						/* information */
2136 						memset(c->err_info, 0,
2137 						   sizeof(ErrorInfo_struct));
2138 						goto resend_cmd1;
2139 					} else {
2140 						printk(KERN_WARNING
2141 						   "retried to many times\n");
2142 						status = IO_ERROR;
2143 						goto cleanup1;
2144 					}
2145 				}
2146 				printk(KERN_WARNING "cciss cciss%d: sendcmd"
2147 				" Error %x \n", ctlr,
2148 					c->err_info->CommandStatus);
2149 				printk(KERN_WARNING "cciss cciss%d: sendcmd"
2150 				" offensive info\n"
2151 				"  size %x\n   num %x   value %x\n", ctlr,
2152 				  c->err_info->MoreErrInfo.Invalid_Cmd.offense_size,
2153 				  c->err_info->MoreErrInfo.Invalid_Cmd.offense_num,
2154 				  c->err_info->MoreErrInfo.Invalid_Cmd.offense_value);
2155 				status = IO_ERROR;
2156 				goto cleanup1;
2157 			}
2158 		}
2159                 if (complete != c->busaddr) {
2160                         printk( KERN_WARNING "cciss cciss%d: SendCmd "
2161                       "Invalid command list address returned! (%lx)\n",
2162                                 ctlr, complete);
2163                         status = IO_ERROR;
2164 			goto cleanup1;
2165                 }
2166         } else {
2167                 printk( KERN_WARNING
2168                         "cciss cciss%d: SendCmd Timeout out, "
2169                         "No command list address returned!\n",
2170                         ctlr);
2171                 status = IO_ERROR;
2172         }
2173 
2174 cleanup1:
2175 	/* unlock the data buffer from DMA */
2176 	pci_unmap_single(info_p->pdev, (dma_addr_t) buff_dma_handle.val,
2177                                 size, PCI_DMA_BIDIRECTIONAL);
2178 	cmd_free(info_p, c, 1);
2179         return status;
2180 }
2181 /*
2182  * Map (physical) PCI mem into (virtual) kernel space
2183  */
remap_pci_mem(ulong base,ulong size)2184 static ulong remap_pci_mem(ulong base, ulong size)
2185 {
2186         ulong page_base        = ((ulong) base) & PAGE_MASK;
2187         ulong page_offs        = ((ulong) base) - page_base;
2188         ulong page_remapped    = (ulong) ioremap(page_base, page_offs+size);
2189 
2190         return (ulong) (page_remapped ? (page_remapped + page_offs) : 0UL);
2191 }
2192 
2193 /*
2194  * Takes jobs of the Q and sends them to the hardware, then puts it on
2195  * the Q to wait for completion.
2196  */
start_io(ctlr_info_t * h)2197 static void start_io( ctlr_info_t *h)
2198 {
2199 	CommandList_struct *c;
2200 
2201 	while(( c = h->reqQ) != NULL ) {
2202 		/* can't do anything if fifo is full */
2203 		if ((h->access.fifo_full(h))) {
2204 			printk(KERN_WARNING "cciss: fifo full \n");
2205 			return;
2206 		}
2207 		/* Get the frist entry from the Request Q */
2208 		removeQ(&(h->reqQ), c);
2209 		h->Qdepth--;
2210 
2211 		/* Tell the controller execute command */
2212 		h->access.submit_command(h, c);
2213 
2214 		/* Put job onto the completed Q */
2215 		addQ (&(h->cmpQ), c);
2216 	}
2217 }
2218 
complete_buffers(struct buffer_head * bh,int status)2219 static inline void complete_buffers( struct buffer_head *bh, int status)
2220 {
2221 	struct buffer_head *xbh;
2222 
2223 	while(bh) {
2224 		xbh = bh->b_reqnext;
2225 		bh->b_reqnext = NULL;
2226 		blk_finished_io(bh->b_size >> 9);
2227 		bh->b_end_io(bh, status);
2228 		bh = xbh;
2229 	}
2230 }
2231 /* This code assumes io_request_lock is already held */
2232 /* Zeros out the error record and then resends the command back */
2233 /* to the controller */
resend_cciss_cmd(ctlr_info_t * h,CommandList_struct * c)2234 static inline void resend_cciss_cmd( ctlr_info_t *h, CommandList_struct *c)
2235 {
2236 	/* erase the old error information */
2237 	memset(c->err_info, 0, sizeof(ErrorInfo_struct));
2238 
2239 	/* add it to software queue and then send it to the controller */
2240 	addQ(&(h->reqQ),c);
2241 	h->Qdepth++;
2242 	if (h->Qdepth > h->maxQsinceinit)
2243 		h->maxQsinceinit = h->Qdepth;
2244 
2245 	start_io(h);
2246 }
2247 /* checks the status of the job and calls complete buffers to mark all
2248  * buffers for the completed job.
2249  */
complete_command(ctlr_info_t * h,CommandList_struct * cmd,int timeout)2250 static inline void complete_command( ctlr_info_t *h, CommandList_struct *cmd,
2251 		int timeout)
2252 {
2253 	int status = 1;
2254 	int retry_cmd = 0;
2255 	int i, ddir;
2256 	u64bit temp64;
2257 
2258 	if (timeout)
2259 		status = 0;
2260 
2261 	if (cmd->err_info->CommandStatus != 0) {
2262 		/* an error has occurred */
2263 		switch (cmd->err_info->CommandStatus) {
2264 			unsigned char sense_key;
2265 			case CMD_TARGET_STATUS:
2266 				status = 0;
2267 
2268 				if (cmd->err_info->ScsiStatus == 0x02) {
2269 					printk(KERN_WARNING "cciss: cmd %p "
2270 						"has CHECK CONDITION,"
2271 						" sense key = 0x%x\n", cmd,
2272 						cmd->err_info->SenseInfo[2]);
2273 					/* check the sense key */
2274 					sense_key = 0xf &
2275 						cmd->err_info->SenseInfo[2];
2276 					/* recovered error */
2277 					if ( sense_key == 0x1)
2278 						status = 1;
2279 				} else {
2280 					printk(KERN_WARNING "cciss: cmd %p "
2281 						"has SCSI Status 0x%x\n",
2282 						cmd, cmd->err_info->ScsiStatus);
2283 				}
2284 			break;
2285 			case CMD_DATA_UNDERRUN:
2286 				printk(KERN_WARNING "cciss: cmd %p has"
2287 					" completed with data underrun "
2288 					"reported\n", cmd);
2289 			break;
2290 			case CMD_DATA_OVERRUN:
2291 				printk(KERN_WARNING "cciss: cmd %p has"
2292 					" completed with data overrun "
2293 					"reported\n", cmd);
2294 			break;
2295 			case CMD_INVALID:
2296 				printk(KERN_WARNING "cciss: cmd %p is "
2297 					"reported invalid\n", cmd);
2298 				status = 0;
2299 			break;
2300 			case CMD_PROTOCOL_ERR:
2301                                 printk(KERN_WARNING "cciss: cmd %p has "
2302 					"protocol error \n", cmd);
2303                                 status = 0;
2304                         break;
2305 			case CMD_HARDWARE_ERR:
2306                                 printk(KERN_WARNING "cciss: cmd %p had "
2307                                         " hardware error\n", cmd);
2308                                 status = 0;
2309                         break;
2310 			case CMD_CONNECTION_LOST:
2311 				printk(KERN_WARNING "cciss: cmd %p had "
2312 					"connection lost\n", cmd);
2313 				status=0;
2314 			break;
2315 			case CMD_ABORTED:
2316 				printk(KERN_WARNING "cciss: cmd %p was "
2317 					"aborted\n", cmd);
2318 				status=0;
2319 			break;
2320 			case CMD_ABORT_FAILED:
2321 				printk(KERN_WARNING "cciss: cmd %p reports "
2322 					"abort failed\n", cmd);
2323 				status=0;
2324 			break;
2325 			case CMD_UNSOLICITED_ABORT:
2326 				printk(KERN_WARNING "cciss: cmd %p aborted do "
2327 					"to an unsolicited abort \n",
2328 				       	cmd);
2329 				if (cmd->retry_count < MAX_CMD_RETRIES) {
2330 					retry_cmd=1;
2331 					printk(KERN_WARNING
2332 						"retrying cmd\n");
2333 					cmd->retry_count++;
2334 				} else {
2335 					printk(KERN_WARNING
2336 					"retried to many times\n");
2337 				}
2338 				status=0;
2339 			break;
2340 			case CMD_TIMEOUT:
2341 				printk(KERN_WARNING "cciss: cmd %p timedout\n",
2342 					cmd);
2343 				status=0;
2344 			break;
2345 			default:
2346 				printk(KERN_WARNING "cciss: cmd %p returned "
2347 					"unknown status %x\n", cmd,
2348 						cmd->err_info->CommandStatus);
2349 				status=0;
2350 		}
2351 	}
2352 	/* We need to return this command */
2353 	if (retry_cmd) {
2354 		resend_cciss_cmd(h,cmd);
2355 		return;
2356 	}
2357 	/* command did not need to be retried */
2358 	/* unmap the DMA mapping for all the scatter gather elements */
2359 	if (cmd->Request.Type.Direction == XFER_READ)
2360 		ddir = PCI_DMA_FROMDEVICE;
2361 	else
2362 		ddir = PCI_DMA_TODEVICE;
2363 	for(i=0; i<cmd->Header.SGList; i++) {
2364 		temp64.val32.lower = cmd->SG[i].Addr.lower;
2365 		temp64.val32.upper = cmd->SG[i].Addr.upper;
2366 		pci_unmap_page(hba[cmd->ctlr]->pdev,
2367 			temp64.val, cmd->SG[i].Len, ddir);
2368 	}
2369 	complete_buffers(cmd->rq->bh, status);
2370 #ifdef CCISS_DEBUG
2371 	printk("Done with %p\n", cmd->rq);
2372 #endif /* CCISS_DEBUG */
2373 	end_that_request_last(cmd->rq);
2374 	cmd_free(h,cmd,1);
2375 }
2376 
2377 
cpq_new_segment(request_queue_t * q,struct request * rq,int max_segments)2378 static inline int cpq_new_segment(request_queue_t *q, struct request *rq,
2379                                   int max_segments)
2380 {
2381         if (rq->nr_segments < MAXSGENTRIES) {
2382                 rq->nr_segments++;
2383                 return 1;
2384         }
2385         return 0;
2386 }
2387 
cpq_back_merge_fn(request_queue_t * q,struct request * rq,struct buffer_head * bh,int max_segments)2388 static int cpq_back_merge_fn(request_queue_t *q, struct request *rq,
2389                              struct buffer_head *bh, int max_segments)
2390 {
2391 	if (blk_seg_merge_ok(rq->bhtail, bh))
2392                 return 1;
2393         return cpq_new_segment(q, rq, max_segments);
2394 }
2395 
cpq_front_merge_fn(request_queue_t * q,struct request * rq,struct buffer_head * bh,int max_segments)2396 static int cpq_front_merge_fn(request_queue_t *q, struct request *rq,
2397                              struct buffer_head *bh, int max_segments)
2398 {
2399 	if (blk_seg_merge_ok(bh, rq->bh))
2400                 return 1;
2401         return cpq_new_segment(q, rq, max_segments);
2402 }
2403 
cpq_merge_requests_fn(request_queue_t * q,struct request * rq,struct request * nxt,int max_segments)2404 static int cpq_merge_requests_fn(request_queue_t *q, struct request *rq,
2405                                  struct request *nxt, int max_segments)
2406 {
2407         int total_segments = rq->nr_segments + nxt->nr_segments;
2408 
2409 	if (blk_seg_merge_ok(rq->bhtail, nxt->bh))
2410                 total_segments--;
2411 
2412         if (total_segments > MAXSGENTRIES)
2413                 return 0;
2414 
2415         rq->nr_segments = total_segments;
2416         return 1;
2417 }
2418 
2419 /*
2420  * Get a request and submit it to the controller.
2421  * Currently we do one request at a time.  Ideally we would like to send
2422  * everything to the controller on the first call, but there is a danger
2423  * of holding the io_request_lock for to long.
2424  */
do_cciss_request(request_queue_t * q)2425 static void do_cciss_request(request_queue_t *q)
2426 {
2427 	ctlr_info_t *h= q->queuedata;
2428 	CommandList_struct *c;
2429 	int log_unit, start_blk, seg;
2430 	unsigned long long lastdataend;
2431 	struct buffer_head *bh;
2432 	struct list_head *queue_head = &q->queue_head;
2433 	struct request *creq;
2434 	u64bit temp64;
2435 	struct scatterlist tmp_sg[MAXSGENTRIES];
2436 	int i, ddir;
2437 
2438 	if (q->plugged)
2439 		goto startio;
2440 
2441 next:
2442 	if (list_empty(queue_head))
2443 		goto startio;
2444 
2445 	creq =	blkdev_entry_next_request(queue_head);
2446 	if (creq->nr_segments > MAXSGENTRIES)
2447                 BUG();
2448 
2449 	if( h->ctlr != map_major_to_ctlr[MAJOR(creq->rq_dev)] ) {
2450                 printk(KERN_WARNING "doreq cmd for %d, %x at %p\n",
2451                                 h->ctlr, creq->rq_dev, creq);
2452                 blkdev_dequeue_request(creq);
2453                 complete_buffers(creq->bh, 0);
2454 		end_that_request_last(creq);
2455 		goto startio;
2456         }
2457 
2458 	/* make sure controller is alive. */
2459 	if (!CTLR_IS_ALIVE(h)) {
2460                 printk(KERN_WARNING "cciss%d: I/O quit ", h->ctlr);
2461                 blkdev_dequeue_request(creq);
2462                 complete_buffers(creq->bh, 0);
2463 		end_that_request_last(creq);
2464 		return;
2465 	}
2466 
2467 	if (( c = cmd_alloc(h, 1)) == NULL)
2468 		goto startio;
2469 
2470 	blkdev_dequeue_request(creq);
2471 
2472 	spin_unlock_irq(&io_request_lock);
2473 
2474 	c->cmd_type = CMD_RWREQ;
2475 	c->rq = creq;
2476 	bh = creq->bh;
2477 
2478 	/* fill in the request */
2479 	log_unit = MINOR(creq->rq_dev) >> NWD_SHIFT;
2480 	c->Header.ReplyQueue = 0;  /* unused in simple mode */
2481 	c->Header.Tag.lower = c->busaddr;  /* use the physical address */
2482 					/* the cmd block for tag */
2483 	c->Header.LUN.LogDev.VolId= hba[h->ctlr]->drv[log_unit].LunID;
2484 	c->Header.LUN.LogDev.Mode = 1;
2485 	c->Request.CDBLen = 10; /* 12 byte commands not in FW yet. */
2486 	c->Request.Type.Type =  TYPE_CMD; /* It is a command.  */
2487 	c->Request.Type.Attribute = ATTR_SIMPLE;
2488 	c->Request.Type.Direction =
2489 		(creq->cmd == READ) ? XFER_READ: XFER_WRITE;
2490 	c->Request.Timeout = 0; /* Don't time out */
2491 	c->Request.CDB[0] = (creq->cmd == READ) ? CCISS_READ : CCISS_WRITE;
2492 	start_blk = hba[h->ctlr]->hd[MINOR(creq->rq_dev)].start_sect + creq->sector;
2493 #ifdef CCISS_DEBUG
2494 	if (bh == NULL)
2495 		panic("cciss: bh== NULL?");
2496 	printk(KERN_DEBUG "cciss: sector =%d nr_sectors=%d\n",(int) creq->sector,
2497 		(int) creq->nr_sectors);
2498 #endif /* CCISS_DEBUG */
2499 	seg = 0;
2500 	lastdataend = ~0ULL;
2501 	while(bh) {
2502 		if (bh_phys(bh) == lastdataend)
2503 		{  /* tack it on to the last segment */
2504 			tmp_sg[seg-1].length +=bh->b_size;
2505 			lastdataend += bh->b_size;
2506 		} else {
2507 			if (seg == MAXSGENTRIES)
2508 				BUG();
2509 			tmp_sg[seg].page = bh->b_page;
2510 			tmp_sg[seg].length = bh->b_size;
2511 			tmp_sg[seg].offset = bh_offset(bh);
2512 			lastdataend = bh_phys(bh) + bh->b_size;
2513 			seg++;
2514 		}
2515 		bh = bh->b_reqnext;
2516 	}
2517 
2518 	/* get the DMA records for the setup */
2519 	if (c->Request.Type.Direction == XFER_READ)
2520 		ddir = PCI_DMA_FROMDEVICE;
2521 	else
2522 		ddir = PCI_DMA_TODEVICE;
2523 	for (i=0; i<seg; i++) {
2524 		c->SG[i].Len = tmp_sg[i].length;
2525 		temp64.val = pci_map_page(h->pdev, tmp_sg[i].page,
2526 			    tmp_sg[i].offset, tmp_sg[i].length, ddir);
2527 		c->SG[i].Addr.lower = temp64.val32.lower;
2528                 c->SG[i].Addr.upper = temp64.val32.upper;
2529                 c->SG[i].Ext = 0;  /* we are not chaining */
2530 	}
2531 	/* track how many SG entries we are using */
2532 	if (seg > h->maxSG)
2533 		h->maxSG = seg;
2534 
2535 #ifdef CCISS_DEBUG
2536 	printk(KERN_DEBUG "cciss: Submitting %d sectors in %d segments\n", sect, seg);
2537 #endif /* CCISS_DEBUG */
2538 
2539 	c->Header.SGList = c->Header.SGTotal = seg;
2540 	c->Request.CDB[1]= 0;
2541 	c->Request.CDB[2]= (start_blk >> 24) & 0xff;	/* MSB */
2542 	c->Request.CDB[3]= (start_blk >> 16) & 0xff;
2543 	c->Request.CDB[4]= (start_blk >>  8) & 0xff;
2544 	c->Request.CDB[5]= start_blk & 0xff;
2545 	c->Request.CDB[6]= 0; /* (sect >> 24) & 0xff; MSB */
2546 	c->Request.CDB[7]= (creq->nr_sectors >>  8) & 0xff;
2547 	c->Request.CDB[8]= creq->nr_sectors & 0xff;
2548 	c->Request.CDB[9] = c->Request.CDB[11] = c->Request.CDB[12] = 0;
2549 
2550 	spin_lock_irq(&io_request_lock);
2551 
2552 	addQ(&(h->reqQ),c);
2553 	h->Qdepth++;
2554 	if (h->Qdepth > h->maxQsinceinit)
2555 		h->maxQsinceinit = h->Qdepth;
2556 
2557 	goto next;
2558 
2559 startio:
2560 	start_io(h);
2561 }
2562 
do_cciss_intr(int irq,void * dev_id,struct pt_regs * regs)2563 static void do_cciss_intr(int irq, void *dev_id, struct pt_regs *regs)
2564 {
2565 	ctlr_info_t *h = dev_id;
2566 	CommandList_struct *c;
2567 	unsigned long flags;
2568 	__u32 a, a1;
2569 
2570 
2571 	/* Is this interrupt for us? */
2572 	if ((h->access.intr_pending(h) == 0) || (h->interrupts_enabled == 0))
2573 		return;
2574 
2575 	/*
2576 	 * If there are completed commands in the completion queue,
2577 	 * we had better do something about it.
2578 	 */
2579 	spin_lock_irqsave(&io_request_lock, flags);
2580 	while( h->access.intr_pending(h)) {
2581 		while((a = h->access.command_completed(h)) != FIFO_EMPTY) {
2582 			a1 = a;
2583 			a &= ~3;
2584 			if ((c = h->cmpQ) == NULL) {
2585 				printk(KERN_WARNING "cciss: Completion of %08lx ignored\n", (unsigned long)a1);
2586 				continue;
2587 			}
2588 			while(c->busaddr != a) {
2589 				c = c->next;
2590 				if (c == h->cmpQ)
2591 					break;
2592 			}
2593 			/*
2594 			 * If we've found the command, take it off the
2595 			 * completion Q and free it
2596 			 */
2597 			 if (c->busaddr == a) {
2598 				removeQ(&h->cmpQ, c);
2599 				if (c->cmd_type == CMD_RWREQ) {
2600 					complete_command(h, c, 0);
2601 				} else if (c->cmd_type == CMD_IOCTL_PEND) {
2602 					complete(c->waiting);
2603 				}
2604 #				ifdef CONFIG_CISS_SCSI_TAPE
2605 				else if (c->cmd_type == CMD_SCSI) {
2606 					complete_scsi_command(c, 0, a1);
2607 				}
2608 #				endif
2609 				continue;
2610 			}
2611 		}
2612 	}
2613 	/*
2614 	 * See if we can queue up some more IO
2615 	 */
2616 	do_cciss_request(BLK_DEFAULT_QUEUE(h->major));
2617 	spin_unlock_irqrestore(&io_request_lock, flags);
2618 }
2619 /*
2620  *  We cannot read the structure directly, for portablity we must use
2621  *   the io functions.
2622  *   This is for debug only.
2623  */
2624 #ifdef CCISS_DEBUG
print_cfg_table(CfgTable_struct * tb)2625 static void print_cfg_table( CfgTable_struct *tb)
2626 {
2627 	int i;
2628 	char temp_name[17];
2629 
2630 	printk("Controller Configuration information\n");
2631 	printk("------------------------------------\n");
2632 	for(i=0;i<4;i++)
2633 		temp_name[i] = readb(&(tb->Signature[i]));
2634 	temp_name[4]='\0';
2635 	printk("   Signature = %s\n", temp_name);
2636 	printk("   Spec Number = %d\n", readl(&(tb->SpecValence)));
2637 	printk("   Transport methods supported = 0x%x\n",
2638 				readl(&(tb-> TransportSupport)));
2639 	printk("   Transport methods active = 0x%x\n",
2640 				readl(&(tb->TransportActive)));
2641 	printk("   Requested transport Method = 0x%x\n",
2642 			readl(&(tb->HostWrite.TransportRequest)));
2643 	printk("   Coalese Interrupt Delay = 0x%x\n",
2644 			readl(&(tb->HostWrite.CoalIntDelay)));
2645 	printk("   Coalese Interrupt Count = 0x%x\n",
2646 			readl(&(tb->HostWrite.CoalIntCount)));
2647 	printk("   Max outstanding commands = 0x%d\n",
2648 			readl(&(tb->CmdsOutMax)));
2649 	printk("   Bus Types = 0x%x\n", readl(&(tb-> BusTypes)));
2650 	for(i=0;i<16;i++)
2651 		temp_name[i] = readb(&(tb->ServerName[i]));
2652 	temp_name[16] = '\0';
2653 	printk("   Server Name = %s\n", temp_name);
2654 	printk("   Heartbeat Counter = 0x%x\n\n\n",
2655 			readl(&(tb->HeartBeat)));
2656 }
2657 #endif /* CCISS_DEBUG */
2658 
release_io_mem(ctlr_info_t * c)2659 static void release_io_mem(ctlr_info_t *c)
2660 {
2661 	/* if IO mem was not protected do nothing */
2662 	if (c->io_mem_addr == 0)
2663 		return;
2664 	release_region(c->io_mem_addr, c->io_mem_length);
2665 	c->io_mem_addr = 0;
2666 	c->io_mem_length = 0;
2667 }
find_PCI_BAR_index(struct pci_dev * pdev,unsigned long pci_bar_addr)2668 static int find_PCI_BAR_index(struct pci_dev *pdev,
2669                unsigned long pci_bar_addr)
2670 {
2671 	int i, offset, mem_type, bar_type;
2672 	if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
2673 		return 0;
2674 	offset = 0;
2675 	for (i=0; i<DEVICE_COUNT_RESOURCE; i++) {
2676 		bar_type = pci_resource_flags(pdev, i) &
2677 			PCI_BASE_ADDRESS_SPACE;
2678 		if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
2679 			offset += 4;
2680 		else {
2681 			mem_type = pci_resource_flags(pdev, i) &
2682 				PCI_BASE_ADDRESS_MEM_TYPE_MASK;
2683 			switch (mem_type) {
2684 				case PCI_BASE_ADDRESS_MEM_TYPE_32:
2685 				case PCI_BASE_ADDRESS_MEM_TYPE_1M:
2686 					offset += 4; /* 32 bit */
2687 					break;
2688 				case PCI_BASE_ADDRESS_MEM_TYPE_64:
2689 					offset += 8;
2690 					break;
2691 				default: /* reserved in PCI 2.2 */
2692 					printk(KERN_WARNING "Base address is invalid\n");
2693 					return -1;
2694 				break;
2695 			}
2696 		}
2697 		if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
2698 			return i+1;
2699 	}
2700 	return -1;
2701 }
2702 
cciss_pci_init(ctlr_info_t * c,struct pci_dev * pdev)2703 static int cciss_pci_init(ctlr_info_t *c, struct pci_dev *pdev)
2704 {
2705 	ushort subsystem_vendor_id, subsystem_device_id, command;
2706 	int ready = 0;
2707 	__u32 board_id, scratchpad;
2708 	__u64 cfg_offset;
2709 	__u32 cfg_base_addr;
2710 	__u64 cfg_base_addr_index;
2711 	int i;
2712 
2713 	/* check to see if controller has been disabled */
2714 	/* BEFORE we try to enable it */
2715 	(void) pci_read_config_word(pdev, PCI_COMMAND,&command);
2716 	if (!(command & 0x02)) {
2717 		printk(KERN_WARNING "cciss: controller appears to be disabled\n");
2718 		return -1;
2719 	}
2720 	if (pci_enable_device(pdev)) {
2721 		printk(KERN_ERR "cciss: Unable to Enable PCI device\n");
2722 		return -1;
2723 	}
2724 	if (pci_set_dma_mask(pdev, CCISS_DMA_MASK ) != 0) {
2725 		printk(KERN_ERR "cciss:  Unable to set DMA mask\n");
2726 		return -1;
2727 	}
2728 
2729 	subsystem_vendor_id = pdev->subsystem_vendor;
2730 	subsystem_device_id = pdev->subsystem_device;
2731 	board_id = (((__u32) (subsystem_device_id << 16) & 0xffff0000) |
2732 					subsystem_vendor_id );
2733 
2734 
2735 	/* search for our IO range so we can protect it */
2736 	for (i=0; i<DEVICE_COUNT_RESOURCE; i++) {
2737 		/* is this an IO range */
2738 		if (pci_resource_flags(pdev, i) & 0x01) {
2739 			c->io_mem_addr = pci_resource_start(pdev, i);
2740 			c->io_mem_length = pci_resource_end(pdev, i) -
2741 				pci_resource_start(pdev, i) + 1;
2742 #ifdef CCISS_DEBUG
2743 			printk("IO value found base_addr[%d] %lx %lx\n", i,
2744 				c->io_mem_addr, c->io_mem_length);
2745 #endif /* CCISS_DEBUG */
2746 			/* register the IO range */
2747 			if (!request_region( c->io_mem_addr,
2748                                         c->io_mem_length, "cciss")) {
2749 				printk(KERN_WARNING
2750 					"cciss I/O memory range already in "
2751 					"use addr=%lx length=%ld\n",
2752 				c->io_mem_addr, c->io_mem_length);
2753 				c->io_mem_addr= 0;
2754 				c->io_mem_length = 0;
2755 			}
2756 			break;
2757 		}
2758 	}
2759 
2760 #ifdef CCISS_DEBUG
2761 	printk("command = %x\n", command);
2762 	printk("irq = %x\n", pdev->irq);
2763 	printk("board_id = %x\n", board_id);
2764 #endif /* CCISS_DEBUG */
2765 
2766 	c->intr = pdev->irq;
2767 
2768 	/*
2769 	 * Memory base addr is first addr , the second points to the config
2770          *   table
2771 	 */
2772 
2773 	c->paddr = pci_resource_start(pdev, 0); /* addressing mode bits already removed */
2774 #ifdef CCISS_DEBUG
2775 	printk("address 0 = %x\n", c->paddr);
2776 #endif /* CCISS_DEBUG */
2777 	c->vaddr = remap_pci_mem(c->paddr, 200);
2778 	/* Wait for the board to become ready.  (PCI hotplug needs this.)
2779 	 * We poll for up to 120 secs, once per 100ms. */
2780 	for (i=0; i < 1200; i++) {
2781 		scratchpad = readl(c->vaddr + SA5_SCRATCHPAD_OFFSET);
2782 		if (scratchpad == 0xffff0000) {
2783 			ready = 1;
2784 			break;
2785 		}
2786 		set_current_state(TASK_UNINTERRUPTIBLE);
2787 		schedule_timeout(HZ / 10); /* wait 100ms */
2788 	}
2789 	if (!ready) {
2790 		printk(KERN_WARNING "cciss: Board not ready.  Timed out.\n");
2791 		return -1;
2792 	}
2793 
2794 	/* get the address index number */
2795 	cfg_base_addr = readl(c->vaddr + SA5_CTCFG_OFFSET);
2796 	cfg_base_addr &= (__u32) 0x0000ffff;
2797 #ifdef CCISS_DEBUG
2798 	printk("cfg base address = %x\n", cfg_base_addr);
2799 #endif /* CCISS_DEBUG */
2800 	cfg_base_addr_index =
2801 		find_PCI_BAR_index(pdev, cfg_base_addr);
2802 #ifdef CCISS_DEBUG
2803 	printk("cfg base address index = %x\n", cfg_base_addr_index);
2804 #endif /* CCISS_DEBUG */
2805 	if (cfg_base_addr_index == -1) {
2806 		printk(KERN_WARNING "cciss: Cannot find cfg_base_addr_index\n");
2807 		release_io_mem(c);
2808 		return -1;
2809 	}
2810 
2811 	cfg_offset = readl(c->vaddr + SA5_CTMEM_OFFSET);
2812 #ifdef CCISS_DEBUG
2813 	printk("cfg offset = %x\n", cfg_offset);
2814 #endif /* CCISS_DEBUG */
2815 	c->cfgtable = (CfgTable_struct *)
2816 		remap_pci_mem(pci_resource_start(pdev, cfg_base_addr_index)
2817 				+ cfg_offset, sizeof(CfgTable_struct));
2818 	c->board_id = board_id;
2819 
2820 #ifdef CCISS_DEBUG
2821 	print_cfg_table(c->cfgtable);
2822 #endif /* CCISS_DEBUG */
2823 
2824 	for(i=0; i<NR_PRODUCTS; i++) {
2825 		if (board_id == products[i].board_id) {
2826 			c->product_name = products[i].product_name;
2827 			c->access = *(products[i].access);
2828 			break;
2829 		}
2830 	}
2831 	if (  (readb(&c->cfgtable->Signature[0]) != 'C') ||
2832 	      (readb(&c->cfgtable->Signature[1]) != 'I') ||
2833 	      (readb(&c->cfgtable->Signature[2]) != 'S') ||
2834 	      (readb(&c->cfgtable->Signature[3]) != 'S') ) {
2835 		printk("Does not appear to be a valid CISS config table\n");
2836 		return -1;
2837 	}
2838 	/* We didn't find the controller in our list. We know the
2839 	 * signature is valid. If it's an HP device let's try to
2840 	 * bind to the device and fire it up. Otherwise we bail.
2841 	 */
2842 	if (i == NR_PRODUCTS) {
2843 		if (subsystem_vendor_id == PCI_VENDOR_ID_HP) {
2844 			c->product_name = products[NR_PRODUCTS-1].product_name;
2845 			c->access = *(products[NR_PRODUCTS-1].access);
2846 			printk(KERN_WARNING "cciss: This is an unknown "
2847 				"Smart Array controller.\n"
2848 				"cciss: Please update to the latest driver "
2849 				"available from www.hp.com.\n");
2850 		} else {
2851 			printk(KERN_WARNING "cciss: Sorry, I don't know how"
2852 				" to access the Smart Array controller %08lx\n"
2853 					, (unsigned long)board_id);
2854 			return -1;
2855 		}
2856 	}
2857 
2858 #ifdef CONFIG_X86
2859 {
2860 	/* Need to enable prefetch in the SCSI core for 6400 in x86 */
2861 	__u32 prefetch;
2862 	prefetch = readl(&(c->cfgtable->SCSI_Prefetch));
2863 	prefetch |= 0x100;
2864 	writel(prefetch, &(c->cfgtable->SCSI_Prefetch));
2865 }
2866 #endif
2867 
2868 #ifdef CCISS_DEBUG
2869 	printk("Trying to put board into Simple mode\n");
2870 #endif /* CCISS_DEBUG */
2871 	c->max_commands = readl(&(c->cfgtable->CmdsOutMax));
2872 	/* Update the field, and then ring the doorbell */
2873 	writel( CFGTBL_Trans_Simple,
2874 		&(c->cfgtable->HostWrite.TransportRequest));
2875 	writel( CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
2876 
2877 	/* Here, we wait, possibly for a long time, (4 secs or more).
2878 	 * In some unlikely cases, (e.g. A failed 144 GB drive in a
2879 	 * RAID 5 set was hot replaced just as we're coming in here) it
2880 	 * can take that long.  Normally (almost always) we will wait
2881 	 * less than 1 sec. */
2882 	for(i=0;i<MAX_CONFIG_WAIT;i++) {
2883 		if (!(readl(c->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
2884 			break;
2885 		/* delay and try again */
2886 		set_current_state(TASK_INTERRUPTIBLE);
2887 		schedule_timeout(1);
2888 	}
2889 
2890 #ifdef CCISS_DEBUG
2891 	printk(KERN_DEBUG "I counter got to %d %x\n", i, readl(c->vaddr + SA5_DOORBELL));
2892 #endif /* CCISS_DEBUG */
2893 #ifdef CCISS_DEBUG
2894 	print_cfg_table(c->cfgtable);
2895 #endif /* CCISS_DEBUG */
2896 
2897 	if (!(readl(&(c->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
2898 		printk(KERN_WARNING "cciss: unable to get board into"
2899 					" simple mode\n");
2900 		return -1;
2901 	}
2902 	return 0;
2903 
2904 }
2905 
2906 /*
2907  * Gets information about the local volumes attached to the controller.
2908  */
cciss_getgeometry(int cntl_num)2909 static void cciss_getgeometry(int cntl_num)
2910 {
2911 	ReportLunData_struct *ld_buff;
2912 	ReadCapdata_struct *size_buff;
2913 	InquiryData_struct *inq_buff;
2914 	int return_code;
2915 	int i;
2916 	int listlength = 0;
2917 	__u32 lunid = 0;
2918 	int block_size;
2919 	int total_size;
2920 
2921 	ld_buff = kmalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
2922 	if (ld_buff == NULL) {
2923 		printk(KERN_ERR "cciss: out of memory\n");
2924 		return;
2925 	}
2926 	memset(ld_buff, 0, sizeof(ReportLunData_struct));
2927 	size_buff = kmalloc(sizeof( ReadCapdata_struct), GFP_KERNEL);
2928         if (size_buff == NULL) {
2929                 printk(KERN_ERR "cciss: out of memory\n");
2930 		kfree(ld_buff);
2931                 return;
2932         }
2933 	inq_buff = kmalloc(sizeof( InquiryData_struct), GFP_KERNEL);
2934         if (inq_buff == NULL) {
2935                 printk(KERN_ERR "cciss: out of memory\n");
2936                 kfree(ld_buff);
2937 		kfree(size_buff);
2938                 return;
2939         }
2940 	/* Get the firmware version */
2941 	return_code = sendcmd(CISS_INQUIRY, cntl_num, inq_buff,
2942 		sizeof(InquiryData_struct), 0, 0 ,0, NULL);
2943 	if (return_code == IO_OK) {
2944 		hba[cntl_num]->firm_ver[0] = inq_buff->data_byte[32];
2945 		hba[cntl_num]->firm_ver[1] = inq_buff->data_byte[33];
2946 		hba[cntl_num]->firm_ver[2] = inq_buff->data_byte[34];
2947 		hba[cntl_num]->firm_ver[3] = inq_buff->data_byte[35];
2948 	} else  {	/* send command failed */
2949 		printk(KERN_WARNING "cciss: unable to determine firmware"
2950 			" version of controller\n");
2951 	}
2952 	/* Get the number of logical volumes */
2953 	return_code = sendcmd(CISS_REPORT_LOG, cntl_num, ld_buff,
2954 			sizeof(ReportLunData_struct), 0, 0, 0, NULL);
2955 
2956 	if (return_code == IO_OK) {
2957 #ifdef CCISS_DEBUG
2958 		printk("LUN Data\n--------------------------\n");
2959 #endif /* CCISS_DEBUG */
2960 
2961 		listlength = be32_to_cpu(*((__u32 *) &ld_buff->LUNListLength[0]));
2962 	} else { /* reading number of logical volumes failed */
2963 		printk(KERN_WARNING "cciss: report logical volume"
2964 			" command failed\n");
2965 		listlength = 0;
2966 	}
2967 	hba[cntl_num]->num_luns = listlength / 8; /* 8 bytes pre entry */
2968 	if (hba[cntl_num]->num_luns > CISS_MAX_LUN) {
2969 		printk(KERN_ERR "cciss:  only %d number of logical volumes supported\n",
2970 			CISS_MAX_LUN);
2971 		hba[cntl_num]->num_luns = CISS_MAX_LUN;
2972 	}
2973 #ifdef CCISS_DEBUG
2974 	printk(KERN_DEBUG "Length = %x %x %x %x = %d\n", ld_buff->LUNListLength[0],
2975 		ld_buff->LUNListLength[1], ld_buff->LUNListLength[2],
2976 		ld_buff->LUNListLength[3],  hba[cntl_num]->num_luns);
2977 #endif /* CCISS_DEBUG */
2978 
2979 	hba[cntl_num]->highest_lun = hba[cntl_num]->num_luns-1;
2980 	for(i=0; i<  hba[cntl_num]->num_luns; i++) {
2981 	  	lunid = (0xff & (unsigned int)(ld_buff->LUN[i][3])) << 24;
2982         	lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][2])) << 16;
2983         	lunid |= (0xff & (unsigned int)(ld_buff->LUN[i][1])) << 8;
2984         	lunid |= 0xff & (unsigned int)(ld_buff->LUN[i][0]);
2985 		hba[cntl_num]->drv[i].LunID = lunid;
2986 
2987 #ifdef CCISS_DEBUG
2988 	  	printk(KERN_DEBUG "LUN[%d]:  %x %x %x %x = %x\n", i,
2989 		ld_buff->LUN[i][0], ld_buff->LUN[i][1],ld_buff->LUN[i][2],
2990 		ld_buff->LUN[i][3], hba[cntl_num]->drv[i].LunID);
2991 #endif /* CCISS_DEBUG */
2992 
2993 	  	memset(size_buff, 0, sizeof(ReadCapdata_struct));
2994 	  	return_code = sendcmd(CCISS_READ_CAPACITY, cntl_num, size_buff,
2995 				sizeof( ReadCapdata_struct), 1, i, 0, NULL);
2996 	  	if (return_code == IO_OK) {
2997 			total_size = (0xff &
2998 				(unsigned int)(size_buff->total_size[0])) << 24;
2999 			total_size |= (0xff &
3000 				(unsigned int)(size_buff->total_size[1])) << 16;
3001 			total_size |= (0xff &
3002 				(unsigned int)(size_buff->total_size[2])) << 8;
3003 			total_size |= (0xff & (unsigned int)
3004 				(size_buff->total_size[3]));
3005 			total_size++; 	/* command returns highest */
3006 					/* block address */
3007 
3008 			block_size = (0xff &
3009 				(unsigned int)(size_buff->block_size[0])) << 24;
3010                 	block_size |= (0xff &
3011 				(unsigned int)(size_buff->block_size[1])) << 16;
3012                 	block_size |= (0xff &
3013 				(unsigned int)(size_buff->block_size[2])) << 8;
3014                 	block_size |= (0xff &
3015 				(unsigned int)(size_buff->block_size[3]));
3016 		} else {	/* read capacity command failed */
3017 			printk(KERN_WARNING "cciss: read capacity failed\n");
3018 			total_size = block_size = 0;
3019 		}
3020 		printk(KERN_INFO "      blocks= %d block_size= %d\n",
3021 					total_size, block_size);
3022 
3023 		/* Execute the command to read the disk geometry */
3024 		memset(inq_buff, 0, sizeof(InquiryData_struct));
3025 		return_code = sendcmd(CISS_INQUIRY, cntl_num, inq_buff,
3026 			sizeof(InquiryData_struct), 1, i, 0xC1, NULL );
3027 	  	if (return_code == IO_OK) {
3028 			if (inq_buff->data_byte[8] == 0xFF) {
3029 			   printk(KERN_WARNING "cciss: reading geometry failed, volume does not support reading geometry\n");
3030 
3031                            hba[cntl_num]->drv[i].block_size = block_size;
3032                            hba[cntl_num]->drv[i].nr_blocks = total_size;
3033                            hba[cntl_num]->drv[i].heads = 255;
3034                            hba[cntl_num]->drv[i].sectors = 32; /* Sectors */
3035 			   					/* per track */
3036                            hba[cntl_num]->drv[i].cylinders = total_size
3037 				   				/ 255 / 32;
3038 			} else {
3039 
3040 		 	   hba[cntl_num]->drv[i].block_size = block_size;
3041                            hba[cntl_num]->drv[i].nr_blocks = total_size;
3042                            hba[cntl_num]->drv[i].heads =
3043 					inq_buff->data_byte[6];
3044                            hba[cntl_num]->drv[i].sectors =
3045 					inq_buff->data_byte[7];
3046 			   hba[cntl_num]->drv[i].cylinders =
3047 					(inq_buff->data_byte[4] & 0xff) << 8;
3048 			   hba[cntl_num]->drv[i].cylinders +=
3049                                         inq_buff->data_byte[5];
3050                            hba[cntl_num]->drv[i].raid_level =
3051 					inq_buff->data_byte[8];
3052 			}
3053 		}
3054 		else {	/* Get geometry failed */
3055 			printk(KERN_WARNING "cciss: reading geometry failed, continuing with default geometry\n");
3056 
3057 			hba[cntl_num]->drv[i].block_size = block_size;
3058 			hba[cntl_num]->drv[i].nr_blocks = total_size;
3059 			hba[cntl_num]->drv[i].heads = 255;
3060 			hba[cntl_num]->drv[i].sectors = 32; 	/* Sectors */
3061 								/* per track */
3062 			hba[cntl_num]->drv[i].cylinders = total_size / 255 / 32;
3063 		}
3064 		if (hba[cntl_num]->drv[i].raid_level > 5)
3065 			hba[cntl_num]->drv[i].raid_level = RAID_UNKNOWN;
3066 		printk(KERN_INFO "      heads= %d, sectors= %d, cylinders= %d RAID %s\n\n",
3067 			hba[cntl_num]->drv[i].heads,
3068 			hba[cntl_num]->drv[i].sectors,
3069 			hba[cntl_num]->drv[i].cylinders,
3070 			raid_label[hba[cntl_num]->drv[i].raid_level]);
3071 	}
3072 	kfree(ld_buff);
3073 	kfree(size_buff);
3074 	kfree(inq_buff);
3075 }
3076 
3077 /* Function to find the first free pointer into our hba[] array */
3078 /* Returns -1 if no free entries are left.  */
alloc_cciss_hba(void)3079 static int alloc_cciss_hba(void)
3080 {
3081 	int i;
3082 	for(i=0; i< MAX_CTLR; i++) {
3083 		if (hba[i] == NULL) {
3084 			hba[i] = kmalloc(sizeof(ctlr_info_t), GFP_KERNEL);
3085 			if (hba[i]==NULL) {
3086 				printk(KERN_ERR "cciss: out of memory.\n");
3087 				return -1;
3088 			}
3089 			return i;
3090 		}
3091 	}
3092 	printk(KERN_WARNING
3093 		"cciss: This driver supports a maximum of %d controllers.\n"
3094 		"You can change this value in cciss.c and recompile.\n",
3095 		MAX_CTLR);
3096 	return -1;
3097 }
3098 
free_hba(int i)3099 static void free_hba(int i)
3100 {
3101 	kfree(hba[i]);
3102 	hba[i]=NULL;
3103 }
3104 #ifdef CONFIG_CISS_MONITOR_THREAD
fail_all_cmds(unsigned long ctlr)3105 static void fail_all_cmds(unsigned long ctlr)
3106 {
3107 	/* If we get here, the board is apparently dead. */
3108 	ctlr_info_t *h = hba[ctlr];
3109 	CommandList_struct *c;
3110 	unsigned long flags;
3111 
3112 	printk(KERN_WARNING "cciss%d: controller not responding.\n", h->ctlr);
3113 	h->alive = 0;	/* the controller apparently died... */
3114 
3115 	spin_lock_irqsave(&io_request_lock, flags);
3116 
3117 	pci_disable_device(h->pdev); /* Make sure it is really dead. */
3118 
3119 	/* move everything off the request queue onto the completed queue */
3120 	while( (c = h->reqQ) != NULL ) {
3121 		removeQ(&(h->reqQ), c);
3122 		h->Qdepth--;
3123 		addQ (&(h->cmpQ), c);
3124 	}
3125 
3126 	/* Now, fail everything on the completed queue with a HW error */
3127 	while( (c = h->cmpQ) != NULL ) {
3128 		removeQ(&h->cmpQ, c);
3129 		c->err_info->CommandStatus = CMD_HARDWARE_ERR;
3130 		if (c->cmd_type == CMD_RWREQ) {
3131 			complete_command(h, c, 0);
3132 		} else if (c->cmd_type == CMD_IOCTL_PEND)
3133 			complete(c->waiting);
3134 #		ifdef CONFIG_CISS_SCSI_TAPE
3135 			else if (c->cmd_type == CMD_SCSI)
3136 				complete_scsi_command(c, 0, 0);
3137 #		endif
3138 	}
3139 	spin_unlock_irqrestore(&io_request_lock, flags);
3140 	return;
3141 }
cciss_monitor(void * ctlr)3142 static int cciss_monitor(void *ctlr)
3143 {
3144 	/* If the board fails, we ought to detect that.  So we periodically
3145 	send down a No-Op message and expect it to complete quickly.  If it
3146 	doesn't, then we assume the board is dead, and fail all commands.
3147 	This is useful mostly in a multipath configuration, so that failover
3148 	will happen. */
3149 
3150 	int rc;
3151 	ctlr_info_t *h = (ctlr_info_t *) ctlr;
3152 	unsigned long flags;
3153 	u32 current_timer;
3154 
3155 	daemonize();
3156 	exit_files(current);
3157 	reparent_to_init();
3158 
3159 	printk("cciss%d: Monitor thread starting.\n", h->ctlr);
3160 
3161 	/* only listen to signals if the HA was loaded as a module.  */
3162 #define SHUTDOWN_SIGS   (sigmask(SIGKILL)|sigmask(SIGINT)|sigmask(SIGTERM))
3163 	siginitsetinv(&current->blocked, SHUTDOWN_SIGS);
3164 	sprintf(current->comm, "ccissmon%d", h->ctlr);
3165 	h->monitor_thread = current;
3166 
3167 	init_timer(&h->watchdog);
3168 	h->watchdog.function = fail_all_cmds;
3169 	h->watchdog.data = (unsigned long) h->ctlr;
3170 	while (1) {
3171   		/* check heartbeat timer */
3172                 current_timer = readl(&h->cfgtable->HeartBeat);
3173   		current_timer &= 0x0fffffff;
3174   		if (heartbeat_timer == current_timer) {
3175   			fail_all_cmds(h->ctlr);
3176   			break;
3177   		}
3178   		else
3179   			heartbeat_timer = current_timer;
3180 
3181 		set_current_state(TASK_UNINTERRUPTIBLE);
3182 		schedule_timeout(h->monitor_period * HZ);
3183 		h->watchdog.expires = jiffies + HZ * h->monitor_deadline;
3184 		add_timer(&h->watchdog);
3185 		/* send down a trivial command (no op message) to ctlr */
3186 		rc = sendcmd_withirq(3, h->ctlr, NULL, 0, 0, 0, 0, TYPE_MSG);
3187 		del_timer(&h->watchdog);
3188 		if (!CTLR_IS_ALIVE(h))
3189 			break;
3190 		if (signal_pending(current)) {
3191 			printk(KERN_WARNING "%s received signal.\n",
3192 				current->comm);
3193 			break;
3194 		}
3195 		if (h->monitor_period == 0) /* zero period means exit thread */
3196 			break;
3197 	}
3198 	printk(KERN_INFO "%s exiting.\n", current->comm);
3199 	spin_lock_irqsave(&io_request_lock, flags);
3200 	h->monitor_started = 0;
3201 	h->monitor_thread = NULL;
3202 	spin_unlock_irqrestore(&io_request_lock, flags);
3203 	return 0;
3204 }
start_monitor_thread(ctlr_info_t * h,unsigned char * cmd,unsigned long count,int (* cciss_monitor)(void *),int * rc)3205 static int start_monitor_thread(ctlr_info_t *h, unsigned char *cmd,
3206 		unsigned long count, int (*cciss_monitor)(void *), int *rc)
3207 {
3208 	unsigned long flags;
3209 	unsigned int new_period, old_period, new_deadline, old_deadline;
3210 
3211 	if (strncmp("monitor", cmd, 7) == 0) {
3212 		new_period = simple_strtol(cmd + 8, NULL, 10);
3213 		spin_lock_irqsave(&io_request_lock, flags);
3214 		new_deadline = h->monitor_deadline;
3215 		spin_unlock_irqrestore(&io_request_lock, flags);
3216 	} else if (strncmp("deadline", cmd, 8) == 0) {
3217 		new_deadline = simple_strtol(cmd + 9, NULL, 10);
3218 		spin_lock_irqsave(&io_request_lock, flags);
3219 		new_period = h->monitor_period;
3220 		spin_unlock_irqrestore(&io_request_lock, flags);
3221 	} else
3222 		return -1;
3223 	if (new_period != 0 && new_period < CCISS_MIN_PERIOD)
3224 		new_period = CCISS_MIN_PERIOD;
3225 	if (new_period > CCISS_MAX_PERIOD)
3226 		new_period = CCISS_MAX_PERIOD;
3227 	if (new_deadline >= new_period) {
3228 		new_deadline = new_period - 5;
3229 		printk(KERN_INFO "setting deadline to %d\n", new_deadline);
3230 	}
3231 	spin_lock_irqsave(&io_request_lock, flags);
3232 	if (h->monitor_started != 0)  {
3233 		old_period = h->monitor_period;
3234 		old_deadline = h->monitor_deadline;
3235 		h->monitor_period = new_period;
3236 		h->monitor_deadline = new_deadline;
3237 		spin_unlock_irqrestore(&io_request_lock, flags);
3238 		if (new_period == 0) {
3239 			printk(KERN_INFO "cciss%d: stopping monitor thread\n",
3240 				h->ctlr);
3241 			*rc = count;
3242 			return 0;
3243 		}
3244 		if (new_period != old_period)
3245 			printk(KERN_INFO "cciss%d: adjusting monitor thread "
3246 				"period from %d to %d seconds\n",
3247 				h->ctlr, old_period, new_period);
3248 		if (new_deadline != old_deadline)
3249 			printk(KERN_INFO "cciss%d: adjusting monitor thread "
3250 				"deadline from %d to %d seconds\n",
3251 				h->ctlr, old_deadline, new_deadline);
3252 		*rc = count;
3253 		return 0;
3254 	}
3255 	h->monitor_started = 1;
3256 	h->monitor_period = new_period;
3257 	h->monitor_deadline = new_deadline;
3258 	spin_unlock_irqrestore(&io_request_lock, flags);
3259 	kernel_thread(cciss_monitor, h, 0);
3260 	*rc = count;
3261 	return 0;
3262 }
3263 
kill_monitor_thread(ctlr_info_t * h)3264 static void kill_monitor_thread(ctlr_info_t *h)
3265 {
3266 	if (h->monitor_thread)
3267 		send_sig(SIGKILL, h->monitor_thread, 1);
3268 }
3269 #else
3270 #define kill_monitor_thread(h)
3271 #endif
3272 /*
3273  *  This is it.  Find all the controllers and register them.  I really hate
3274  *  stealing all these major device numbers.
3275  *  returns the number of block devices registered.
3276  */
cciss_init_one(struct pci_dev * pdev,const struct pci_device_id * ent)3277 static int __init cciss_init_one(struct pci_dev *pdev,
3278 	const struct pci_device_id *ent)
3279 {
3280 	request_queue_t *q;
3281 	int i;
3282 	int j;
3283 	int rc;
3284 
3285 	printk(KERN_DEBUG "cciss: Device 0x%x has been found at"
3286 			" bus %d dev %d func %d\n",
3287 		pdev->device, pdev->bus->number, PCI_SLOT(pdev->devfn),
3288 			PCI_FUNC(pdev->devfn));
3289 	i = alloc_cciss_hba();
3290 	if (i < 0 )
3291 		return -1;
3292 	memset(hba[i], 0, sizeof(ctlr_info_t));
3293 	if (cciss_pci_init(hba[i], pdev) != 0) {
3294 		free_hba(i);
3295 		return -1;
3296 	}
3297 	sprintf(hba[i]->devname, "cciss%d", i);
3298 	hba[i]->ctlr = i;
3299 
3300 	/* register with the major number, or get a dynamic major number */
3301 	/* by passing 0 as argument */
3302 
3303 	if (i < MAX_CTLR_ORIG)
3304 		hba[i]->major = MAJOR_NR + i;
3305 
3306 	hba[i]->pdev = pdev;
3307 	ASSERT_CTLR_ALIVE(hba[i]);
3308 
3309 	rc = (register_blkdev(hba[i]->major, hba[i]->devname, &cciss_fops));
3310 	if (rc < 0) {
3311 		printk(KERN_ERR "cciss:  Unable to get major number "
3312 			"%d for %s\n", hba[i]->major, hba[i]->devname);
3313 		release_io_mem(hba[i]);
3314 		free_hba(i);
3315 		return -1;
3316 	} else {
3317 		if (i < MAX_CTLR_ORIG) {
3318 			hba[i]->major = MAJOR_NR + i;
3319 			map_major_to_ctlr[MAJOR_NR + i] = i;
3320 		} else {
3321 			hba[i]->major = rc;
3322 			map_major_to_ctlr[rc] = i;
3323 		}
3324 	}
3325 
3326 	/* make sure the board interrupts are off */
3327 	hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_OFF);
3328 	if (request_irq(hba[i]->intr, do_cciss_intr,
3329 		SA_INTERRUPT | SA_SHIRQ | SA_SAMPLE_RANDOM,
3330 			hba[i]->devname, hba[i])) {
3331 
3332 		printk(KERN_ERR "cciss: Unable to get irq %d for %s\n",
3333 			hba[i]->intr, hba[i]->devname);
3334 		unregister_blkdev( hba[i]->major, hba[i]->devname);
3335 		map_major_to_ctlr[hba[i]->major] = 0;
3336 		release_io_mem(hba[i]);
3337 		free_hba(i);
3338 		return -1;
3339 	}
3340 	hba[i]->cmd_pool_bits = (__u32*)kmalloc(
3341         	((NR_CMDS+31)/32)*sizeof(__u32), GFP_KERNEL);
3342 	hba[i]->cmd_pool = (CommandList_struct *)pci_alloc_consistent(
3343 		hba[i]->pdev, NR_CMDS * sizeof(CommandList_struct),
3344 		&(hba[i]->cmd_pool_dhandle));
3345 	hba[i]->errinfo_pool = (ErrorInfo_struct *)pci_alloc_consistent(
3346 		hba[i]->pdev, NR_CMDS * sizeof( ErrorInfo_struct),
3347 		&(hba[i]->errinfo_pool_dhandle));
3348 	if ((hba[i]->cmd_pool_bits == NULL)
3349 		|| (hba[i]->cmd_pool == NULL)
3350 		|| (hba[i]->errinfo_pool == NULL)) {
3351 
3352 		if (hba[i]->cmd_pool_bits)
3353                 	kfree(hba[i]->cmd_pool_bits);
3354                 if (hba[i]->cmd_pool)
3355                 	pci_free_consistent(hba[i]->pdev,
3356 				NR_CMDS * sizeof(CommandList_struct),
3357 				hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
3358 		if (hba[i]->errinfo_pool)
3359 			pci_free_consistent(hba[i]->pdev,
3360 				NR_CMDS * sizeof( ErrorInfo_struct),
3361 				hba[i]->errinfo_pool,
3362 				hba[i]->errinfo_pool_dhandle);
3363                 free_irq(hba[i]->intr, hba[i]);
3364                 unregister_blkdev(hba[i]->major, hba[i]->devname);
3365 		map_major_to_ctlr[hba[i]->major] = 0;
3366 		release_io_mem(hba[i]);
3367 		free_hba(i);
3368                 printk( KERN_ERR "cciss: out of memory");
3369 		return -1;
3370 	}
3371 
3372 	/* Initialize the pdev driver private data.
3373 		have it point to hba[i].  */
3374 	pci_set_drvdata(pdev, hba[i]);
3375 	/* command and error info recs zeroed out before
3376 			they are used */
3377         memset(hba[i]->cmd_pool_bits, 0, ((NR_CMDS+31)/32)*sizeof(__u32));
3378 
3379 #ifdef CCISS_DEBUG
3380 	printk(KERN_DEBUG "Scanning for drives on controller cciss%d\n",i);
3381 #endif /* CCISS_DEBUG */
3382 
3383 	cciss_getgeometry(i);
3384 
3385 	cciss_find_non_disk_devices(i);	/* find our tape drives, if any */
3386 
3387 	/* Turn the interrupts on so we can service requests */
3388 	hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_ON);
3389 
3390 	cciss_procinit(i);
3391 
3392 	q = BLK_DEFAULT_QUEUE(hba[i]->major);
3393 	q->queuedata = hba[i];
3394 	blk_init_queue(q, do_cciss_request);
3395 	blk_queue_bounce_limit(q, hba[i]->pdev->dma_mask);
3396 	blk_queue_headactive(q, 0);
3397 
3398 	/* fill in the other Kernel structs */
3399 	blksize_size[hba[i]->major] = hba[i]->blocksizes;
3400         hardsect_size[hba[i]->major] = hba[i]->hardsizes;
3401         read_ahead[hba[i]->major] = READ_AHEAD;
3402 
3403 	/* Set the pointers to queue functions */
3404 	q->back_merge_fn = cpq_back_merge_fn;
3405         q->front_merge_fn = cpq_front_merge_fn;
3406         q->merge_requests_fn = cpq_merge_requests_fn;
3407 
3408 
3409 	/* Fill in the gendisk data */
3410 	hba[i]->gendisk.major = hba[i]->major;
3411 	hba[i]->gendisk.major_name = "cciss";
3412 	hba[i]->gendisk.minor_shift = NWD_SHIFT;
3413 	hba[i]->gendisk.max_p = MAX_PART;
3414 	hba[i]->gendisk.part = hba[i]->hd;
3415 	hba[i]->gendisk.sizes = hba[i]->sizes;
3416 	hba[i]->gendisk.nr_real = hba[i]->highest_lun+1;
3417 	hba[i]->gendisk.fops = &cciss_fops;
3418 
3419 	/* Get on the disk list */
3420 	add_gendisk(&(hba[i]->gendisk));
3421 
3422 	cciss_geninit(i);
3423 	for(j=0; j<NWD; j++)
3424 		register_disk(&(hba[i]->gendisk),
3425 			MKDEV(hba[i]->major, j <<4),
3426 			MAX_PART, &cciss_fops,
3427 			hba[i]->drv[j].nr_blocks);
3428 
3429 	cciss_register_scsi(i, 1);  /* hook ourself into SCSI subsystem */
3430 
3431 	return 1;
3432 }
3433 
cciss_remove_one(struct pci_dev * pdev)3434 static void __devexit cciss_remove_one (struct pci_dev *pdev)
3435 {
3436 	ctlr_info_t *tmp_ptr;
3437 	int i;
3438 	char flush_buf[4];
3439 	int return_code;
3440 
3441 	if (pci_get_drvdata(pdev) == NULL) {
3442 		printk( KERN_ERR "cciss: Unable to remove device \n");
3443 		return;
3444 	}
3445 	tmp_ptr = pci_get_drvdata(pdev);
3446 	i = tmp_ptr->ctlr;
3447 	if (hba[i] == NULL) {
3448 		printk(KERN_ERR "cciss: device appears to "
3449 			"already be removed \n");
3450 		return;
3451 	}
3452 	kill_monitor_thread(hba[i]);
3453 	/* no sense in trying to flush a dead board's cache. */
3454 	if (CTLR_IS_ALIVE(hba[i])) {
3455 		/* Turn board interrupts off and flush the cache */
3456 		/* write all data in the battery backed cache to disks */
3457  	memset(flush_buf, 0, 4);
3458 		return_code = sendcmd(CCISS_CACHE_FLUSH, i, flush_buf,
3459 					4, 0, 0, 0, NULL);
3460 		if (return_code != IO_OK)
3461  		printk(KERN_WARNING
3462 				"cciss%d: Error flushing cache\n", i);
3463  	}
3464 	free_irq(hba[i]->intr, hba[i]);
3465 	pci_set_drvdata(pdev, NULL);
3466 	iounmap((void*)hba[i]->vaddr);
3467 	cciss_unregister_scsi(i);  /* unhook from SCSI subsystem */
3468 	unregister_blkdev(hba[i]->major, hba[i]->devname);
3469 	map_major_to_ctlr[hba[i]->major] = 0;
3470 	remove_proc_entry(hba[i]->devname, proc_cciss);
3471 
3472 
3473 	/* remove it from the disk list */
3474 	del_gendisk(&(hba[i]->gendisk));
3475 
3476 	pci_free_consistent(hba[i]->pdev, NR_CMDS * sizeof(CommandList_struct),
3477 		hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
3478 	pci_free_consistent(hba[i]->pdev, NR_CMDS * sizeof( ErrorInfo_struct),
3479 		hba[i]->errinfo_pool, hba[i]->errinfo_pool_dhandle);
3480 	kfree(hba[i]->cmd_pool_bits);
3481 	release_io_mem(hba[i]);
3482 	free_hba(i);
3483 }
3484 
3485 static struct pci_driver cciss_pci_driver = {
3486 	 name:   "cciss",
3487 	probe:  cciss_init_one,
3488 	remove:  __devexit_p(cciss_remove_one),
3489 	id_table:  cciss_pci_device_id, /* id_table */
3490 };
3491 
3492 /*
3493 *  This is it.  Register the PCI driver information for the cards we control
3494 *  the OS will call our registered routines when it finds one of our cards.
3495 */
cciss_init(void)3496 int __init cciss_init(void)
3497 {
3498 
3499 	printk(KERN_INFO DRIVER_NAME "\n");
3500 	/* Register for out PCI devices */
3501 	return pci_module_init(&cciss_pci_driver);
3502 }
3503 
3504 EXPORT_NO_SYMBOLS;
init_cciss_module(void)3505 static int __init init_cciss_module(void)
3506 {
3507 	register_cciss_ioctl32();
3508 	return cciss_init();
3509 }
3510 
cleanup_cciss_module(void)3511 static void __exit cleanup_cciss_module(void)
3512 {
3513 	int i;
3514 
3515 	unregister_cciss_ioctl32();
3516 	pci_unregister_driver(&cciss_pci_driver);
3517 	/* double check that all controller entrys have been removed */
3518 	for (i=0; i< MAX_CTLR; i++) {
3519 		if (hba[i] != NULL) {
3520 			printk(KERN_WARNING "cciss: had to remove"
3521 					" controller %d\n", i);
3522 			cciss_remove_one(hba[i]->pdev);
3523 		}
3524 	}
3525 	remove_proc_entry("cciss", proc_root_driver);
3526 }
3527 
3528 module_init(init_cciss_module);
3529 module_exit(cleanup_cciss_module);
3530