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