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