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