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