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