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