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