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