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