1/*
2 *    Disk Array driver for Compaq SA53xx Controllers, SCSI Tape module
3 *    Copyright 2001 Compaq Computer Corporation
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 iss_storagedev@hp.com
20 *
21 *    Author: Stephen M. Cameron
22 */
23#ifdef CONFIG_CISS_SCSI_TAPE
24
25/* Here we have code to present the driver as a scsi driver
26   as it is simultaneously presented as a block driver.  The
27   reason for doing this is to allow access to SCSI tape drives
28   through the array controller.  Note in particular, neither
29   physical nor logical disks are presented through the scsi layer. */
30
31#include <linux/timer.h>
32#include <linux/completion.h>
33#include <linux/slab.h>
34#include <linux/string.h>
35
36#include <asm/atomic.h>
37
38#include <scsi/scsi_cmnd.h>
39#include <scsi/scsi_device.h>
40#include <scsi/scsi_host.h>
41
42#include "cciss_scsi.h"
43
44#define CCISS_ABORT_MSG 0x00
45#define CCISS_RESET_MSG 0x01
46
47/* some prototypes... */
48static int sendcmd(
49	__u8	cmd,
50	int	ctlr,
51	void	*buff,
52	size_t	size,
53	unsigned int use_unit_num, /* 0: address the controller,
54				      1: address logical volume log_unit,
55				      2: address is in scsi3addr */
56	unsigned int log_unit,
57	__u8	page_code,
58	unsigned char *scsi3addr,
59	int cmd_type);
60
61
62static int cciss_scsi_proc_info(
63		struct Scsi_Host *sh,
64		char *buffer, /* data buffer */
65		char **start, 	   /* where data in buffer starts */
66		off_t offset,	   /* offset from start of imaginary file */
67		int length, 	   /* length of data in buffer */
68		int func);	   /* 0 == read, 1 == write */
69
70static int cciss_scsi_queue_command (struct scsi_cmnd *cmd,
71		void (* done)(struct scsi_cmnd *));
72static int cciss_eh_device_reset_handler(struct scsi_cmnd *);
73static int cciss_eh_abort_handler(struct scsi_cmnd *);
74
75static struct cciss_scsi_hba_t ccissscsi[MAX_CTLR] = {
76	{ .name = "cciss0", .ndevices = 0 },
77	{ .name = "cciss1", .ndevices = 0 },
78	{ .name = "cciss2", .ndevices = 0 },
79	{ .name = "cciss3", .ndevices = 0 },
80	{ .name = "cciss4", .ndevices = 0 },
81	{ .name = "cciss5", .ndevices = 0 },
82	{ .name = "cciss6", .ndevices = 0 },
83	{ .name = "cciss7", .ndevices = 0 },
84};
85
86static struct scsi_host_template cciss_driver_template = {
87	.module			= THIS_MODULE,
88	.name			= "cciss",
89	.proc_name		= "cciss",
90	.proc_info		= cciss_scsi_proc_info,
91	.queuecommand		= cciss_scsi_queue_command,
92	.can_queue		= SCSI_CCISS_CAN_QUEUE,
93	.this_id		= 7,
94	.sg_tablesize		= MAXSGENTRIES,
95	.cmd_per_lun		= 1,
96	.use_clustering		= DISABLE_CLUSTERING,
97	/* Can't have eh_bus_reset_handler or eh_host_reset_handler for cciss */
98	.eh_device_reset_handler= cciss_eh_device_reset_handler,
99	.eh_abort_handler	= cciss_eh_abort_handler,
100};
101
102#pragma pack(1)
103struct cciss_scsi_cmd_stack_elem_t {
104	CommandList_struct cmd;
105	ErrorInfo_struct Err;
106	__u32 busaddr;
107	__u32 pad;
108};
109
110#pragma pack()
111
112#define CMD_STACK_SIZE (SCSI_CCISS_CAN_QUEUE * \
113		CCISS_MAX_SCSI_DEVS_PER_HBA + 2)
114			// plus two for init time usage
115
116#pragma pack(1)
117struct cciss_scsi_cmd_stack_t {
118	struct cciss_scsi_cmd_stack_elem_t *pool;
119	struct cciss_scsi_cmd_stack_elem_t *elem[CMD_STACK_SIZE];
120	dma_addr_t cmd_pool_handle;
121	int top;
122};
123#pragma pack()
124
125struct cciss_scsi_adapter_data_t {
126	struct Scsi_Host *scsi_host;
127	struct cciss_scsi_cmd_stack_t cmd_stack;
128	int registered;
129	spinlock_t lock; // to protect ccissscsi[ctlr];
130};
131
132#define CPQ_TAPE_LOCK(ctlr, flags) spin_lock_irqsave( \
133	&(((struct cciss_scsi_adapter_data_t *) \
134	hba[ctlr]->scsi_ctlr)->lock), flags);
135#define CPQ_TAPE_UNLOCK(ctlr, flags) spin_unlock_irqrestore( \
136	&(((struct cciss_scsi_adapter_data_t *) \
137	hba[ctlr]->scsi_ctlr)->lock), flags);
138
139static CommandList_struct *
140scsi_cmd_alloc(ctlr_info_t *h)
141{
142	/* assume only one process in here at a time, locking done by caller. */
143	/* use CCISS_LOCK(ctlr) */
144	/* might be better to rewrite how we allocate scsi commands in a way that */
145	/* needs no locking at all. */
146
147	/* take the top memory chunk off the stack and return it, if any. */
148	struct cciss_scsi_cmd_stack_elem_t *c;
149	struct cciss_scsi_adapter_data_t *sa;
150	struct cciss_scsi_cmd_stack_t *stk;
151	u64bit temp64;
152
153	sa = (struct cciss_scsi_adapter_data_t *) h->scsi_ctlr;
154	stk = &sa->cmd_stack;
155
156	if (stk->top < 0)
157		return NULL;
158	c = stk->elem[stk->top];
159	/* memset(c, 0, sizeof(*c)); */
160	memset(&c->cmd, 0, sizeof(c->cmd));
161	memset(&c->Err, 0, sizeof(c->Err));
162	/* set physical addr of cmd and addr of scsi parameters */
163	c->cmd.busaddr = c->busaddr;
164	/* (__u32) (stk->cmd_pool_handle +
165		(sizeof(struct cciss_scsi_cmd_stack_elem_t)*stk->top)); */
166
167	temp64.val = (__u64) (c->busaddr + sizeof(CommandList_struct));
168	/* (__u64) (stk->cmd_pool_handle +
169		(sizeof(struct cciss_scsi_cmd_stack_elem_t)*stk->top) +
170		 sizeof(CommandList_struct)); */
171	stk->top--;
172	c->cmd.ErrDesc.Addr.lower = temp64.val32.lower;
173	c->cmd.ErrDesc.Addr.upper = temp64.val32.upper;
174	c->cmd.ErrDesc.Len = sizeof(ErrorInfo_struct);
175
176	c->cmd.ctlr = h->ctlr;
177	c->cmd.err_info = &c->Err;
178
179	return (CommandList_struct *) c;
180}
181
182static void
183scsi_cmd_free(ctlr_info_t *h, CommandList_struct *cmd)
184{
185	/* assume only one process in here at a time, locking done by caller. */
186	/* use CCISS_LOCK(ctlr) */
187	/* drop the free memory chunk on top of the stack. */
188
189	struct cciss_scsi_adapter_data_t *sa;
190	struct cciss_scsi_cmd_stack_t *stk;
191
192	sa = (struct cciss_scsi_adapter_data_t *) h->scsi_ctlr;
193	stk = &sa->cmd_stack;
194	if (stk->top >= CMD_STACK_SIZE) {
195		printk("cciss: scsi_cmd_free called too many times.\n");
196		BUG();
197	}
198	stk->top++;
199	stk->elem[stk->top] = (struct cciss_scsi_cmd_stack_elem_t *) cmd;
200}
201
202static int
203scsi_cmd_stack_setup(int ctlr, struct cciss_scsi_adapter_data_t *sa)
204{
205	int i;
206	struct cciss_scsi_cmd_stack_t *stk;
207	size_t size;
208
209	stk = &sa->cmd_stack;
210	size = sizeof(struct cciss_scsi_cmd_stack_elem_t) * CMD_STACK_SIZE;
211
212	// pci_alloc_consistent guarantees 32-bit DMA address will
213	// be used
214
215	stk->pool = (struct cciss_scsi_cmd_stack_elem_t *)
216		pci_alloc_consistent(hba[ctlr]->pdev, size, &stk->cmd_pool_handle);
217
218	if (stk->pool == NULL) {
219		printk("stk->pool is null\n");
220		return -1;
221	}
222
223	for (i=0; i<CMD_STACK_SIZE; i++) {
224		stk->elem[i] = &stk->pool[i];
225		stk->elem[i]->busaddr = (__u32) (stk->cmd_pool_handle +
226			(sizeof(struct cciss_scsi_cmd_stack_elem_t) * i));
227	}
228	stk->top = CMD_STACK_SIZE-1;
229	return 0;
230}
231
232static void
233scsi_cmd_stack_free(int ctlr)
234{
235	struct cciss_scsi_adapter_data_t *sa;
236	struct cciss_scsi_cmd_stack_t *stk;
237	size_t size;
238
239	sa = (struct cciss_scsi_adapter_data_t *) hba[ctlr]->scsi_ctlr;
240	stk = &sa->cmd_stack;
241	if (stk->top != CMD_STACK_SIZE-1) {
242		printk( "cciss: %d scsi commands are still outstanding.\n",
243			CMD_STACK_SIZE - stk->top);
244		// BUG();
245		printk("WE HAVE A BUG HERE!!! stk=0x%p\n", stk);
246	}
247	size = sizeof(struct cciss_scsi_cmd_stack_elem_t) * CMD_STACK_SIZE;
248
249	pci_free_consistent(hba[ctlr]->pdev, size, stk->pool, stk->cmd_pool_handle);
250	stk->pool = NULL;
251}
252
253
254static int
255find_bus_target_lun(int ctlr, int *bus, int *target, int *lun)
256{
257	/* finds an unused bus, target, lun for a new device */
258	/* assumes hba[ctlr]->scsi_ctlr->lock is held */
259	int i, found=0;
260	unsigned char target_taken[CCISS_MAX_SCSI_DEVS_PER_HBA];
261
262	memset(&target_taken[0], 0, CCISS_MAX_SCSI_DEVS_PER_HBA);
263
264	target_taken[SELF_SCSI_ID] = 1;
265	for (i=0;i<ccissscsi[ctlr].ndevices;i++)
266		target_taken[ccissscsi[ctlr].dev[i].target] = 1;
267
268	for (i=0;i<CCISS_MAX_SCSI_DEVS_PER_HBA;i++) {
269		if (!target_taken[i]) {
270			*bus = 0; *target=i; *lun = 0; found=1;
271			break;
272		}
273	}
274	return (!found);
275}
276
277static int
278cciss_scsi_add_entry(int ctlr, int hostno,
279		unsigned char *scsi3addr, int devtype)
280{
281	/* assumes hba[ctlr]->scsi_ctlr->lock is held */
282	int n = ccissscsi[ctlr].ndevices;
283	struct cciss_scsi_dev_t *sd;
284
285	if (n >= CCISS_MAX_SCSI_DEVS_PER_HBA) {
286		printk("cciss%d: Too many devices, "
287			"some will be inaccessible.\n", ctlr);
288		return -1;
289	}
290	sd = &ccissscsi[ctlr].dev[n];
291	if (find_bus_target_lun(ctlr, &sd->bus, &sd->target, &sd->lun) != 0)
292		return -1;
293	memcpy(&sd->scsi3addr[0], scsi3addr, 8);
294	sd->devtype = devtype;
295	ccissscsi[ctlr].ndevices++;
296
297	/* initially, (before registering with scsi layer) we don't
298	   know our hostno and we don't want to print anything first
299	   time anyway (the scsi layer's inquiries will show that info) */
300	if (hostno != -1)
301		printk("cciss%d: %s device c%db%dt%dl%d added.\n",
302			ctlr, scsi_device_type(sd->devtype), hostno,
303			sd->bus, sd->target, sd->lun);
304	return 0;
305}
306
307static void
308cciss_scsi_remove_entry(int ctlr, int hostno, int entry)
309{
310	/* assumes hba[ctlr]->scsi_ctlr->lock is held */
311	int i;
312	struct cciss_scsi_dev_t sd;
313
314	if (entry < 0 || entry >= CCISS_MAX_SCSI_DEVS_PER_HBA) return;
315	sd = ccissscsi[ctlr].dev[entry];
316	for (i=entry;i<ccissscsi[ctlr].ndevices-1;i++)
317		ccissscsi[ctlr].dev[i] = ccissscsi[ctlr].dev[i+1];
318	ccissscsi[ctlr].ndevices--;
319	printk("cciss%d: %s device c%db%dt%dl%d removed.\n",
320		ctlr, scsi_device_type(sd.devtype), hostno,
321			sd.bus, sd.target, sd.lun);
322}
323
324
325#define SCSI3ADDR_EQ(a,b) ( \
326	(a)[7] == (b)[7] && \
327	(a)[6] == (b)[6] && \
328	(a)[5] == (b)[5] && \
329	(a)[4] == (b)[4] && \
330	(a)[3] == (b)[3] && \
331	(a)[2] == (b)[2] && \
332	(a)[1] == (b)[1] && \
333	(a)[0] == (b)[0])
334
335static int
336adjust_cciss_scsi_table(int ctlr, int hostno,
337	struct cciss_scsi_dev_t sd[], int nsds)
338{
339	/* sd contains scsi3 addresses and devtypes, but
340	   bus target and lun are not filled in.  This funciton
341	   takes what's in sd to be the current and adjusts
342	   ccissscsi[] to be in line with what's in sd. */
343
344	int i,j, found, changes=0;
345	struct cciss_scsi_dev_t *csd;
346	unsigned long flags;
347
348	CPQ_TAPE_LOCK(ctlr, flags);
349
350	/* find any devices in ccissscsi[] that are not in
351	   sd[] and remove them from ccissscsi[] */
352
353	i = 0;
354	while(i<ccissscsi[ctlr].ndevices) {
355		csd = &ccissscsi[ctlr].dev[i];
356		found=0;
357		for (j=0;j<nsds;j++) {
358			if (SCSI3ADDR_EQ(sd[j].scsi3addr,
359				csd->scsi3addr)) {
360				if (sd[j].devtype == csd->devtype)
361					found=2;
362				else
363					found=1;
364				break;
365			}
366		}
367
368		if (found == 0) { /* device no longer present. */
369			changes++;
370			/* printk("cciss%d: %s device c%db%dt%dl%d removed.\n",
371				ctlr, scsi_device_type(csd->devtype), hostno,
372					csd->bus, csd->target, csd->lun); */
373			cciss_scsi_remove_entry(ctlr, hostno, i);
374			/* note, i not incremented */
375		}
376		else if (found == 1) { /* device is different kind */
377			changes++;
378			printk("cciss%d: device c%db%dt%dl%d type changed "
379				"(device type now %s).\n",
380				ctlr, hostno, csd->bus, csd->target, csd->lun,
381					scsi_device_type(csd->devtype));
382			csd->devtype = sd[j].devtype;
383			i++;	/* so just move along. */
384		} else 		/* device is same as it ever was, */
385			i++;	/* so just move along. */
386	}
387
388	/* Now, make sure every device listed in sd[] is also
389 	   listed in ccissscsi[], adding them if they aren't found */
390
391	for (i=0;i<nsds;i++) {
392		found=0;
393		for (j=0;j<ccissscsi[ctlr].ndevices;j++) {
394			csd = &ccissscsi[ctlr].dev[j];
395			if (SCSI3ADDR_EQ(sd[i].scsi3addr,
396				csd->scsi3addr)) {
397				if (sd[i].devtype == csd->devtype)
398					found=2;	/* found device */
399				else
400					found=1; 	/* found a bug. */
401				break;
402			}
403		}
404		if (!found) {
405			changes++;
406			if (cciss_scsi_add_entry(ctlr, hostno,
407				&sd[i].scsi3addr[0], sd[i].devtype) != 0)
408				break;
409		} else if (found == 1) {
410			/* should never happen... */
411			changes++;
412			printk("cciss%d: device unexpectedly changed type\n",
413				ctlr);
414			/* but if it does happen, we just ignore that device */
415		}
416	}
417	CPQ_TAPE_UNLOCK(ctlr, flags);
418
419	if (!changes)
420		printk("cciss%d: No device changes detected.\n", ctlr);
421
422	return 0;
423}
424
425static int
426lookup_scsi3addr(int ctlr, int bus, int target, int lun, char *scsi3addr)
427{
428	int i;
429	struct cciss_scsi_dev_t *sd;
430	unsigned long flags;
431
432	CPQ_TAPE_LOCK(ctlr, flags);
433	for (i=0;i<ccissscsi[ctlr].ndevices;i++) {
434		sd = &ccissscsi[ctlr].dev[i];
435		if (sd->bus == bus &&
436		    sd->target == target &&
437		    sd->lun == lun) {
438			memcpy(scsi3addr, &sd->scsi3addr[0], 8);
439			CPQ_TAPE_UNLOCK(ctlr, flags);
440			return 0;
441		}
442	}
443	CPQ_TAPE_UNLOCK(ctlr, flags);
444	return -1;
445}
446
447static void
448cciss_scsi_setup(int cntl_num)
449{
450	struct cciss_scsi_adapter_data_t * shba;
451
452	ccissscsi[cntl_num].ndevices = 0;
453	shba = (struct cciss_scsi_adapter_data_t *)
454		kmalloc(sizeof(*shba), GFP_KERNEL);
455	if (shba == NULL)
456		return;
457	shba->scsi_host = NULL;
458	spin_lock_init(&shba->lock);
459	shba->registered = 0;
460	if (scsi_cmd_stack_setup(cntl_num, shba) != 0) {
461		kfree(shba);
462		shba = NULL;
463	}
464	hba[cntl_num]->scsi_ctlr = (void *) shba;
465	return;
466}
467
468static void
469complete_scsi_command( CommandList_struct *cp, int timeout, __u32 tag)
470{
471	struct scsi_cmnd *cmd;
472	ctlr_info_t *ctlr;
473	u64bit addr64;
474	ErrorInfo_struct *ei;
475
476	ei = cp->err_info;
477
478	/* First, see if it was a message rather than a command */
479	if (cp->Request.Type.Type == TYPE_MSG)  {
480		cp->cmd_type = CMD_MSG_DONE;
481		return;
482	}
483
484	cmd = (struct scsi_cmnd *) cp->scsi_cmd;
485	ctlr = hba[cp->ctlr];
486
487	/* undo the DMA mappings */
488
489	if (cmd->use_sg) {
490		pci_unmap_sg(ctlr->pdev,
491			cmd->request_buffer, cmd->use_sg,
492				cmd->sc_data_direction);
493	}
494	else if (cmd->request_bufflen) {
495		addr64.val32.lower = cp->SG[0].Addr.lower;
496                addr64.val32.upper = cp->SG[0].Addr.upper;
497                pci_unmap_single(ctlr->pdev, (dma_addr_t) addr64.val,
498                	cmd->request_bufflen,
499				cmd->sc_data_direction);
500	}
501
502	cmd->result = (DID_OK << 16); 		/* host byte */
503	cmd->result |= (COMMAND_COMPLETE << 8);	/* msg byte */
504	/* cmd->result |= (GOOD < 1); */		/* status byte */
505
506	cmd->result |= (ei->ScsiStatus);
507	/* printk("Scsistatus is 0x%02x\n", ei->ScsiStatus);  */
508
509	/* copy the sense data whether we need to or not. */
510
511	memcpy(cmd->sense_buffer, ei->SenseInfo,
512		ei->SenseLen > SCSI_SENSE_BUFFERSIZE ?
513			SCSI_SENSE_BUFFERSIZE :
514			ei->SenseLen);
515	cmd->resid = ei->ResidualCnt;
516
517	if(ei->CommandStatus != 0)
518	{ /* an error has occurred */
519		switch(ei->CommandStatus)
520		{
521			case CMD_TARGET_STATUS:
522				/* Pass it up to the upper layers... */
523				if( ei->ScsiStatus)
524                		{
525					cmd->result |= (ei->ScsiStatus < 1);
526                		}
527				else {  /* scsi status is zero??? How??? */
528
529	/* Ordinarily, this case should never happen, but there is a bug
530	   in some released firmware revisions that allows it to happen
531	   if, for example, a 4100 backplane loses power and the tape
532	   drive is in it.  We assume that it's a fatal error of some
533	   kind because we can't show that it wasn't. We will make it
534	   look like selection timeout since that is the most common
535	   reason for this to occur, and it's severe enough. */
536
537					cmd->result = DID_NO_CONNECT << 16;
538				}
539			break;
540			case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
541			break;
542			case CMD_DATA_OVERRUN:
543				printk(KERN_WARNING "cciss: cp %p has"
544					" completed with data overrun "
545					"reported\n", cp);
546			break;
547			case CMD_INVALID: {
548				/* print_bytes(cp, sizeof(*cp), 1, 0);
549				print_cmd(cp); */
550     /* We get CMD_INVALID if you address a non-existent tape drive instead
551	of a selection timeout (no response).  You will see this if you yank
552	out a tape drive, then try to access it. This is kind of a shame
553	because it means that any other CMD_INVALID (e.g. driver bug) will
554	get interpreted as a missing target. */
555				cmd->result = DID_NO_CONNECT << 16;
556				}
557			break;
558			case CMD_PROTOCOL_ERR:
559                                printk(KERN_WARNING "cciss: cp %p has "
560					"protocol error \n", cp);
561                        break;
562			case CMD_HARDWARE_ERR:
563				cmd->result = DID_ERROR << 16;
564                                printk(KERN_WARNING "cciss: cp %p had "
565                                        " hardware error\n", cp);
566                        break;
567			case CMD_CONNECTION_LOST:
568				cmd->result = DID_ERROR << 16;
569				printk(KERN_WARNING "cciss: cp %p had "
570					"connection lost\n", cp);
571			break;
572			case CMD_ABORTED:
573				cmd->result = DID_ABORT << 16;
574				printk(KERN_WARNING "cciss: cp %p was "
575					"aborted\n", cp);
576			break;
577			case CMD_ABORT_FAILED:
578				cmd->result = DID_ERROR << 16;
579				printk(KERN_WARNING "cciss: cp %p reports "
580					"abort failed\n", cp);
581			break;
582			case CMD_UNSOLICITED_ABORT:
583				cmd->result = DID_ABORT << 16;
584				printk(KERN_WARNING "cciss: cp %p aborted "
585					"do to an unsolicited abort\n", cp);
586			break;
587			case CMD_TIMEOUT:
588				cmd->result = DID_TIME_OUT << 16;
589				printk(KERN_WARNING "cciss: cp %p timedout\n",
590					cp);
591			break;
592			default:
593				cmd->result = DID_ERROR << 16;
594				printk(KERN_WARNING "cciss: cp %p returned "
595					"unknown status %x\n", cp,
596						ei->CommandStatus);
597		}
598	}
599	// printk("c:%p:c%db%dt%dl%d ", cmd, ctlr->ctlr, cmd->channel,
600	//	cmd->target, cmd->lun);
601	cmd->scsi_done(cmd);
602	scsi_cmd_free(ctlr, cp);
603}
604
605static int
606cciss_scsi_detect(int ctlr)
607{
608	struct Scsi_Host *sh;
609	int error;
610
611	sh = scsi_host_alloc(&cciss_driver_template, sizeof(struct ctlr_info *));
612	if (sh == NULL)
613		goto fail;
614	sh->io_port = 0;
615	sh->n_io_port = 0;	// I don't think we use these two...
616	sh->this_id = SELF_SCSI_ID;
617
618	((struct cciss_scsi_adapter_data_t *)
619		hba[ctlr]->scsi_ctlr)->scsi_host = (void *) sh;
620	sh->hostdata[0] = (unsigned long) hba[ctlr];
621	sh->irq = hba[ctlr]->intr[SIMPLE_MODE_INT];
622	sh->unique_id = sh->irq;
623	error = scsi_add_host(sh, &hba[ctlr]->pdev->dev);
624	if (error)
625		goto fail_host_put;
626	scsi_scan_host(sh);
627	return 1;
628
629 fail_host_put:
630	scsi_host_put(sh);
631 fail:
632	return 0;
633}
634
635static void
636cciss_unmap_one(struct pci_dev *pdev,
637		CommandList_struct *cp,
638		size_t buflen,
639		int data_direction)
640{
641	u64bit addr64;
642
643	addr64.val32.lower = cp->SG[0].Addr.lower;
644	addr64.val32.upper = cp->SG[0].Addr.upper;
645	pci_unmap_single(pdev, (dma_addr_t) addr64.val, buflen, data_direction);
646}
647
648static void
649cciss_map_one(struct pci_dev *pdev,
650		CommandList_struct *cp,
651		unsigned char *buf,
652		size_t buflen,
653		int data_direction)
654{
655	__u64 addr64;
656
657	addr64 = (__u64) pci_map_single(pdev, buf, buflen, data_direction);
658	cp->SG[0].Addr.lower =
659	  (__u32) (addr64 & (__u64) 0x00000000FFFFFFFF);
660	cp->SG[0].Addr.upper =
661	  (__u32) ((addr64 >> 32) & (__u64) 0x00000000FFFFFFFF);
662	cp->SG[0].Len = buflen;
663	cp->Header.SGList = (__u8) 1;   /* no. SGs contig in this cmd */
664	cp->Header.SGTotal = (__u16) 1; /* total sgs in this cmd list */
665}
666
667static int
668cciss_scsi_do_simple_cmd(ctlr_info_t *c,
669			CommandList_struct *cp,
670			unsigned char *scsi3addr,
671			unsigned char *cdb,
672			unsigned char cdblen,
673			unsigned char *buf, int bufsize,
674			int direction)
675{
676	unsigned long flags;
677	DECLARE_COMPLETION_ONSTACK(wait);
678
679	cp->cmd_type = CMD_IOCTL_PEND;		// treat this like an ioctl
680	cp->scsi_cmd = NULL;
681	cp->Header.ReplyQueue = 0;  // unused in simple mode
682	memcpy(&cp->Header.LUN, scsi3addr, sizeof(cp->Header.LUN));
683	cp->Header.Tag.lower = cp->busaddr;  // Use k. address of cmd as tag
684	// Fill in the request block...
685
686	/* printk("Using scsi3addr 0x%02x%0x2%0x2%0x2%0x2%0x2%0x2%0x2\n",
687		scsi3addr[0], scsi3addr[1], scsi3addr[2], scsi3addr[3],
688		scsi3addr[4], scsi3addr[5], scsi3addr[6], scsi3addr[7]); */
689
690	memset(cp->Request.CDB, 0, sizeof(cp->Request.CDB));
691	memcpy(cp->Request.CDB, cdb, cdblen);
692	cp->Request.Timeout = 0;
693	cp->Request.CDBLen = cdblen;
694	cp->Request.Type.Type = TYPE_CMD;
695	cp->Request.Type.Attribute = ATTR_SIMPLE;
696	cp->Request.Type.Direction = direction;
697
698	/* Fill in the SG list and do dma mapping */
699	cciss_map_one(c->pdev, cp, (unsigned char *) buf,
700			bufsize, DMA_FROM_DEVICE);
701
702	cp->waiting = &wait;
703
704	/* Put the request on the tail of the request queue */
705	spin_lock_irqsave(CCISS_LOCK(c->ctlr), flags);
706	addQ(&c->reqQ, cp);
707	c->Qdepth++;
708	start_io(c);
709	spin_unlock_irqrestore(CCISS_LOCK(c->ctlr), flags);
710
711	wait_for_completion(&wait);
712
713	/* undo the dma mapping */
714	cciss_unmap_one(c->pdev, cp, bufsize, DMA_FROM_DEVICE);
715	return(0);
716}
717
718static void
719cciss_scsi_interpret_error(CommandList_struct *cp)
720{
721	ErrorInfo_struct *ei;
722
723	ei = cp->err_info;
724	switch(ei->CommandStatus)
725	{
726		case CMD_TARGET_STATUS:
727			printk(KERN_WARNING "cciss: cmd %p has "
728				"completed with errors\n", cp);
729			printk(KERN_WARNING "cciss: cmd %p "
730				"has SCSI Status = %x\n",
731					cp,
732					ei->ScsiStatus);
733			if (ei->ScsiStatus == 0)
734				printk(KERN_WARNING
735				"cciss:SCSI status is abnormally zero.  "
736				"(probably indicates selection timeout "
737				"reported incorrectly due to a known "
738				"firmware bug, circa July, 2001.)\n");
739		break;
740		case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
741			printk("UNDERRUN\n");
742		break;
743		case CMD_DATA_OVERRUN:
744			printk(KERN_WARNING "cciss: cp %p has"
745				" completed with data overrun "
746				"reported\n", cp);
747		break;
748		case CMD_INVALID: {
749			/* controller unfortunately reports SCSI passthru's */
750			/* to non-existent targets as invalid commands. */
751			printk(KERN_WARNING "cciss: cp %p is "
752				"reported invalid (probably means "
753				"target device no longer present)\n",
754				cp);
755			/* print_bytes((unsigned char *) cp, sizeof(*cp), 1, 0);
756			print_cmd(cp);  */
757			}
758		break;
759		case CMD_PROTOCOL_ERR:
760			printk(KERN_WARNING "cciss: cp %p has "
761				"protocol error \n", cp);
762		break;
763		case CMD_HARDWARE_ERR:
764			/* cmd->result = DID_ERROR << 16; */
765			printk(KERN_WARNING "cciss: cp %p had "
766				" hardware error\n", cp);
767		break;
768		case CMD_CONNECTION_LOST:
769			printk(KERN_WARNING "cciss: cp %p had "
770				"connection lost\n", cp);
771		break;
772		case CMD_ABORTED:
773			printk(KERN_WARNING "cciss: cp %p was "
774				"aborted\n", cp);
775		break;
776		case CMD_ABORT_FAILED:
777			printk(KERN_WARNING "cciss: cp %p reports "
778				"abort failed\n", cp);
779		break;
780		case CMD_UNSOLICITED_ABORT:
781			printk(KERN_WARNING "cciss: cp %p aborted "
782				"do to an unsolicited abort\n", cp);
783		break;
784		case CMD_TIMEOUT:
785			printk(KERN_WARNING "cciss: cp %p timedout\n",
786				cp);
787		break;
788		default:
789			printk(KERN_WARNING "cciss: cp %p returned "
790				"unknown status %x\n", cp,
791					ei->CommandStatus);
792	}
793}
794
795static int
796cciss_scsi_do_inquiry(ctlr_info_t *c, unsigned char *scsi3addr,
797		 unsigned char *buf, unsigned char bufsize)
798{
799	int rc;
800	CommandList_struct *cp;
801	char cdb[6];
802	ErrorInfo_struct *ei;
803	unsigned long flags;
804
805	spin_lock_irqsave(CCISS_LOCK(c->ctlr), flags);
806	cp = scsi_cmd_alloc(c);
807	spin_unlock_irqrestore(CCISS_LOCK(c->ctlr), flags);
808
809	if (cp == NULL) {			/* trouble... */
810		printk("cmd_alloc returned NULL!\n");
811		return -1;
812	}
813
814	ei = cp->err_info;
815
816	cdb[0] = CISS_INQUIRY;
817	cdb[1] = 0;
818	cdb[2] = 0;
819	cdb[3] = 0;
820	cdb[4] = bufsize;
821	cdb[5] = 0;
822	rc = cciss_scsi_do_simple_cmd(c, cp, scsi3addr, cdb,
823				6, buf, bufsize, XFER_READ);
824
825	if (rc != 0) return rc; /* something went wrong */
826
827	if (ei->CommandStatus != 0 &&
828	    ei->CommandStatus != CMD_DATA_UNDERRUN) {
829		cciss_scsi_interpret_error(cp);
830		rc = -1;
831	}
832	spin_lock_irqsave(CCISS_LOCK(c->ctlr), flags);
833	scsi_cmd_free(c, cp);
834	spin_unlock_irqrestore(CCISS_LOCK(c->ctlr), flags);
835	return rc;
836}
837
838static int
839cciss_scsi_do_report_phys_luns(ctlr_info_t *c,
840		ReportLunData_struct *buf, int bufsize)
841{
842	int rc;
843	CommandList_struct *cp;
844	unsigned char cdb[12];
845	unsigned char scsi3addr[8];
846	ErrorInfo_struct *ei;
847	unsigned long flags;
848
849	spin_lock_irqsave(CCISS_LOCK(c->ctlr), flags);
850	cp = scsi_cmd_alloc(c);
851	spin_unlock_irqrestore(CCISS_LOCK(c->ctlr), flags);
852	if (cp == NULL) {			/* trouble... */
853		printk("cmd_alloc returned NULL!\n");
854		return -1;
855	}
856
857	memset(&scsi3addr[0], 0, 8); /* address the controller */
858	cdb[0] = CISS_REPORT_PHYS;
859	cdb[1] = 0;
860	cdb[2] = 0;
861	cdb[3] = 0;
862	cdb[4] = 0;
863	cdb[5] = 0;
864	cdb[6] = (bufsize >> 24) & 0xFF;  //MSB
865	cdb[7] = (bufsize >> 16) & 0xFF;
866	cdb[8] = (bufsize >> 8) & 0xFF;
867	cdb[9] = bufsize & 0xFF;
868	cdb[10] = 0;
869	cdb[11] = 0;
870
871	rc = cciss_scsi_do_simple_cmd(c, cp, scsi3addr,
872				cdb, 12,
873				(unsigned char *) buf,
874				bufsize, XFER_READ);
875
876	if (rc != 0) return rc; /* something went wrong */
877
878	ei = cp->err_info;
879	if (ei->CommandStatus != 0 &&
880	    ei->CommandStatus != CMD_DATA_UNDERRUN) {
881		cciss_scsi_interpret_error(cp);
882		rc = -1;
883	}
884	spin_lock_irqsave(CCISS_LOCK(c->ctlr), flags);
885	scsi_cmd_free(c, cp);
886	spin_unlock_irqrestore(CCISS_LOCK(c->ctlr), flags);
887	return rc;
888}
889
890static void
891cciss_update_non_disk_devices(int cntl_num, int hostno)
892{
893	/* the idea here is we could get notified from /proc
894	   that some devices have changed, so we do a report
895	   physical luns cmd, and adjust our list of devices
896	   accordingly.  (We can't rely on the scsi-mid layer just
897	   doing inquiries, because the "busses" that the scsi
898	   mid-layer probes are totally fabricated by this driver,
899	   so new devices wouldn't show up.
900
901	   the scsi3addr's of devices won't change so long as the
902	   adapter is not reset.  That means we can rescan and
903	   tell which devices we already know about, vs. new
904	   devices, vs.  disappearing devices.
905
906	   Also, if you yank out a tape drive, then put in a disk
907	   in it's place, (say, a configured volume from another
908	   array controller for instance)  _don't_ poke this driver
909           (so it thinks it's still a tape, but _do_ poke the scsi
910           mid layer, so it does an inquiry... the scsi mid layer
911           will see the physical disk.  This would be bad.  Need to
912	   think about how to prevent that.  One idea would be to
913	   snoop all scsi responses and if an inquiry repsonse comes
914	   back that reports a disk, chuck it an return selection
915	   timeout instead and adjust our table...  Not sure i like
916	   that though.
917
918	 */
919#define OBDR_TAPE_INQ_SIZE 49
920#define OBDR_TAPE_SIG "$DR-10"
921	ReportLunData_struct *ld_buff;
922	unsigned char *inq_buff;
923	unsigned char scsi3addr[8];
924	ctlr_info_t *c;
925	__u32 num_luns=0;
926	unsigned char *ch;
927	/* unsigned char found[CCISS_MAX_SCSI_DEVS_PER_HBA]; */
928	struct cciss_scsi_dev_t currentsd[CCISS_MAX_SCSI_DEVS_PER_HBA];
929	int ncurrent=0;
930	int reportlunsize = sizeof(*ld_buff) + CISS_MAX_PHYS_LUN * 8;
931	int i;
932
933	c = (ctlr_info_t *) hba[cntl_num];
934	ld_buff = kzalloc(reportlunsize, GFP_KERNEL);
935	if (ld_buff == NULL) {
936		printk(KERN_ERR "cciss: out of memory\n");
937		return;
938	}
939	inq_buff = kmalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
940        if (inq_buff == NULL) {
941                printk(KERN_ERR "cciss: out of memory\n");
942                kfree(ld_buff);
943                return;
944	}
945
946	if (cciss_scsi_do_report_phys_luns(c, ld_buff, reportlunsize) == 0) {
947		ch = &ld_buff->LUNListLength[0];
948		num_luns = ((ch[0]<<24) | (ch[1]<<16) | (ch[2]<<8) | ch[3]) / 8;
949		if (num_luns > CISS_MAX_PHYS_LUN) {
950			printk(KERN_WARNING
951				"cciss: Maximum physical LUNs (%d) exceeded.  "
952				"%d LUNs ignored.\n", CISS_MAX_PHYS_LUN,
953				num_luns - CISS_MAX_PHYS_LUN);
954			num_luns = CISS_MAX_PHYS_LUN;
955		}
956	}
957	else {
958		printk(KERN_ERR  "cciss: Report physical LUNs failed.\n");
959		goto out;
960	}
961
962
963	/* adjust our table of devices */
964	for(i=0; i<num_luns; i++)
965	{
966		int devtype;
967
968		/* for each physical lun, do an inquiry */
969		if (ld_buff->LUN[i][3] & 0xC0) continue;
970		memset(inq_buff, 0, OBDR_TAPE_INQ_SIZE);
971		memcpy(&scsi3addr[0], &ld_buff->LUN[i][0], 8);
972
973		if (cciss_scsi_do_inquiry(hba[cntl_num], scsi3addr, inq_buff,
974			(unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
975			/* Inquiry failed (msg printed already) */
976			devtype = 0; /* so we will skip this device. */
977		} else /* what kind of device is this? */
978			devtype = (inq_buff[0] & 0x1f);
979
980		switch (devtype)
981		{
982		  case 0x05: /* CD-ROM */ {
983
984			/* We don't *really* support actual CD-ROM devices,
985			 * just this "One Button Disaster Recovery" tape drive
986			 * which temporarily pretends to be a CD-ROM drive.
987			 * So we check that the device is really an OBDR tape
988			 * device by checking for "$DR-10" in bytes 43-48 of
989			 * the inquiry data.
990			 */
991				char obdr_sig[7];
992
993				strncpy(obdr_sig, &inq_buff[43], 6);
994				obdr_sig[6] = '\0';
995				if (strncmp(obdr_sig, OBDR_TAPE_SIG, 6) != 0)
996					/* Not OBDR device, ignore it. */
997					break;
998			}
999			/* fall through . . . */
1000		  case 0x01: /* sequential access, (tape) */
1001		  case 0x08: /* medium changer */
1002			if (ncurrent >= CCISS_MAX_SCSI_DEVS_PER_HBA) {
1003				printk(KERN_INFO "cciss%d: %s ignored, "
1004					"too many devices.\n", cntl_num,
1005					scsi_device_type(devtype));
1006				break;
1007			}
1008			memcpy(&currentsd[ncurrent].scsi3addr[0],
1009				&scsi3addr[0], 8);
1010			currentsd[ncurrent].devtype = devtype;
1011			currentsd[ncurrent].bus = -1;
1012			currentsd[ncurrent].target = -1;
1013			currentsd[ncurrent].lun = -1;
1014			ncurrent++;
1015			break;
1016		  default:
1017			break;
1018		}
1019	}
1020
1021	adjust_cciss_scsi_table(cntl_num, hostno, currentsd, ncurrent);
1022out:
1023	kfree(inq_buff);
1024	kfree(ld_buff);
1025	return;
1026}
1027
1028static int
1029is_keyword(char *ptr, int len, char *verb)  // Thanks to ncr53c8xx.c
1030{
1031	int verb_len = strlen(verb);
1032	if (len >= verb_len && !memcmp(verb,ptr,verb_len))
1033		return verb_len;
1034	else
1035		return 0;
1036}
1037
1038static int
1039cciss_scsi_user_command(int ctlr, int hostno, char *buffer, int length)
1040{
1041	int arg_len;
1042
1043	if ((arg_len = is_keyword(buffer, length, "rescan")) != 0)
1044		cciss_update_non_disk_devices(ctlr, hostno);
1045	else
1046		return -EINVAL;
1047	return length;
1048}
1049
1050
1051static int
1052cciss_scsi_proc_info(struct Scsi_Host *sh,
1053		char *buffer, /* data buffer */
1054		char **start, 	   /* where data in buffer starts */
1055		off_t offset,	   /* offset from start of imaginary file */
1056		int length, 	   /* length of data in buffer */
1057		int func)	   /* 0 == read, 1 == write */
1058{
1059
1060	int buflen, datalen;
1061	ctlr_info_t *ci;
1062	int i;
1063	int cntl_num;
1064
1065
1066	ci = (ctlr_info_t *) sh->hostdata[0];
1067	if (ci == NULL)  /* This really shouldn't ever happen. */
1068		return -EINVAL;
1069
1070	cntl_num = ci->ctlr;	/* Get our index into the hba[] array */
1071
1072	if (func == 0) {	/* User is reading from /proc/scsi/ciss*?/?*  */
1073		buflen = sprintf(buffer, "cciss%d: SCSI host: %d\n",
1074				cntl_num, sh->host_no);
1075
1076		/* this information is needed by apps to know which cciss
1077		   device corresponds to which scsi host number without
1078		   having to open a scsi target device node.  The device
1079		   information is not a duplicate of /proc/scsi/scsi because
1080		   the two may be out of sync due to scsi hotplug, rather
1081		   this info is for an app to be able to use to know how to
1082		   get them back in sync. */
1083
1084		for (i=0;i<ccissscsi[cntl_num].ndevices;i++) {
1085			struct cciss_scsi_dev_t *sd = &ccissscsi[cntl_num].dev[i];
1086			buflen += sprintf(&buffer[buflen], "c%db%dt%dl%d %02d "
1087				"0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
1088				sh->host_no, sd->bus, sd->target, sd->lun,
1089				sd->devtype,
1090				sd->scsi3addr[0], sd->scsi3addr[1],
1091				sd->scsi3addr[2], sd->scsi3addr[3],
1092				sd->scsi3addr[4], sd->scsi3addr[5],
1093				sd->scsi3addr[6], sd->scsi3addr[7]);
1094		}
1095		datalen = buflen - offset;
1096		if (datalen < 0) { 	/* they're reading past EOF. */
1097			datalen = 0;
1098			*start = buffer+buflen;
1099		} else
1100			*start = buffer + offset;
1101		return(datalen);
1102	} else 	/* User is writing to /proc/scsi/cciss*?/?*  ... */
1103		return cciss_scsi_user_command(cntl_num, sh->host_no,
1104			buffer, length);
1105}
1106
1107/* cciss_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
1108   dma mapping  and fills in the scatter gather entries of the
1109   cciss command, cp. */
1110
1111static void
1112cciss_scatter_gather(struct pci_dev *pdev,
1113		CommandList_struct *cp,
1114		struct scsi_cmnd *cmd)
1115{
1116	unsigned int use_sg, nsegs=0, len;
1117	struct scatterlist *scatter = (struct scatterlist *) cmd->request_buffer;
1118	__u64 addr64;
1119
1120	/* is it just one virtual address? */
1121	if (!cmd->use_sg) {
1122		if (cmd->request_bufflen) {	/* anything to xfer? */
1123
1124			addr64 = (__u64) pci_map_single(pdev,
1125				cmd->request_buffer,
1126				cmd->request_bufflen,
1127				cmd->sc_data_direction);
1128
1129			cp->SG[0].Addr.lower =
1130			  (__u32) (addr64 & (__u64) 0x00000000FFFFFFFF);
1131			cp->SG[0].Addr.upper =
1132			  (__u32) ((addr64 >> 32) & (__u64) 0x00000000FFFFFFFF);
1133			cp->SG[0].Len = cmd->request_bufflen;
1134			nsegs=1;
1135		}
1136	} /* else, must be a list of virtual addresses.... */
1137	else if (cmd->use_sg <= MAXSGENTRIES) {	/* not too many addrs? */
1138
1139		use_sg = pci_map_sg(pdev, cmd->request_buffer, cmd->use_sg,
1140			cmd->sc_data_direction);
1141
1142		for (nsegs=0; nsegs < use_sg; nsegs++) {
1143			addr64 = (__u64) sg_dma_address(&scatter[nsegs]);
1144			len  = sg_dma_len(&scatter[nsegs]);
1145			cp->SG[nsegs].Addr.lower =
1146			  (__u32) (addr64 & (__u64) 0x00000000FFFFFFFF);
1147			cp->SG[nsegs].Addr.upper =
1148			  (__u32) ((addr64 >> 32) & (__u64) 0x00000000FFFFFFFF);
1149			cp->SG[nsegs].Len = len;
1150			cp->SG[nsegs].Ext = 0;  // we are not chaining
1151		}
1152	} else BUG();
1153
1154	cp->Header.SGList = (__u8) nsegs;   /* no. SGs contig in this cmd */
1155	cp->Header.SGTotal = (__u16) nsegs; /* total sgs in this cmd list */
1156	return;
1157}
1158
1159
1160static int
1161cciss_scsi_queue_command (struct scsi_cmnd *cmd, void (* done)(struct scsi_cmnd *))
1162{
1163	ctlr_info_t **c;
1164	int ctlr, rc;
1165	unsigned char scsi3addr[8];
1166	CommandList_struct *cp;
1167	unsigned long flags;
1168
1169	// Get the ptr to our adapter structure (hba[i]) out of cmd->host.
1170	// We violate cmd->host privacy here.  (Is there another way?)
1171	c = (ctlr_info_t **) &cmd->device->host->hostdata[0];
1172	ctlr = (*c)->ctlr;
1173
1174	rc = lookup_scsi3addr(ctlr, cmd->device->channel, cmd->device->id,
1175			cmd->device->lun, scsi3addr);
1176	if (rc != 0) {
1177		/* the scsi nexus does not match any that we presented... */
1178		/* pretend to mid layer that we got selection timeout */
1179		cmd->result = DID_NO_CONNECT << 16;
1180		done(cmd);
1181		/* we might want to think about registering controller itself
1182		   as a processor device on the bus so sg binds to it. */
1183		return 0;
1184	}
1185
1186	/* printk("cciss_queue_command, p=%p, cmd=0x%02x, c%db%dt%dl%d\n",
1187		cmd, cmd->cmnd[0], ctlr, cmd->channel, cmd->target, cmd->lun);*/
1188	// printk("q:%p:c%db%dt%dl%d ", cmd, ctlr, cmd->channel,
1189	//	cmd->target, cmd->lun);
1190
1191	/* Ok, we have a reasonable scsi nexus, so send the cmd down, and
1192           see what the device thinks of it. */
1193
1194	spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1195	cp = scsi_cmd_alloc(*c);
1196	spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1197	if (cp == NULL) {			/* trouble... */
1198		printk("scsi_cmd_alloc returned NULL!\n");
1199		cmd->result = DID_NO_CONNECT << 16;
1200		done(cmd);
1201		return 0;
1202	}
1203
1204	// Fill in the command list header
1205
1206	cmd->scsi_done = done;    // save this for use by completion code
1207
1208	// save cp in case we have to abort it
1209	cmd->host_scribble = (unsigned char *) cp;
1210
1211	cp->cmd_type = CMD_SCSI;
1212	cp->scsi_cmd = cmd;
1213	cp->Header.ReplyQueue = 0;  // unused in simple mode
1214	memcpy(&cp->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
1215	cp->Header.Tag.lower = cp->busaddr;  // Use k. address of cmd as tag
1216
1217	// Fill in the request block...
1218
1219	cp->Request.Timeout = 0;
1220	memset(cp->Request.CDB, 0, sizeof(cp->Request.CDB));
1221	BUG_ON(cmd->cmd_len > sizeof(cp->Request.CDB));
1222	cp->Request.CDBLen = cmd->cmd_len;
1223	memcpy(cp->Request.CDB, cmd->cmnd, cmd->cmd_len);
1224	cp->Request.Type.Type = TYPE_CMD;
1225	cp->Request.Type.Attribute = ATTR_SIMPLE;
1226	switch(cmd->sc_data_direction)
1227	{
1228	  case DMA_TO_DEVICE: cp->Request.Type.Direction = XFER_WRITE; break;
1229	  case DMA_FROM_DEVICE: cp->Request.Type.Direction = XFER_READ; break;
1230	  case DMA_NONE: cp->Request.Type.Direction = XFER_NONE; break;
1231	  case DMA_BIDIRECTIONAL:
1232		// This can happen if a buggy application does a scsi passthru
1233		// and sets both inlen and outlen to non-zero. ( see
1234		// ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
1235
1236	  	cp->Request.Type.Direction = XFER_RSVD;
1237		// This is technically wrong, and cciss controllers should
1238		// reject it with CMD_INVALID, which is the most correct
1239		// response, but non-fibre backends appear to let it
1240		// slide by, and give the same results as if this field
1241		// were set correctly.  Either way is acceptable for
1242		// our purposes here.
1243
1244		break;
1245
1246	  default:
1247		printk("cciss: unknown data direction: %d\n",
1248			cmd->sc_data_direction);
1249		BUG();
1250		break;
1251	}
1252
1253	cciss_scatter_gather((*c)->pdev, cp, cmd); // Fill the SG list
1254
1255	/* Put the request on the tail of the request queue */
1256
1257	spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1258	addQ(&(*c)->reqQ, cp);
1259	(*c)->Qdepth++;
1260	start_io(*c);
1261	spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1262
1263	/* the cmd'll come back via intr handler in complete_scsi_command()  */
1264	return 0;
1265}
1266
1267static void
1268cciss_unregister_scsi(int ctlr)
1269{
1270	struct cciss_scsi_adapter_data_t *sa;
1271	struct cciss_scsi_cmd_stack_t *stk;
1272	unsigned long flags;
1273
1274	/* we are being forcibly unloaded, and may not refuse. */
1275
1276	spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1277	sa = (struct cciss_scsi_adapter_data_t *) hba[ctlr]->scsi_ctlr;
1278	stk = &sa->cmd_stack;
1279
1280	/* if we weren't ever actually registered, don't unregister */
1281	if (sa->registered) {
1282		spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1283		scsi_remove_host(sa->scsi_host);
1284		scsi_host_put(sa->scsi_host);
1285		spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1286	}
1287
1288	/* set scsi_host to NULL so our detect routine will
1289	   find us on register */
1290	sa->scsi_host = NULL;
1291	scsi_cmd_stack_free(ctlr);
1292	kfree(sa);
1293	spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1294}
1295
1296static int
1297cciss_register_scsi(int ctlr)
1298{
1299	unsigned long flags;
1300
1301	CPQ_TAPE_LOCK(ctlr, flags);
1302
1303	/* Since this is really a block driver, the SCSI core may not be
1304	   initialized at init time, in which case, calling scsi_register_host
1305	   would hang.  Instead, we do it later, via /proc filesystem
1306	   and rc scripts, when we know SCSI core is good to go. */
1307
1308	/* Only register if SCSI devices are detected. */
1309	if (ccissscsi[ctlr].ndevices != 0) {
1310		((struct cciss_scsi_adapter_data_t *)
1311			hba[ctlr]->scsi_ctlr)->registered = 1;
1312		CPQ_TAPE_UNLOCK(ctlr, flags);
1313		return cciss_scsi_detect(ctlr);
1314	}
1315	CPQ_TAPE_UNLOCK(ctlr, flags);
1316	printk(KERN_INFO
1317		"cciss%d: No appropriate SCSI device detected, "
1318		"SCSI subsystem not engaged.\n", ctlr);
1319	return 0;
1320}
1321
1322static int
1323cciss_engage_scsi(int ctlr)
1324{
1325	struct cciss_scsi_adapter_data_t *sa;
1326	struct cciss_scsi_cmd_stack_t *stk;
1327	unsigned long flags;
1328
1329	spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1330	sa = (struct cciss_scsi_adapter_data_t *) hba[ctlr]->scsi_ctlr;
1331	stk = &sa->cmd_stack;
1332
1333	if (((struct cciss_scsi_adapter_data_t *)
1334		hba[ctlr]->scsi_ctlr)->registered) {
1335		printk("cciss%d: SCSI subsystem already engaged.\n", ctlr);
1336		spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1337		return ENXIO;
1338	}
1339	spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1340	cciss_update_non_disk_devices(ctlr, -1);
1341	cciss_register_scsi(ctlr);
1342	return 0;
1343}
1344
1345static void
1346cciss_proc_tape_report(int ctlr, unsigned char *buffer, off_t *pos, off_t *len)
1347{
1348	unsigned long flags;
1349	int size;
1350
1351	*pos = *pos -1; *len = *len - 1; // cut off the last trailing newline
1352
1353	CPQ_TAPE_LOCK(ctlr, flags);
1354	size = sprintf(buffer + *len,
1355		"Sequential access devices: %d\n\n",
1356			ccissscsi[ctlr].ndevices);
1357	CPQ_TAPE_UNLOCK(ctlr, flags);
1358	*pos += size; *len += size;
1359}
1360
1361/* Need at least one of these error handlers to keep ../scsi/hosts.c from
1362 * complaining.  Doing a host- or bus-reset can't do anything good here.
1363 * Despite what it might say in scsi_error.c, there may well be commands
1364 * on the controller, as the cciss driver registers twice, once as a block
1365 * device for the logical drives, and once as a scsi device, for any tape
1366 * drives.  So we know there are no commands out on the tape drives, but we
1367 * don't know there are no commands on the controller, and it is likely
1368 * that there probably are, as the cciss block device is most commonly used
1369 * as a boot device (embedded controller on HP/Compaq systems.)
1370*/
1371
1372static int cciss_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
1373{
1374	int rc;
1375	CommandList_struct *cmd_in_trouble;
1376	ctlr_info_t **c;
1377	int ctlr;
1378
1379	/* find the controller to which the command to be aborted was sent */
1380	c = (ctlr_info_t **) &scsicmd->device->host->hostdata[0];
1381	if (c == NULL) /* paranoia */
1382		return FAILED;
1383	ctlr = (*c)->ctlr;
1384	printk(KERN_WARNING "cciss%d: resetting tape drive or medium changer.\n", ctlr);
1385
1386	/* find the command that's giving us trouble */
1387	cmd_in_trouble = (CommandList_struct *) scsicmd->host_scribble;
1388	if (cmd_in_trouble == NULL) { /* paranoia */
1389		return FAILED;
1390	}
1391	/* send a reset to the SCSI LUN which the command was sent to */
1392	rc = sendcmd(CCISS_RESET_MSG, ctlr, NULL, 0, 2, 0, 0,
1393		(unsigned char *) &cmd_in_trouble->Header.LUN.LunAddrBytes[0],
1394		TYPE_MSG);
1395	/* sendcmd turned off interrputs on the board, turn 'em back on. */
1396	(*c)->access.set_intr_mask(*c, CCISS_INTR_ON);
1397	if (rc == 0)
1398		return SUCCESS;
1399	printk(KERN_WARNING "cciss%d: resetting device failed.\n", ctlr);
1400	return FAILED;
1401}
1402
1403static int  cciss_eh_abort_handler(struct scsi_cmnd *scsicmd)
1404{
1405	int rc;
1406	CommandList_struct *cmd_to_abort;
1407	ctlr_info_t **c;
1408	int ctlr;
1409
1410	/* find the controller to which the command to be aborted was sent */
1411	c = (ctlr_info_t **) &scsicmd->device->host->hostdata[0];
1412	if (c == NULL) /* paranoia */
1413		return FAILED;
1414	ctlr = (*c)->ctlr;
1415	printk(KERN_WARNING "cciss%d: aborting tardy SCSI cmd\n", ctlr);
1416
1417	/* find the command to be aborted */
1418	cmd_to_abort = (CommandList_struct *) scsicmd->host_scribble;
1419	if (cmd_to_abort == NULL) /* paranoia */
1420		return FAILED;
1421	rc = sendcmd(CCISS_ABORT_MSG, ctlr, &cmd_to_abort->Header.Tag,
1422		0, 2, 0, 0,
1423		(unsigned char *) &cmd_to_abort->Header.LUN.LunAddrBytes[0],
1424		TYPE_MSG);
1425	/* sendcmd turned off interrputs on the board, turn 'em back on. */
1426	(*c)->access.set_intr_mask(*c, CCISS_INTR_ON);
1427	if (rc == 0)
1428		return SUCCESS;
1429	return FAILED;
1430
1431}
1432
1433#else /* no CONFIG_CISS_SCSI_TAPE */
1434
1435/* If no tape support, then these become defined out of existence */
1436
1437#define cciss_scsi_setup(cntl_num)
1438#define cciss_unregister_scsi(ctlr)
1439#define cciss_register_scsi(ctlr)
1440#define cciss_proc_tape_report(ctlr, buffer, pos, len)
1441
1442#endif /* CONFIG_CISS_SCSI_TAPE */
1443