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