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