[SCSI] fix two leaks in scsi_alloc_sdev failure paths
[pandora-kernel.git] / drivers / scsi / scsi_scan.c
1 /*
2  * scsi_scan.c
3  *
4  * Copyright (C) 2000 Eric Youngdale,
5  * Copyright (C) 2002 Patrick Mansfield
6  *
7  * The general scanning/probing algorithm is as follows, exceptions are
8  * made to it depending on device specific flags, compilation options, and
9  * global variable (boot or module load time) settings.
10  *
11  * A specific LUN is scanned via an INQUIRY command; if the LUN has a
12  * device attached, a scsi_device is allocated and setup for it.
13  *
14  * For every id of every channel on the given host:
15  *
16  *      Scan LUN 0; if the target responds to LUN 0 (even if there is no
17  *      device or storage attached to LUN 0):
18  *
19  *              If LUN 0 has a device attached, allocate and setup a
20  *              scsi_device for it.
21  *
22  *              If target is SCSI-3 or up, issue a REPORT LUN, and scan
23  *              all of the LUNs returned by the REPORT LUN; else,
24  *              sequentially scan LUNs up until some maximum is reached,
25  *              or a LUN is seen that cannot have a device attached to it.
26  */
27
28 #include <linux/config.h>
29 #include <linux/module.h>
30 #include <linux/moduleparam.h>
31 #include <linux/init.h>
32 #include <linux/blkdev.h>
33 #include <asm/semaphore.h>
34
35 #include <scsi/scsi.h>
36 #include <scsi/scsi_device.h>
37 #include <scsi/scsi_driver.h>
38 #include <scsi/scsi_devinfo.h>
39 #include <scsi/scsi_host.h>
40 #include <scsi/scsi_request.h>
41 #include <scsi/scsi_transport.h>
42 #include <scsi/scsi_eh.h>
43
44 #include "scsi_priv.h"
45 #include "scsi_logging.h"
46
47 #define ALLOC_FAILURE_MSG       KERN_ERR "%s: Allocation failure during" \
48         " SCSI scanning, some SCSI devices might not be configured\n"
49
50 /*
51  * Default timeout
52  */
53 #define SCSI_TIMEOUT (2*HZ)
54
55 /*
56  * Prefix values for the SCSI id's (stored in driverfs name field)
57  */
58 #define SCSI_UID_SER_NUM 'S'
59 #define SCSI_UID_UNKNOWN 'Z'
60
61 /*
62  * Return values of some of the scanning functions.
63  *
64  * SCSI_SCAN_NO_RESPONSE: no valid response received from the target, this
65  * includes allocation or general failures preventing IO from being sent.
66  *
67  * SCSI_SCAN_TARGET_PRESENT: target responded, but no device is available
68  * on the given LUN.
69  *
70  * SCSI_SCAN_LUN_PRESENT: target responded, and a device is available on a
71  * given LUN.
72  */
73 #define SCSI_SCAN_NO_RESPONSE           0
74 #define SCSI_SCAN_TARGET_PRESENT        1
75 #define SCSI_SCAN_LUN_PRESENT           2
76
77 static const char *scsi_null_device_strs = "nullnullnullnull";
78
79 #define MAX_SCSI_LUNS   512
80
81 #ifdef CONFIG_SCSI_MULTI_LUN
82 static unsigned int max_scsi_luns = MAX_SCSI_LUNS;
83 #else
84 static unsigned int max_scsi_luns = 1;
85 #endif
86
87 module_param_named(max_luns, max_scsi_luns, int, S_IRUGO|S_IWUSR);
88 MODULE_PARM_DESC(max_luns,
89                  "last scsi LUN (should be between 1 and 2^32-1)");
90
91 /*
92  * max_scsi_report_luns: the maximum number of LUNS that will be
93  * returned from the REPORT LUNS command. 8 times this value must
94  * be allocated. In theory this could be up to an 8 byte value, but
95  * in practice, the maximum number of LUNs suppored by any device
96  * is about 16k.
97  */
98 static unsigned int max_scsi_report_luns = 511;
99
100 module_param_named(max_report_luns, max_scsi_report_luns, int, S_IRUGO|S_IWUSR);
101 MODULE_PARM_DESC(max_report_luns,
102                  "REPORT LUNS maximum number of LUNS received (should be"
103                  " between 1 and 16384)");
104
105 static unsigned int scsi_inq_timeout = SCSI_TIMEOUT/HZ+3;
106
107 module_param_named(inq_timeout, scsi_inq_timeout, int, S_IRUGO|S_IWUSR);
108 MODULE_PARM_DESC(inq_timeout, 
109                  "Timeout (in seconds) waiting for devices to answer INQUIRY."
110                  " Default is 5. Some non-compliant devices need more.");
111
112 /**
113  * scsi_unlock_floptical - unlock device via a special MODE SENSE command
114  * @sdev:       scsi device to send command to
115  * @result:     area to store the result of the MODE SENSE
116  *
117  * Description:
118  *     Send a vendor specific MODE SENSE (not a MODE SELECT) command.
119  *     Called for BLIST_KEY devices.
120  **/
121 static void scsi_unlock_floptical(struct scsi_device *sdev,
122                                   unsigned char *result)
123 {
124         unsigned char scsi_cmd[MAX_COMMAND_SIZE];
125
126         printk(KERN_NOTICE "scsi: unlocking floptical drive\n");
127         scsi_cmd[0] = MODE_SENSE;
128         scsi_cmd[1] = 0;
129         scsi_cmd[2] = 0x2e;
130         scsi_cmd[3] = 0;
131         scsi_cmd[4] = 0x2a;     /* size */
132         scsi_cmd[5] = 0;
133         scsi_execute_req(sdev, scsi_cmd, DMA_FROM_DEVICE, result, 0x2a, NULL,
134                          SCSI_TIMEOUT, 3);
135 }
136
137 /**
138  * print_inquiry - printk the inquiry information
139  * @inq_result: printk this SCSI INQUIRY
140  *
141  * Description:
142  *     printk the vendor, model, and other information found in the
143  *     INQUIRY data in @inq_result.
144  *
145  * Notes:
146  *     Remove this, and replace with a hotplug event that logs any
147  *     relevant information.
148  **/
149 static void print_inquiry(unsigned char *inq_result)
150 {
151         int i;
152
153         printk(KERN_NOTICE "  Vendor: ");
154         for (i = 8; i < 16; i++)
155                 if (inq_result[i] >= 0x20 && i < inq_result[4] + 5)
156                         printk("%c", inq_result[i]);
157                 else
158                         printk(" ");
159
160         printk("  Model: ");
161         for (i = 16; i < 32; i++)
162                 if (inq_result[i] >= 0x20 && i < inq_result[4] + 5)
163                         printk("%c", inq_result[i]);
164                 else
165                         printk(" ");
166
167         printk("  Rev: ");
168         for (i = 32; i < 36; i++)
169                 if (inq_result[i] >= 0x20 && i < inq_result[4] + 5)
170                         printk("%c", inq_result[i]);
171                 else
172                         printk(" ");
173
174         printk("\n");
175
176         i = inq_result[0] & 0x1f;
177
178         printk(KERN_NOTICE "  Type:   %s ",
179                i <
180                MAX_SCSI_DEVICE_CODE ? scsi_device_types[i] :
181                "Unknown          ");
182         printk("                 ANSI SCSI revision: %02x",
183                inq_result[2] & 0x07);
184         if ((inq_result[2] & 0x07) == 1 && (inq_result[3] & 0x0f) == 1)
185                 printk(" CCS\n");
186         else
187                 printk("\n");
188 }
189
190 /**
191  * scsi_alloc_sdev - allocate and setup a scsi_Device
192  *
193  * Description:
194  *     Allocate, initialize for io, and return a pointer to a scsi_Device.
195  *     Stores the @shost, @channel, @id, and @lun in the scsi_Device, and
196  *     adds scsi_Device to the appropriate list.
197  *
198  * Return value:
199  *     scsi_Device pointer, or NULL on failure.
200  **/
201 static struct scsi_device *scsi_alloc_sdev(struct scsi_target *starget,
202                                            unsigned int lun, void *hostdata)
203 {
204         struct scsi_device *sdev;
205         int display_failure_msg = 1, ret;
206         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
207
208         sdev = kzalloc(sizeof(*sdev) + shost->transportt->device_size,
209                        GFP_ATOMIC);
210         if (!sdev)
211                 goto out;
212
213         sdev->vendor = scsi_null_device_strs;
214         sdev->model = scsi_null_device_strs;
215         sdev->rev = scsi_null_device_strs;
216         sdev->host = shost;
217         sdev->id = starget->id;
218         sdev->lun = lun;
219         sdev->channel = starget->channel;
220         sdev->sdev_state = SDEV_CREATED;
221         INIT_LIST_HEAD(&sdev->siblings);
222         INIT_LIST_HEAD(&sdev->same_target_siblings);
223         INIT_LIST_HEAD(&sdev->cmd_list);
224         INIT_LIST_HEAD(&sdev->starved_entry);
225         spin_lock_init(&sdev->list_lock);
226
227         sdev->sdev_gendev.parent = get_device(&starget->dev);
228         sdev->sdev_target = starget;
229
230         /* usually NULL and set by ->slave_alloc instead */
231         sdev->hostdata = hostdata;
232
233         /* if the device needs this changing, it may do so in the
234          * slave_configure function */
235         sdev->max_device_blocked = SCSI_DEFAULT_DEVICE_BLOCKED;
236
237         /*
238          * Some low level driver could use device->type
239          */
240         sdev->type = -1;
241
242         /*
243          * Assume that the device will have handshaking problems,
244          * and then fix this field later if it turns out it
245          * doesn't
246          */
247         sdev->borken = 1;
248
249         sdev->request_queue = scsi_alloc_queue(sdev);
250         if (!sdev->request_queue) {
251                 /* release fn is set up in scsi_sysfs_device_initialise, so
252                  * have to free and put manually here */
253                 put_device(&starget->dev);
254                 kfree(sdev);
255                 goto out;
256         }
257
258         sdev->request_queue->queuedata = sdev;
259         scsi_adjust_queue_depth(sdev, 0, sdev->host->cmd_per_lun);
260
261         scsi_sysfs_device_initialize(sdev);
262
263         if (shost->hostt->slave_alloc) {
264                 ret = shost->hostt->slave_alloc(sdev);
265                 if (ret) {
266                         /*
267                          * if LLDD reports slave not present, don't clutter
268                          * console with alloc failure messages
269                          */
270                         if (ret == -ENXIO)
271                                 display_failure_msg = 0;
272                         goto out_device_destroy;
273                 }
274         }
275
276         return sdev;
277
278 out_device_destroy:
279         transport_destroy_device(&sdev->sdev_gendev);
280         put_device(&sdev->sdev_gendev);
281 out:
282         if (display_failure_msg)
283                 printk(ALLOC_FAILURE_MSG, __FUNCTION__);
284         return NULL;
285 }
286
287 static void scsi_target_dev_release(struct device *dev)
288 {
289         struct device *parent = dev->parent;
290         struct scsi_target *starget = to_scsi_target(dev);
291         struct Scsi_Host *shost = dev_to_shost(parent);
292
293         if (shost->hostt->target_destroy)
294                 shost->hostt->target_destroy(starget);
295         kfree(starget);
296         put_device(parent);
297 }
298
299 int scsi_is_target_device(const struct device *dev)
300 {
301         return dev->release == scsi_target_dev_release;
302 }
303 EXPORT_SYMBOL(scsi_is_target_device);
304
305 static struct scsi_target *__scsi_find_target(struct device *parent,
306                                               int channel, uint id)
307 {
308         struct scsi_target *starget, *found_starget = NULL;
309         struct Scsi_Host *shost = dev_to_shost(parent);
310         /*
311          * Search for an existing target for this sdev.
312          */
313         list_for_each_entry(starget, &shost->__targets, siblings) {
314                 if (starget->id == id &&
315                     starget->channel == channel) {
316                         found_starget = starget;
317                         break;
318                 }
319         }
320         if (found_starget)
321                 get_device(&found_starget->dev);
322
323         return found_starget;
324 }
325
326 static struct scsi_target *scsi_alloc_target(struct device *parent,
327                                              int channel, uint id)
328 {
329         struct Scsi_Host *shost = dev_to_shost(parent);
330         struct device *dev = NULL;
331         unsigned long flags;
332         const int size = sizeof(struct scsi_target)
333                 + shost->transportt->target_size;
334         struct scsi_target *starget;
335         struct scsi_target *found_target;
336         int error;
337
338         starget = kzalloc(size, GFP_KERNEL);
339         if (!starget) {
340                 printk(KERN_ERR "%s: allocation failure\n", __FUNCTION__);
341                 return NULL;
342         }
343         dev = &starget->dev;
344         device_initialize(dev);
345         starget->reap_ref = 1;
346         dev->parent = get_device(parent);
347         dev->release = scsi_target_dev_release;
348         sprintf(dev->bus_id, "target%d:%d:%d",
349                 shost->host_no, channel, id);
350         starget->id = id;
351         starget->channel = channel;
352         INIT_LIST_HEAD(&starget->siblings);
353         INIT_LIST_HEAD(&starget->devices);
354         starget->state = STARGET_RUNNING;
355  retry:
356         spin_lock_irqsave(shost->host_lock, flags);
357
358         found_target = __scsi_find_target(parent, channel, id);
359         if (found_target)
360                 goto found;
361
362         list_add_tail(&starget->siblings, &shost->__targets);
363         spin_unlock_irqrestore(shost->host_lock, flags);
364         /* allocate and add */
365         transport_setup_device(dev);
366         error = device_add(dev);
367         if (error) {
368                 dev_err(dev, "target device_add failed, error %d\n", error);
369                 spin_lock_irqsave(shost->host_lock, flags);
370                 list_del_init(&starget->siblings);
371                 spin_unlock_irqrestore(shost->host_lock, flags);
372                 transport_destroy_device(dev);
373                 put_device(parent);
374                 kfree(starget);
375                 return NULL;
376         }
377         transport_add_device(dev);
378         if (shost->hostt->target_alloc) {
379                 error = shost->hostt->target_alloc(starget);
380
381                 if(error) {
382                         dev_printk(KERN_ERR, dev, "target allocation failed, error %d\n", error);
383                         /* don't want scsi_target_reap to do the final
384                          * put because it will be under the host lock */
385                         get_device(dev);
386                         scsi_target_reap(starget);
387                         put_device(dev);
388                         return NULL;
389                 }
390         }
391
392         return starget;
393
394  found:
395         found_target->reap_ref++;
396         spin_unlock_irqrestore(shost->host_lock, flags);
397         put_device(parent);
398         if (found_target->state != STARGET_DEL) {
399                 kfree(starget);
400                 return found_target;
401         }
402         /* Unfortunately, we found a dying target; need to
403          * wait until it's dead before we can get a new one */
404         put_device(&found_target->dev);
405         flush_scheduled_work();
406         goto retry;
407 }
408
409 static void scsi_target_reap_usercontext(void *data)
410 {
411         struct scsi_target *starget = data;
412         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
413         unsigned long flags;
414
415         transport_remove_device(&starget->dev);
416         device_del(&starget->dev);
417         transport_destroy_device(&starget->dev);
418         spin_lock_irqsave(shost->host_lock, flags);
419         list_del_init(&starget->siblings);
420         spin_unlock_irqrestore(shost->host_lock, flags);
421         put_device(&starget->dev);
422 }
423
424 /**
425  * scsi_target_reap - check to see if target is in use and destroy if not
426  *
427  * @starget: target to be checked
428  *
429  * This is used after removing a LUN or doing a last put of the target
430  * it checks atomically that nothing is using the target and removes
431  * it if so.
432  */
433 void scsi_target_reap(struct scsi_target *starget)
434 {
435         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
436         unsigned long flags;
437
438         spin_lock_irqsave(shost->host_lock, flags);
439
440         if (--starget->reap_ref == 0 && list_empty(&starget->devices)) {
441                 BUG_ON(starget->state == STARGET_DEL);
442                 starget->state = STARGET_DEL;
443                 spin_unlock_irqrestore(shost->host_lock, flags);
444                 execute_in_process_context(scsi_target_reap_usercontext,
445                                            starget, &starget->ew);
446                 return;
447
448         }
449         spin_unlock_irqrestore(shost->host_lock, flags);
450
451         return;
452 }
453
454 /**
455  * scsi_probe_lun - probe a single LUN using a SCSI INQUIRY
456  * @sdev:       scsi_device to probe
457  * @inq_result: area to store the INQUIRY result
458  * @result_len: len of inq_result
459  * @bflags:     store any bflags found here
460  *
461  * Description:
462  *     Probe the lun associated with @req using a standard SCSI INQUIRY;
463  *
464  *     If the INQUIRY is successful, zero is returned and the
465  *     INQUIRY data is in @inq_result; the scsi_level and INQUIRY length
466  *     are copied to the scsi_device any flags value is stored in *@bflags.
467  **/
468 static int scsi_probe_lun(struct scsi_device *sdev, char *inq_result,
469                           int result_len, int *bflags)
470 {
471         unsigned char scsi_cmd[MAX_COMMAND_SIZE];
472         int first_inquiry_len, try_inquiry_len, next_inquiry_len;
473         int response_len = 0;
474         int pass, count, result;
475         struct scsi_sense_hdr sshdr;
476
477         *bflags = 0;
478
479         /* Perform up to 3 passes.  The first pass uses a conservative
480          * transfer length of 36 unless sdev->inquiry_len specifies a
481          * different value. */
482         first_inquiry_len = sdev->inquiry_len ? sdev->inquiry_len : 36;
483         try_inquiry_len = first_inquiry_len;
484         pass = 1;
485
486  next_pass:
487         SCSI_LOG_SCAN_BUS(3, sdev_printk(KERN_INFO, sdev,
488                                 "scsi scan: INQUIRY pass %d length %d\n",
489                                 pass, try_inquiry_len));
490
491         /* Each pass gets up to three chances to ignore Unit Attention */
492         for (count = 0; count < 3; ++count) {
493                 memset(scsi_cmd, 0, 6);
494                 scsi_cmd[0] = INQUIRY;
495                 scsi_cmd[4] = (unsigned char) try_inquiry_len;
496
497                 memset(inq_result, 0, try_inquiry_len);
498
499                 result = scsi_execute_req(sdev,  scsi_cmd, DMA_FROM_DEVICE,
500                                           inq_result, try_inquiry_len, &sshdr,
501                                           HZ / 2 + HZ * scsi_inq_timeout, 3);
502
503                 SCSI_LOG_SCAN_BUS(3, printk(KERN_INFO "scsi scan: INQUIRY %s "
504                                 "with code 0x%x\n",
505                                 result ? "failed" : "successful", result));
506
507                 if (result) {
508                         /*
509                          * not-ready to ready transition [asc/ascq=0x28/0x0]
510                          * or power-on, reset [asc/ascq=0x29/0x0], continue.
511                          * INQUIRY should not yield UNIT_ATTENTION
512                          * but many buggy devices do so anyway. 
513                          */
514                         if ((driver_byte(result) & DRIVER_SENSE) &&
515                             scsi_sense_valid(&sshdr)) {
516                                 if ((sshdr.sense_key == UNIT_ATTENTION) &&
517                                     ((sshdr.asc == 0x28) ||
518                                      (sshdr.asc == 0x29)) &&
519                                     (sshdr.ascq == 0))
520                                         continue;
521                         }
522                 }
523                 break;
524         }
525
526         if (result == 0) {
527                 response_len = (unsigned char) inq_result[4] + 5;
528                 if (response_len > 255)
529                         response_len = first_inquiry_len;       /* sanity */
530
531                 /*
532                  * Get any flags for this device.
533                  *
534                  * XXX add a bflags to scsi_device, and replace the
535                  * corresponding bit fields in scsi_device, so bflags
536                  * need not be passed as an argument.
537                  */
538                 *bflags = scsi_get_device_flags(sdev, &inq_result[8],
539                                 &inq_result[16]);
540
541                 /* When the first pass succeeds we gain information about
542                  * what larger transfer lengths might work. */
543                 if (pass == 1) {
544                         if (BLIST_INQUIRY_36 & *bflags)
545                                 next_inquiry_len = 36;
546                         else if (BLIST_INQUIRY_58 & *bflags)
547                                 next_inquiry_len = 58;
548                         else if (sdev->inquiry_len)
549                                 next_inquiry_len = sdev->inquiry_len;
550                         else
551                                 next_inquiry_len = response_len;
552
553                         /* If more data is available perform the second pass */
554                         if (next_inquiry_len > try_inquiry_len) {
555                                 try_inquiry_len = next_inquiry_len;
556                                 pass = 2;
557                                 goto next_pass;
558                         }
559                 }
560
561         } else if (pass == 2) {
562                 printk(KERN_INFO "scsi scan: %d byte inquiry failed.  "
563                                 "Consider BLIST_INQUIRY_36 for this device\n",
564                                 try_inquiry_len);
565
566                 /* If this pass failed, the third pass goes back and transfers
567                  * the same amount as we successfully got in the first pass. */
568                 try_inquiry_len = first_inquiry_len;
569                 pass = 3;
570                 goto next_pass;
571         }
572
573         /* If the last transfer attempt got an error, assume the
574          * peripheral doesn't exist or is dead. */
575         if (result)
576                 return -EIO;
577
578         /* Don't report any more data than the device says is valid */
579         sdev->inquiry_len = min(try_inquiry_len, response_len);
580
581         /*
582          * XXX Abort if the response length is less than 36? If less than
583          * 32, the lookup of the device flags (above) could be invalid,
584          * and it would be possible to take an incorrect action - we do
585          * not want to hang because of a short INQUIRY. On the flip side,
586          * if the device is spun down or becoming ready (and so it gives a
587          * short INQUIRY), an abort here prevents any further use of the
588          * device, including spin up.
589          *
590          * Related to the above issue:
591          *
592          * XXX Devices (disk or all?) should be sent a TEST UNIT READY,
593          * and if not ready, sent a START_STOP to start (maybe spin up) and
594          * then send the INQUIRY again, since the INQUIRY can change after
595          * a device is initialized.
596          *
597          * Ideally, start a device if explicitly asked to do so.  This
598          * assumes that a device is spun up on power on, spun down on
599          * request, and then spun up on request.
600          */
601
602         /*
603          * The scanning code needs to know the scsi_level, even if no
604          * device is attached at LUN 0 (SCSI_SCAN_TARGET_PRESENT) so
605          * non-zero LUNs can be scanned.
606          */
607         sdev->scsi_level = inq_result[2] & 0x07;
608         if (sdev->scsi_level >= 2 ||
609             (sdev->scsi_level == 1 && (inq_result[3] & 0x0f) == 1))
610                 sdev->scsi_level++;
611         sdev->sdev_target->scsi_level = sdev->scsi_level;
612
613         return 0;
614 }
615
616 /**
617  * scsi_add_lun - allocate and fully initialze a scsi_device
618  * @sdevscan:   holds information to be stored in the new scsi_device
619  * @sdevnew:    store the address of the newly allocated scsi_device
620  * @inq_result: holds the result of a previous INQUIRY to the LUN
621  * @bflags:     black/white list flag
622  *
623  * Description:
624  *     Allocate and initialize a scsi_device matching sdevscan. Optionally
625  *     set fields based on values in *@bflags. If @sdevnew is not
626  *     NULL, store the address of the new scsi_device in *@sdevnew (needed
627  *     when scanning a particular LUN).
628  *
629  * Return:
630  *     SCSI_SCAN_NO_RESPONSE: could not allocate or setup a scsi_device
631  *     SCSI_SCAN_LUN_PRESENT: a new scsi_device was allocated and initialized
632  **/
633 static int scsi_add_lun(struct scsi_device *sdev, char *inq_result, int *bflags)
634 {
635         /*
636          * XXX do not save the inquiry, since it can change underneath us,
637          * save just vendor/model/rev.
638          *
639          * Rather than save it and have an ioctl that retrieves the saved
640          * value, have an ioctl that executes the same INQUIRY code used
641          * in scsi_probe_lun, let user level programs doing INQUIRY
642          * scanning run at their own risk, or supply a user level program
643          * that can correctly scan.
644          */
645         sdev->inquiry = kmalloc(sdev->inquiry_len, GFP_ATOMIC);
646         if (sdev->inquiry == NULL) {
647                 return SCSI_SCAN_NO_RESPONSE;
648         }
649
650         memcpy(sdev->inquiry, inq_result, sdev->inquiry_len);
651         sdev->vendor = (char *) (sdev->inquiry + 8);
652         sdev->model = (char *) (sdev->inquiry + 16);
653         sdev->rev = (char *) (sdev->inquiry + 32);
654
655         if (*bflags & BLIST_ISROM) {
656                 /*
657                  * It would be better to modify sdev->type, and set
658                  * sdev->removable, but then the print_inquiry() output
659                  * would not show TYPE_ROM; if print_inquiry() is removed
660                  * the issue goes away.
661                  */
662                 inq_result[0] = TYPE_ROM;
663                 inq_result[1] |= 0x80;  /* removable */
664         } else if (*bflags & BLIST_NO_ULD_ATTACH)
665                 sdev->no_uld_attach = 1;
666
667         switch (sdev->type = (inq_result[0] & 0x1f)) {
668         case TYPE_TAPE:
669         case TYPE_DISK:
670         case TYPE_PRINTER:
671         case TYPE_MOD:
672         case TYPE_PROCESSOR:
673         case TYPE_SCANNER:
674         case TYPE_MEDIUM_CHANGER:
675         case TYPE_ENCLOSURE:
676         case TYPE_COMM:
677         case TYPE_RBC:
678                 sdev->writeable = 1;
679                 break;
680         case TYPE_WORM:
681         case TYPE_ROM:
682                 sdev->writeable = 0;
683                 break;
684         default:
685                 printk(KERN_INFO "scsi: unknown device type %d\n", sdev->type);
686         }
687
688         print_inquiry(inq_result);
689
690         /*
691          * For a peripheral qualifier (PQ) value of 1 (001b), the SCSI
692          * spec says: The device server is capable of supporting the
693          * specified peripheral device type on this logical unit. However,
694          * the physical device is not currently connected to this logical
695          * unit.
696          *
697          * The above is vague, as it implies that we could treat 001 and
698          * 011 the same. Stay compatible with previous code, and create a
699          * scsi_device for a PQ of 1
700          *
701          * Don't set the device offline here; rather let the upper
702          * level drivers eval the PQ to decide whether they should
703          * attach. So remove ((inq_result[0] >> 5) & 7) == 1 check.
704          */ 
705
706         sdev->inq_periph_qual = (inq_result[0] >> 5) & 7;
707         sdev->removable = (0x80 & inq_result[1]) >> 7;
708         sdev->lockable = sdev->removable;
709         sdev->soft_reset = (inq_result[7] & 1) && ((inq_result[3] & 7) == 2);
710
711         if (sdev->scsi_level >= SCSI_3 || (sdev->inquiry_len > 56 &&
712                 inq_result[56] & 0x04))
713                 sdev->ppr = 1;
714         if (inq_result[7] & 0x60)
715                 sdev->wdtr = 1;
716         if (inq_result[7] & 0x10)
717                 sdev->sdtr = 1;
718
719         /*
720          * End sysfs code.
721          */
722
723         if ((sdev->scsi_level >= SCSI_2) && (inq_result[7] & 2) &&
724             !(*bflags & BLIST_NOTQ))
725                 sdev->tagged_supported = 1;
726         /*
727          * Some devices (Texel CD ROM drives) have handshaking problems
728          * when used with the Seagate controllers. borken is initialized
729          * to 1, and then set it to 0 here.
730          */
731         if ((*bflags & BLIST_BORKEN) == 0)
732                 sdev->borken = 0;
733
734         /*
735          * Apparently some really broken devices (contrary to the SCSI
736          * standards) need to be selected without asserting ATN
737          */
738         if (*bflags & BLIST_SELECT_NO_ATN)
739                 sdev->select_no_atn = 1;
740
741         /*
742          * Some devices may not want to have a start command automatically
743          * issued when a device is added.
744          */
745         if (*bflags & BLIST_NOSTARTONADD)
746                 sdev->no_start_on_add = 1;
747
748         if (*bflags & BLIST_SINGLELUN)
749                 sdev->single_lun = 1;
750
751
752         sdev->use_10_for_rw = 1;
753
754         if (*bflags & BLIST_MS_SKIP_PAGE_08)
755                 sdev->skip_ms_page_8 = 1;
756
757         if (*bflags & BLIST_MS_SKIP_PAGE_3F)
758                 sdev->skip_ms_page_3f = 1;
759
760         if (*bflags & BLIST_USE_10_BYTE_MS)
761                 sdev->use_10_for_ms = 1;
762
763         /* set the device running here so that slave configure
764          * may do I/O */
765         scsi_device_set_state(sdev, SDEV_RUNNING);
766
767         if (*bflags & BLIST_MS_192_BYTES_FOR_3F)
768                 sdev->use_192_bytes_for_3f = 1;
769
770         if (*bflags & BLIST_NOT_LOCKABLE)
771                 sdev->lockable = 0;
772
773         if (*bflags & BLIST_RETRY_HWERROR)
774                 sdev->retry_hwerror = 1;
775
776         transport_configure_device(&sdev->sdev_gendev);
777
778         if (sdev->host->hostt->slave_configure)
779                 sdev->host->hostt->slave_configure(sdev);
780
781         /*
782          * Ok, the device is now all set up, we can
783          * register it and tell the rest of the kernel
784          * about it.
785          */
786         if (scsi_sysfs_add_sdev(sdev) != 0)
787                 return SCSI_SCAN_NO_RESPONSE;
788
789         return SCSI_SCAN_LUN_PRESENT;
790 }
791
792 static inline void scsi_destroy_sdev(struct scsi_device *sdev)
793 {
794         if (sdev->host->hostt->slave_destroy)
795                 sdev->host->hostt->slave_destroy(sdev);
796         transport_destroy_device(&sdev->sdev_gendev);
797         put_device(&sdev->sdev_gendev);
798 }
799
800
801 /**
802  * scsi_probe_and_add_lun - probe a LUN, if a LUN is found add it
803  * @starget:    pointer to target device structure
804  * @lun:        LUN of target device
805  * @sdevscan:   probe the LUN corresponding to this scsi_device
806  * @sdevnew:    store the value of any new scsi_device allocated
807  * @bflagsp:    store bflags here if not NULL
808  *
809  * Description:
810  *     Call scsi_probe_lun, if a LUN with an attached device is found,
811  *     allocate and set it up by calling scsi_add_lun.
812  *
813  * Return:
814  *     SCSI_SCAN_NO_RESPONSE: could not allocate or setup a scsi_device
815  *     SCSI_SCAN_TARGET_PRESENT: target responded, but no device is
816  *         attached at the LUN
817  *     SCSI_SCAN_LUN_PRESENT: a new scsi_device was allocated and initialized
818  **/
819 static int scsi_probe_and_add_lun(struct scsi_target *starget,
820                                   uint lun, int *bflagsp,
821                                   struct scsi_device **sdevp, int rescan,
822                                   void *hostdata)
823 {
824         struct scsi_device *sdev;
825         unsigned char *result;
826         int bflags, res = SCSI_SCAN_NO_RESPONSE, result_len = 256;
827         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
828
829         /*
830          * The rescan flag is used as an optimization, the first scan of a
831          * host adapter calls into here with rescan == 0.
832          */
833         sdev = scsi_device_lookup_by_target(starget, lun);
834         if (sdev) {
835                 if (rescan || sdev->sdev_state != SDEV_CREATED) {
836                         SCSI_LOG_SCAN_BUS(3, printk(KERN_INFO
837                                 "scsi scan: device exists on %s\n",
838                                 sdev->sdev_gendev.bus_id));
839                         if (sdevp)
840                                 *sdevp = sdev;
841                         else
842                                 scsi_device_put(sdev);
843
844                         if (bflagsp)
845                                 *bflagsp = scsi_get_device_flags(sdev,
846                                                                  sdev->vendor,
847                                                                  sdev->model);
848                         return SCSI_SCAN_LUN_PRESENT;
849                 }
850                 scsi_device_put(sdev);
851         } else
852                 sdev = scsi_alloc_sdev(starget, lun, hostdata);
853         if (!sdev)
854                 goto out;
855
856         result = kmalloc(result_len, GFP_ATOMIC |
857                         ((shost->unchecked_isa_dma) ? __GFP_DMA : 0));
858         if (!result)
859                 goto out_free_sdev;
860
861         if (scsi_probe_lun(sdev, result, result_len, &bflags))
862                 goto out_free_result;
863
864         /*
865          * result contains valid SCSI INQUIRY data.
866          */
867         if ((result[0] >> 5) == 3) {
868                 /*
869                  * For a Peripheral qualifier 3 (011b), the SCSI
870                  * spec says: The device server is not capable of
871                  * supporting a physical device on this logical
872                  * unit.
873                  *
874                  * For disks, this implies that there is no
875                  * logical disk configured at sdev->lun, but there
876                  * is a target id responding.
877                  */
878                 SCSI_LOG_SCAN_BUS(3, printk(KERN_INFO
879                                         "scsi scan: peripheral qualifier of 3,"
880                                         " no device added\n"));
881                 res = SCSI_SCAN_TARGET_PRESENT;
882                 goto out_free_result;
883         }
884
885         /*
886          * Non-standard SCSI targets may set the PDT to 0x1f (unknown or
887          * no device type) instead of using the Peripheral Qualifier to
888          * indicate that no LUN is present.  For example, USB UFI does this.
889          */
890         if (starget->pdt_1f_for_no_lun && (result[0] & 0x1f) == 0x1f) {
891                 SCSI_LOG_SCAN_BUS(3, printk(KERN_INFO
892                                         "scsi scan: peripheral device type"
893                                         " of 31, no device added\n"));
894                 res = SCSI_SCAN_TARGET_PRESENT;
895                 goto out_free_result;
896         }
897
898         res = scsi_add_lun(sdev, result, &bflags);
899         if (res == SCSI_SCAN_LUN_PRESENT) {
900                 if (bflags & BLIST_KEY) {
901                         sdev->lockable = 0;
902                         scsi_unlock_floptical(sdev, result);
903                 }
904                 if (bflagsp)
905                         *bflagsp = bflags;
906         }
907
908  out_free_result:
909         kfree(result);
910  out_free_sdev:
911         if (res == SCSI_SCAN_LUN_PRESENT) {
912                 if (sdevp) {
913                         if (scsi_device_get(sdev) == 0) {
914                                 *sdevp = sdev;
915                         } else {
916                                 __scsi_remove_device(sdev);
917                                 res = SCSI_SCAN_NO_RESPONSE;
918                         }
919                 }
920         } else
921                 scsi_destroy_sdev(sdev);
922  out:
923         return res;
924 }
925
926 /**
927  * scsi_sequential_lun_scan - sequentially scan a SCSI target
928  * @starget:    pointer to target structure to scan
929  * @bflags:     black/white list flag for LUN 0
930  * @lun0_res:   result of scanning LUN 0
931  *
932  * Description:
933  *     Generally, scan from LUN 1 (LUN 0 is assumed to already have been
934  *     scanned) to some maximum lun until a LUN is found with no device
935  *     attached. Use the bflags to figure out any oddities.
936  *
937  *     Modifies sdevscan->lun.
938  **/
939 static void scsi_sequential_lun_scan(struct scsi_target *starget,
940                                      int bflags, int lun0_res, int scsi_level,
941                                      int rescan)
942 {
943         unsigned int sparse_lun, lun, max_dev_lun;
944         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
945
946         SCSI_LOG_SCAN_BUS(3, printk(KERN_INFO "scsi scan: Sequential scan of"
947                                     "%s\n", starget->dev.bus_id));
948
949         max_dev_lun = min(max_scsi_luns, shost->max_lun);
950         /*
951          * If this device is known to support sparse multiple units,
952          * override the other settings, and scan all of them. Normally,
953          * SCSI-3 devices should be scanned via the REPORT LUNS.
954          */
955         if (bflags & BLIST_SPARSELUN) {
956                 max_dev_lun = shost->max_lun;
957                 sparse_lun = 1;
958         } else
959                 sparse_lun = 0;
960
961         /*
962          * If not sparse lun and no device attached at LUN 0 do not scan
963          * any further.
964          */
965         if (!sparse_lun && (lun0_res != SCSI_SCAN_LUN_PRESENT))
966                 return;
967
968         /*
969          * If less than SCSI_1_CSS, and no special lun scaning, stop
970          * scanning; this matches 2.4 behaviour, but could just be a bug
971          * (to continue scanning a SCSI_1_CSS device).
972          *
973          * This test is broken.  We might not have any device on lun0 for
974          * a sparselun device, and if that's the case then how would we
975          * know the real scsi_level, eh?  It might make sense to just not
976          * scan any SCSI_1 device for non-0 luns, but that check would best
977          * go into scsi_alloc_sdev() and just have it return null when asked
978          * to alloc an sdev for lun > 0 on an already found SCSI_1 device.
979          *
980         if ((sdevscan->scsi_level < SCSI_1_CCS) &&
981             ((bflags & (BLIST_FORCELUN | BLIST_SPARSELUN | BLIST_MAX5LUN))
982              == 0))
983                 return;
984          */
985         /*
986          * If this device is known to support multiple units, override
987          * the other settings, and scan all of them.
988          */
989         if (bflags & BLIST_FORCELUN)
990                 max_dev_lun = shost->max_lun;
991         /*
992          * REGAL CDC-4X: avoid hang after LUN 4
993          */
994         if (bflags & BLIST_MAX5LUN)
995                 max_dev_lun = min(5U, max_dev_lun);
996         /*
997          * Do not scan SCSI-2 or lower device past LUN 7, unless
998          * BLIST_LARGELUN.
999          */
1000         if (scsi_level < SCSI_3 && !(bflags & BLIST_LARGELUN))
1001                 max_dev_lun = min(8U, max_dev_lun);
1002
1003         /*
1004          * We have already scanned LUN 0, so start at LUN 1. Keep scanning
1005          * until we reach the max, or no LUN is found and we are not
1006          * sparse_lun.
1007          */
1008         for (lun = 1; lun < max_dev_lun; ++lun)
1009                 if ((scsi_probe_and_add_lun(starget, lun, NULL, NULL, rescan,
1010                                             NULL) != SCSI_SCAN_LUN_PRESENT) &&
1011                     !sparse_lun)
1012                         return;
1013 }
1014
1015 /**
1016  * scsilun_to_int: convert a scsi_lun to an int
1017  * @scsilun:    struct scsi_lun to be converted.
1018  *
1019  * Description:
1020  *     Convert @scsilun from a struct scsi_lun to a four byte host byte-ordered
1021  *     integer, and return the result. The caller must check for
1022  *     truncation before using this function.
1023  *
1024  * Notes:
1025  *     The struct scsi_lun is assumed to be four levels, with each level
1026  *     effectively containing a SCSI byte-ordered (big endian) short; the
1027  *     addressing bits of each level are ignored (the highest two bits).
1028  *     For a description of the LUN format, post SCSI-3 see the SCSI
1029  *     Architecture Model, for SCSI-3 see the SCSI Controller Commands.
1030  *
1031  *     Given a struct scsi_lun of: 0a 04 0b 03 00 00 00 00, this function returns
1032  *     the integer: 0x0b030a04
1033  **/
1034 static int scsilun_to_int(struct scsi_lun *scsilun)
1035 {
1036         int i;
1037         unsigned int lun;
1038
1039         lun = 0;
1040         for (i = 0; i < sizeof(lun); i += 2)
1041                 lun = lun | (((scsilun->scsi_lun[i] << 8) |
1042                               scsilun->scsi_lun[i + 1]) << (i * 8));
1043         return lun;
1044 }
1045
1046 /**
1047  * int_to_scsilun: reverts an int into a scsi_lun
1048  * @int:        integer to be reverted
1049  * @scsilun:    struct scsi_lun to be set.
1050  *
1051  * Description:
1052  *     Reverts the functionality of the scsilun_to_int, which packed
1053  *     an 8-byte lun value into an int. This routine unpacks the int
1054  *     back into the lun value.
1055  *     Note: the scsilun_to_int() routine does not truly handle all
1056  *     8bytes of the lun value. This functions restores only as much
1057  *     as was set by the routine.
1058  *
1059  * Notes:
1060  *     Given an integer : 0x0b030a04,  this function returns a
1061  *     scsi_lun of : struct scsi_lun of: 0a 04 0b 03 00 00 00 00
1062  *
1063  **/
1064 void int_to_scsilun(unsigned int lun, struct scsi_lun *scsilun)
1065 {
1066         int i;
1067
1068         memset(scsilun->scsi_lun, 0, sizeof(scsilun->scsi_lun));
1069
1070         for (i = 0; i < sizeof(lun); i += 2) {
1071                 scsilun->scsi_lun[i] = (lun >> 8) & 0xFF;
1072                 scsilun->scsi_lun[i+1] = lun & 0xFF;
1073                 lun = lun >> 16;
1074         }
1075 }
1076 EXPORT_SYMBOL(int_to_scsilun);
1077
1078 /**
1079  * scsi_report_lun_scan - Scan using SCSI REPORT LUN results
1080  * @sdevscan:   scan the host, channel, and id of this scsi_device
1081  *
1082  * Description:
1083  *     If @sdevscan is for a SCSI-3 or up device, send a REPORT LUN
1084  *     command, and scan the resulting list of LUNs by calling
1085  *     scsi_probe_and_add_lun.
1086  *
1087  *     Modifies sdevscan->lun.
1088  *
1089  * Return:
1090  *     0: scan completed (or no memory, so further scanning is futile)
1091  *     1: no report lun scan, or not configured
1092  **/
1093 static int scsi_report_lun_scan(struct scsi_target *starget, int bflags,
1094                                 int rescan)
1095 {
1096         char devname[64];
1097         unsigned char scsi_cmd[MAX_COMMAND_SIZE];
1098         unsigned int length;
1099         unsigned int lun;
1100         unsigned int num_luns;
1101         unsigned int retries;
1102         int result;
1103         struct scsi_lun *lunp, *lun_data;
1104         u8 *data;
1105         struct scsi_sense_hdr sshdr;
1106         struct scsi_device *sdev;
1107         struct Scsi_Host *shost = dev_to_shost(&starget->dev);
1108         int ret = 0;
1109
1110         /*
1111          * Only support SCSI-3 and up devices if BLIST_NOREPORTLUN is not set.
1112          * Also allow SCSI-2 if BLIST_REPORTLUN2 is set and host adapter does
1113          * support more than 8 LUNs.
1114          */
1115         if ((bflags & BLIST_NOREPORTLUN) || 
1116              starget->scsi_level < SCSI_2 ||
1117             (starget->scsi_level < SCSI_3 && 
1118              (!(bflags & BLIST_REPORTLUN2) || shost->max_lun <= 8)) )
1119                 return 1;
1120         if (bflags & BLIST_NOLUN)
1121                 return 0;
1122
1123         if (!(sdev = scsi_device_lookup_by_target(starget, 0))) {
1124                 sdev = scsi_alloc_sdev(starget, 0, NULL);
1125                 if (!sdev)
1126                         return 0;
1127                 if (scsi_device_get(sdev))
1128                         return 0;
1129         }
1130
1131         sprintf(devname, "host %d channel %d id %d",
1132                 shost->host_no, sdev->channel, sdev->id);
1133
1134         /*
1135          * Allocate enough to hold the header (the same size as one scsi_lun)
1136          * plus the max number of luns we are requesting.
1137          *
1138          * Reallocating and trying again (with the exact amount we need)
1139          * would be nice, but then we need to somehow limit the size
1140          * allocated based on the available memory and the limits of
1141          * kmalloc - we don't want a kmalloc() failure of a huge value to
1142          * prevent us from finding any LUNs on this target.
1143          */
1144         length = (max_scsi_report_luns + 1) * sizeof(struct scsi_lun);
1145         lun_data = kmalloc(length, GFP_ATOMIC |
1146                            (sdev->host->unchecked_isa_dma ? __GFP_DMA : 0));
1147         if (!lun_data) {
1148                 printk(ALLOC_FAILURE_MSG, __FUNCTION__);
1149                 goto out;
1150         }
1151
1152         scsi_cmd[0] = REPORT_LUNS;
1153
1154         /*
1155          * bytes 1 - 5: reserved, set to zero.
1156          */
1157         memset(&scsi_cmd[1], 0, 5);
1158
1159         /*
1160          * bytes 6 - 9: length of the command.
1161          */
1162         scsi_cmd[6] = (unsigned char) (length >> 24) & 0xff;
1163         scsi_cmd[7] = (unsigned char) (length >> 16) & 0xff;
1164         scsi_cmd[8] = (unsigned char) (length >> 8) & 0xff;
1165         scsi_cmd[9] = (unsigned char) length & 0xff;
1166
1167         scsi_cmd[10] = 0;       /* reserved */
1168         scsi_cmd[11] = 0;       /* control */
1169
1170         /*
1171          * We can get a UNIT ATTENTION, for example a power on/reset, so
1172          * retry a few times (like sd.c does for TEST UNIT READY).
1173          * Experience shows some combinations of adapter/devices get at
1174          * least two power on/resets.
1175          *
1176          * Illegal requests (for devices that do not support REPORT LUNS)
1177          * should come through as a check condition, and will not generate
1178          * a retry.
1179          */
1180         for (retries = 0; retries < 3; retries++) {
1181                 SCSI_LOG_SCAN_BUS(3, printk (KERN_INFO "scsi scan: Sending"
1182                                 " REPORT LUNS to %s (try %d)\n", devname,
1183                                 retries));
1184
1185                 result = scsi_execute_req(sdev, scsi_cmd, DMA_FROM_DEVICE,
1186                                           lun_data, length, &sshdr,
1187                                           SCSI_TIMEOUT + 4 * HZ, 3);
1188
1189                 SCSI_LOG_SCAN_BUS(3, printk (KERN_INFO "scsi scan: REPORT LUNS"
1190                                 " %s (try %d) result 0x%x\n", result
1191                                 ?  "failed" : "successful", retries, result));
1192                 if (result == 0)
1193                         break;
1194                 else if (scsi_sense_valid(&sshdr)) {
1195                         if (sshdr.sense_key != UNIT_ATTENTION)
1196                                 break;
1197                 }
1198         }
1199
1200         if (result) {
1201                 /*
1202                  * The device probably does not support a REPORT LUN command
1203                  */
1204                 ret = 1;
1205                 goto out_err;
1206         }
1207
1208         /*
1209          * Get the length from the first four bytes of lun_data.
1210          */
1211         data = (u8 *) lun_data->scsi_lun;
1212         length = ((data[0] << 24) | (data[1] << 16) |
1213                   (data[2] << 8) | (data[3] << 0));
1214
1215         num_luns = (length / sizeof(struct scsi_lun));
1216         if (num_luns > max_scsi_report_luns) {
1217                 printk(KERN_WARNING "scsi: On %s only %d (max_scsi_report_luns)"
1218                        " of %d luns reported, try increasing"
1219                        " max_scsi_report_luns.\n", devname,
1220                        max_scsi_report_luns, num_luns);
1221                 num_luns = max_scsi_report_luns;
1222         }
1223
1224         SCSI_LOG_SCAN_BUS(3, sdev_printk (KERN_INFO, sdev,
1225                 "scsi scan: REPORT LUN scan\n"));
1226
1227         /*
1228          * Scan the luns in lun_data. The entry at offset 0 is really
1229          * the header, so start at 1 and go up to and including num_luns.
1230          */
1231         for (lunp = &lun_data[1]; lunp <= &lun_data[num_luns]; lunp++) {
1232                 lun = scsilun_to_int(lunp);
1233
1234                 /*
1235                  * Check if the unused part of lunp is non-zero, and so
1236                  * does not fit in lun.
1237                  */
1238                 if (memcmp(&lunp->scsi_lun[sizeof(lun)], "\0\0\0\0", 4)) {
1239                         int i;
1240
1241                         /*
1242                          * Output an error displaying the LUN in byte order,
1243                          * this differs from what linux would print for the
1244                          * integer LUN value.
1245                          */
1246                         printk(KERN_WARNING "scsi: %s lun 0x", devname);
1247                         data = (char *)lunp->scsi_lun;
1248                         for (i = 0; i < sizeof(struct scsi_lun); i++)
1249                                 printk("%02x", data[i]);
1250                         printk(" has a LUN larger than currently supported.\n");
1251                 } else if (lun > sdev->host->max_lun) {
1252                         printk(KERN_WARNING "scsi: %s lun%d has a LUN larger"
1253                                " than allowed by the host adapter\n",
1254                                devname, lun);
1255                 } else {
1256                         int res;
1257
1258                         res = scsi_probe_and_add_lun(starget,
1259                                 lun, NULL, NULL, rescan, NULL);
1260                         if (res == SCSI_SCAN_NO_RESPONSE) {
1261                                 /*
1262                                  * Got some results, but now none, abort.
1263                                  */
1264                                 sdev_printk(KERN_ERR, sdev,
1265                                         "Unexpected response"
1266                                         " from lun %d while scanning, scan"
1267                                         " aborted\n", lun);
1268                                 break;
1269                         }
1270                 }
1271         }
1272
1273  out_err:
1274         kfree(lun_data);
1275  out:
1276         scsi_device_put(sdev);
1277         if (sdev->sdev_state == SDEV_CREATED)
1278                 /*
1279                  * the sdev we used didn't appear in the report luns scan
1280                  */
1281                 scsi_destroy_sdev(sdev);
1282         return ret;
1283 }
1284
1285 struct scsi_device *__scsi_add_device(struct Scsi_Host *shost, uint channel,
1286                                       uint id, uint lun, void *hostdata)
1287 {
1288         struct scsi_device *sdev = ERR_PTR(-ENODEV);
1289         struct device *parent = &shost->shost_gendev;
1290         struct scsi_target *starget;
1291
1292         starget = scsi_alloc_target(parent, channel, id);
1293         if (!starget)
1294                 return ERR_PTR(-ENOMEM);
1295
1296         get_device(&starget->dev);
1297         mutex_lock(&shost->scan_mutex);
1298         if (scsi_host_scan_allowed(shost))
1299                 scsi_probe_and_add_lun(starget, lun, NULL, &sdev, 1, hostdata);
1300         mutex_unlock(&shost->scan_mutex);
1301         scsi_target_reap(starget);
1302         put_device(&starget->dev);
1303
1304         return sdev;
1305 }
1306 EXPORT_SYMBOL(__scsi_add_device);
1307
1308 int scsi_add_device(struct Scsi_Host *host, uint channel,
1309                     uint target, uint lun)
1310 {
1311         struct scsi_device *sdev = 
1312                 __scsi_add_device(host, channel, target, lun, NULL);
1313         if (IS_ERR(sdev))
1314                 return PTR_ERR(sdev);
1315
1316         scsi_device_put(sdev);
1317         return 0;
1318 }
1319 EXPORT_SYMBOL(scsi_add_device);
1320
1321 void scsi_rescan_device(struct device *dev)
1322 {
1323         struct scsi_driver *drv;
1324         
1325         if (!dev->driver)
1326                 return;
1327
1328         drv = to_scsi_driver(dev->driver);
1329         if (try_module_get(drv->owner)) {
1330                 if (drv->rescan)
1331                         drv->rescan(dev);
1332                 module_put(drv->owner);
1333         }
1334 }
1335 EXPORT_SYMBOL(scsi_rescan_device);
1336
1337 static void __scsi_scan_target(struct device *parent, unsigned int channel,
1338                 unsigned int id, unsigned int lun, int rescan)
1339 {
1340         struct Scsi_Host *shost = dev_to_shost(parent);
1341         int bflags = 0;
1342         int res;
1343         struct scsi_target *starget;
1344
1345         if (shost->this_id == id)
1346                 /*
1347                  * Don't scan the host adapter
1348                  */
1349                 return;
1350
1351         starget = scsi_alloc_target(parent, channel, id);
1352         if (!starget)
1353                 return;
1354
1355         get_device(&starget->dev);
1356         if (lun != SCAN_WILD_CARD) {
1357                 /*
1358                  * Scan for a specific host/chan/id/lun.
1359                  */
1360                 scsi_probe_and_add_lun(starget, lun, NULL, NULL, rescan, NULL);
1361                 goto out_reap;
1362         }
1363
1364         /*
1365          * Scan LUN 0, if there is some response, scan further. Ideally, we
1366          * would not configure LUN 0 until all LUNs are scanned.
1367          */
1368         res = scsi_probe_and_add_lun(starget, 0, &bflags, NULL, rescan, NULL);
1369         if (res == SCSI_SCAN_LUN_PRESENT || res == SCSI_SCAN_TARGET_PRESENT) {
1370                 if (scsi_report_lun_scan(starget, bflags, rescan) != 0)
1371                         /*
1372                          * The REPORT LUN did not scan the target,
1373                          * do a sequential scan.
1374                          */
1375                         scsi_sequential_lun_scan(starget, bflags,
1376                                         res, starget->scsi_level, rescan);
1377         }
1378
1379  out_reap:
1380         /* now determine if the target has any children at all
1381          * and if not, nuke it */
1382         scsi_target_reap(starget);
1383
1384         put_device(&starget->dev);
1385 }
1386
1387 /**
1388  * scsi_scan_target - scan a target id, possibly including all LUNs on the
1389  *     target.
1390  * @parent:     host to scan
1391  * @channel:    channel to scan
1392  * @id:         target id to scan
1393  * @lun:        Specific LUN to scan or SCAN_WILD_CARD
1394  * @rescan:     passed to LUN scanning routines
1395  *
1396  * Description:
1397  *     Scan the target id on @parent, @channel, and @id. Scan at least LUN 0,
1398  *     and possibly all LUNs on the target id.
1399  *
1400  *     First try a REPORT LUN scan, if that does not scan the target, do a
1401  *     sequential scan of LUNs on the target id.
1402  **/
1403 void scsi_scan_target(struct device *parent, unsigned int channel,
1404                       unsigned int id, unsigned int lun, int rescan)
1405 {
1406         struct Scsi_Host *shost = dev_to_shost(parent);
1407
1408         mutex_lock(&shost->scan_mutex);
1409         if (scsi_host_scan_allowed(shost))
1410                 __scsi_scan_target(parent, channel, id, lun, rescan);
1411         mutex_unlock(&shost->scan_mutex);
1412 }
1413 EXPORT_SYMBOL(scsi_scan_target);
1414
1415 static void scsi_scan_channel(struct Scsi_Host *shost, unsigned int channel,
1416                               unsigned int id, unsigned int lun, int rescan)
1417 {
1418         uint order_id;
1419
1420         if (id == SCAN_WILD_CARD)
1421                 for (id = 0; id < shost->max_id; ++id) {
1422                         /*
1423                          * XXX adapter drivers when possible (FCP, iSCSI)
1424                          * could modify max_id to match the current max,
1425                          * not the absolute max.
1426                          *
1427                          * XXX add a shost id iterator, so for example,
1428                          * the FC ID can be the same as a target id
1429                          * without a huge overhead of sparse id's.
1430                          */
1431                         if (shost->reverse_ordering)
1432                                 /*
1433                                  * Scan from high to low id.
1434                                  */
1435                                 order_id = shost->max_id - id - 1;
1436                         else
1437                                 order_id = id;
1438                         __scsi_scan_target(&shost->shost_gendev, channel,
1439                                         order_id, lun, rescan);
1440                 }
1441         else
1442                 __scsi_scan_target(&shost->shost_gendev, channel,
1443                                 id, lun, rescan);
1444 }
1445
1446 int scsi_scan_host_selected(struct Scsi_Host *shost, unsigned int channel,
1447                             unsigned int id, unsigned int lun, int rescan)
1448 {
1449         SCSI_LOG_SCAN_BUS(3, shost_printk (KERN_INFO, shost,
1450                 "%s: <%u:%u:%u>\n",
1451                 __FUNCTION__, channel, id, lun));
1452
1453         if (((channel != SCAN_WILD_CARD) && (channel > shost->max_channel)) ||
1454             ((id != SCAN_WILD_CARD) && (id > shost->max_id)) ||
1455             ((lun != SCAN_WILD_CARD) && (lun > shost->max_lun)))
1456                 return -EINVAL;
1457
1458         mutex_lock(&shost->scan_mutex);
1459         if (scsi_host_scan_allowed(shost)) {
1460                 if (channel == SCAN_WILD_CARD)
1461                         for (channel = 0; channel <= shost->max_channel;
1462                              channel++)
1463                                 scsi_scan_channel(shost, channel, id, lun,
1464                                                   rescan);
1465                 else
1466                         scsi_scan_channel(shost, channel, id, lun, rescan);
1467         }
1468         mutex_unlock(&shost->scan_mutex);
1469
1470         return 0;
1471 }
1472
1473 /**
1474  * scsi_scan_host - scan the given adapter
1475  * @shost:      adapter to scan
1476  **/
1477 void scsi_scan_host(struct Scsi_Host *shost)
1478 {
1479         scsi_scan_host_selected(shost, SCAN_WILD_CARD, SCAN_WILD_CARD,
1480                                 SCAN_WILD_CARD, 0);
1481 }
1482 EXPORT_SYMBOL(scsi_scan_host);
1483
1484 void scsi_forget_host(struct Scsi_Host *shost)
1485 {
1486         struct scsi_device *sdev;
1487         unsigned long flags;
1488
1489  restart:
1490         spin_lock_irqsave(shost->host_lock, flags);
1491         list_for_each_entry(sdev, &shost->__devices, siblings) {
1492                 if (sdev->sdev_state == SDEV_DEL)
1493                         continue;
1494                 spin_unlock_irqrestore(shost->host_lock, flags);
1495                 __scsi_remove_device(sdev);
1496                 goto restart;
1497         }
1498         spin_unlock_irqrestore(shost->host_lock, flags);
1499 }
1500
1501 /*
1502  * Function:    scsi_get_host_dev()
1503  *
1504  * Purpose:     Create a scsi_device that points to the host adapter itself.
1505  *
1506  * Arguments:   SHpnt   - Host that needs a scsi_device
1507  *
1508  * Lock status: None assumed.
1509  *
1510  * Returns:     The scsi_device or NULL
1511  *
1512  * Notes:
1513  *      Attach a single scsi_device to the Scsi_Host - this should
1514  *      be made to look like a "pseudo-device" that points to the
1515  *      HA itself.
1516  *
1517  *      Note - this device is not accessible from any high-level
1518  *      drivers (including generics), which is probably not
1519  *      optimal.  We can add hooks later to attach 
1520  */
1521 struct scsi_device *scsi_get_host_dev(struct Scsi_Host *shost)
1522 {
1523         struct scsi_device *sdev = NULL;
1524         struct scsi_target *starget;
1525
1526         mutex_lock(&shost->scan_mutex);
1527         if (!scsi_host_scan_allowed(shost))
1528                 goto out;
1529         starget = scsi_alloc_target(&shost->shost_gendev, 0, shost->this_id);
1530         if (!starget)
1531                 goto out;
1532
1533         sdev = scsi_alloc_sdev(starget, 0, NULL);
1534         if (sdev) {
1535                 sdev->sdev_gendev.parent = get_device(&starget->dev);
1536                 sdev->borken = 0;
1537         }
1538         put_device(&starget->dev);
1539  out:
1540         mutex_unlock(&shost->scan_mutex);
1541         return sdev;
1542 }
1543 EXPORT_SYMBOL(scsi_get_host_dev);
1544
1545 /*
1546  * Function:    scsi_free_host_dev()
1547  *
1548  * Purpose:     Free a scsi_device that points to the host adapter itself.
1549  *
1550  * Arguments:   SHpnt   - Host that needs a scsi_device
1551  *
1552  * Lock status: None assumed.
1553  *
1554  * Returns:     Nothing
1555  *
1556  * Notes:
1557  */
1558 void scsi_free_host_dev(struct scsi_device *sdev)
1559 {
1560         BUG_ON(sdev->id != sdev->host->this_id);
1561
1562         scsi_destroy_sdev(sdev);
1563 }
1564 EXPORT_SYMBOL(scsi_free_host_dev);
1565