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