ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / scsi / sd.c
1 /*
2  *      sd.c Copyright (C) 1992 Drew Eckhardt
3  *           Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
4  *
5  *      Linux scsi disk driver
6  *              Initial versions: Drew Eckhardt
7  *              Subsequent revisions: Eric Youngdale
8  *      Modification history:
9  *       - Drew Eckhardt <drew@colorado.edu> original
10  *       - Eric Youngdale <eric@andante.org> add scatter-gather, multiple 
11  *         outstanding request, and other enhancements.
12  *         Support loadable low-level scsi drivers.
13  *       - Jirka Hanika <geo@ff.cuni.cz> support more scsi disks using 
14  *         eight major numbers.
15  *       - Richard Gooch <rgooch@atnf.csiro.au> support devfs.
16  *       - Torben Mathiasen <tmm@image.dk> Resource allocation fixes in 
17  *         sd_init and cleanups.
18  *       - Alex Davis <letmein@erols.com> Fix problem where partition info
19  *         not being read in sd_open. Fix problem where removable media 
20  *         could be ejected after sd_open.
21  *       - Douglas Gilbert <dgilbert@interlog.com> cleanup for lk 2.5.x
22  *       - Badari Pulavarty <pbadari@us.ibm.com>, Matthew Wilcox 
23  *         <willy@debian.org>, Kurt Garloff <garloff@suse.de>: 
24  *         Support 32k/1M disks.
25  *
26  *      Logging policy (needs CONFIG_SCSI_LOGGING defined):
27  *       - setting up transfer: SCSI_LOG_HLQUEUE levels 1 and 2
28  *       - end of transfer (bh + scsi_lib): SCSI_LOG_HLCOMPLETE level 1
29  *       - entering sd_ioctl: SCSI_LOG_IOCTL level 1
30  *       - entering other commands: SCSI_LOG_HLQUEUE level 3
31  *      Note: when the logging level is set by the user, it must be greater
32  *      than the level indicated above to trigger output.       
33  */
34
35 #include <linux/config.h>
36 #include <linux/module.h>
37 #include <linux/fs.h>
38 #include <linux/kernel.h>
39 #include <linux/sched.h>
40 #include <linux/mm.h>
41 #include <linux/bio.h>
42 #include <linux/genhd.h>
43 #include <linux/hdreg.h>
44 #include <linux/errno.h>
45 #include <linux/interrupt.h>
46 #include <linux/init.h>
47 #include <linux/reboot.h>
48 #include <linux/vmalloc.h>
49 #include <linux/blkdev.h>
50 #include <linux/blkpg.h>
51 #include <linux/kref.h>
52 #include <asm/uaccess.h>
53
54 #include "scsi.h"
55 #include "hosts.h"
56
57 #include <scsi/scsi_driver.h>
58 #include <scsi/scsi_ioctl.h>
59 #include <scsi/scsicam.h>
60
61 #include "scsi_logging.h"
62
63
64 /*
65  * Remaining dev_t-handling stuff
66  */
67 #define SD_MAJORS       16
68 #define SD_DISKS        32768   /* anything between 256 and 262144 */
69
70 /*
71  * Time out in seconds for disks and Magneto-opticals (which are slower).
72  */
73 #define SD_TIMEOUT              (30 * HZ)
74 #define SD_MOD_TIMEOUT          (75 * HZ)
75
76 /*
77  * Number of allowed retries
78  */
79 #define SD_MAX_RETRIES          5
80
81 static void scsi_disk_release(struct kref *kref);
82
83 struct scsi_disk {
84         struct scsi_driver *driver;     /* always &sd_template */
85         struct scsi_device *device;
86         struct kref     kref;
87         struct gendisk  *disk;
88         unsigned int    openers;        /* protected by BKL for now, yuck */
89         sector_t        capacity;       /* size in 512-byte sectors */
90         u32             index;
91         u8              media_present;
92         u8              write_prot;
93         unsigned        WCE : 1;        /* state of disk WCE bit */
94         unsigned        RCD : 1;        /* state of disk RCD bit, unused */
95 };
96
97
98 static unsigned long sd_index_bits[SD_DISKS / BITS_PER_LONG];
99 static spinlock_t sd_index_lock = SPIN_LOCK_UNLOCKED;
100
101 /* This semaphore is used to mediate the 0->1 reference get in the
102  * face of object destruction (i.e. we can't allow a get on an
103  * object after last put) */
104 static DECLARE_MUTEX(sd_ref_sem);
105
106 static int sd_revalidate_disk(struct gendisk *disk);
107 static void sd_rw_intr(struct scsi_cmnd * SCpnt);
108
109 static int sd_probe(struct device *);
110 static int sd_remove(struct device *);
111 static void sd_shutdown(struct device *dev);
112 static void sd_rescan(struct device *);
113 static int sd_init_command(struct scsi_cmnd *);
114 static void sd_read_capacity(struct scsi_disk *sdkp, char *diskname,
115                  struct scsi_request *SRpnt, unsigned char *buffer);
116
117 static struct scsi_driver sd_template = {
118         .owner                  = THIS_MODULE,
119         .gendrv = {
120                 .name           = "sd",
121                 .probe          = sd_probe,
122                 .remove         = sd_remove,
123                 .shutdown       = sd_shutdown,
124         },
125         .rescan                 = sd_rescan,
126         .init_command           = sd_init_command,
127 };
128
129 /* Device no to disk mapping:
130  * 
131  *       major         disc2     disc  p1
132  *   |............|.............|....|....| <- dev_t
133  *    31        20 19          8 7  4 3  0
134  * 
135  * Inside a major, we have 16k disks, however mapped non-
136  * contiguously. The first 16 disks are for major0, the next
137  * ones with major1, ... Disk 256 is for major0 again, disk 272 
138  * for major1, ... 
139  * As we stay compatible with our numbering scheme, we can reuse 
140  * the well-know SCSI majors 8, 65--71, 136--143.
141  */
142
143 static int sd_major(int major_idx)
144 {
145         switch (major_idx) {
146         case 0:
147                 return SCSI_DISK0_MAJOR;
148         case 1 ... 7:
149                 return SCSI_DISK1_MAJOR + major_idx - 1;
150         case 8 ... 15:
151                 return SCSI_DISK8_MAJOR + major_idx - 8;
152         default:
153                 BUG();
154                 return 0;       /* shut up gcc */
155         }
156 }
157
158 static unsigned int make_sd_dev(unsigned int sd_nr, unsigned int part)
159 {
160         return  (part & 0xf) | ((sd_nr & 0xf) << 4) |
161                 (sd_major((sd_nr & 0xf0) >> 4) << 20) | (sd_nr & 0xfff00);
162 }
163
164 /* reverse mapping dev -> (sd_nr, part) not currently needed */
165
166 #define to_scsi_disk(obj) container_of(obj,struct scsi_disk,kref)
167
168 static inline struct scsi_disk *scsi_disk(struct gendisk *disk)
169 {
170         return container_of(disk->private_data, struct scsi_disk, driver);
171 }
172
173 static struct scsi_disk *scsi_disk_get(struct gendisk *disk)
174 {
175         struct scsi_disk *sdkp = NULL;
176
177         down(&sd_ref_sem);
178         if (disk->private_data == NULL)
179                 goto out;
180         sdkp = scsi_disk(disk);
181         if (!kref_get(&sdkp->kref))
182                 sdkp = NULL;
183  out:
184         up(&sd_ref_sem);
185         return sdkp;
186 }
187
188 static void scsi_disk_put(struct scsi_disk *sdkp)
189 {
190         down(&sd_ref_sem);
191         kref_put(&sdkp->kref);
192         up(&sd_ref_sem);
193 }
194
195 /**
196  *      sd_init_command - build a scsi (read or write) command from
197  *      information in the request structure.
198  *      @SCpnt: pointer to mid-level's per scsi command structure that
199  *      contains request and into which the scsi command is written
200  *
201  *      Returns 1 if successful and 0 if error (or cannot be done now).
202  **/
203 static int sd_init_command(struct scsi_cmnd * SCpnt)
204 {
205         unsigned int this_count, timeout;
206         struct gendisk *disk;
207         sector_t block;
208         struct scsi_device *sdp = SCpnt->device;
209
210         timeout = SD_TIMEOUT;
211         if (SCpnt->device->type != TYPE_DISK)
212                 timeout = SD_MOD_TIMEOUT;
213
214         /*
215          * these are already setup, just copy cdb basically
216          */
217         if (SCpnt->request->flags & REQ_BLOCK_PC) {
218                 struct request *rq = SCpnt->request;
219
220                 if (sizeof(rq->cmd) > sizeof(SCpnt->cmnd))
221                         return 0;
222
223                 memcpy(SCpnt->cmnd, rq->cmd, sizeof(SCpnt->cmnd));
224                 if (rq_data_dir(rq) == WRITE)
225                         SCpnt->sc_data_direction = DMA_TO_DEVICE;
226                 else if (rq->data_len)
227                         SCpnt->sc_data_direction = DMA_FROM_DEVICE;
228                 else
229                         SCpnt->sc_data_direction = DMA_NONE;
230
231                 this_count = rq->data_len;
232                 if (rq->timeout)
233                         timeout = rq->timeout;
234
235                 SCpnt->transfersize = rq->data_len;
236                 goto queue;
237         }
238
239         /*
240          * we only do REQ_CMD and REQ_BLOCK_PC
241          */
242         if (!(SCpnt->request->flags & REQ_CMD))
243                 return 0;
244
245         disk = SCpnt->request->rq_disk;
246         block = SCpnt->request->sector;
247         this_count = SCpnt->request_bufflen >> 9;
248
249         SCSI_LOG_HLQUEUE(1, printk("sd_init_command: disk=%s, block=%llu, "
250                             "count=%d\n", disk->disk_name, (unsigned long long)block, this_count));
251
252         if (!sdp || !scsi_device_online(sdp) ||
253             block + SCpnt->request->nr_sectors > get_capacity(disk)) {
254                 SCSI_LOG_HLQUEUE(2, printk("Finishing %ld sectors\n", 
255                                  SCpnt->request->nr_sectors));
256                 SCSI_LOG_HLQUEUE(2, printk("Retry with 0x%p\n", SCpnt));
257                 return 0;
258         }
259
260         if (sdp->changed) {
261                 /*
262                  * quietly refuse to do anything to a changed disc until 
263                  * the changed bit has been reset
264                  */
265                 /* printk("SCSI disk has been changed. Prohibiting further I/O.\n"); */
266                 return 0;
267         }
268         SCSI_LOG_HLQUEUE(2, printk("%s : block=%llu\n",
269                                    disk->disk_name, (unsigned long long)block));
270
271         /*
272          * If we have a 1K hardware sectorsize, prevent access to single
273          * 512 byte sectors.  In theory we could handle this - in fact
274          * the scsi cdrom driver must be able to handle this because
275          * we typically use 1K blocksizes, and cdroms typically have
276          * 2K hardware sectorsizes.  Of course, things are simpler
277          * with the cdrom, since it is read-only.  For performance
278          * reasons, the filesystems should be able to handle this
279          * and not force the scsi disk driver to use bounce buffers
280          * for this.
281          */
282         if (sdp->sector_size == 1024) {
283                 if ((block & 1) || (SCpnt->request->nr_sectors & 1)) {
284                         printk(KERN_ERR "sd: Bad block number requested");
285                         return 0;
286                 } else {
287                         block = block >> 1;
288                         this_count = this_count >> 1;
289                 }
290         }
291         if (sdp->sector_size == 2048) {
292                 if ((block & 3) || (SCpnt->request->nr_sectors & 3)) {
293                         printk(KERN_ERR "sd: Bad block number requested");
294                         return 0;
295                 } else {
296                         block = block >> 2;
297                         this_count = this_count >> 2;
298                 }
299         }
300         if (sdp->sector_size == 4096) {
301                 if ((block & 7) || (SCpnt->request->nr_sectors & 7)) {
302                         printk(KERN_ERR "sd: Bad block number requested");
303                         return 0;
304                 } else {
305                         block = block >> 3;
306                         this_count = this_count >> 3;
307                 }
308         }
309         if (rq_data_dir(SCpnt->request) == WRITE) {
310                 if (!sdp->writeable) {
311                         return 0;
312                 }
313                 SCpnt->cmnd[0] = WRITE_6;
314                 SCpnt->sc_data_direction = DMA_TO_DEVICE;
315         } else if (rq_data_dir(SCpnt->request) == READ) {
316                 SCpnt->cmnd[0] = READ_6;
317                 SCpnt->sc_data_direction = DMA_FROM_DEVICE;
318         } else {
319                 printk(KERN_ERR "sd: Unknown command %lx\n", 
320                        SCpnt->request->flags);
321 /* overkill     panic("Unknown sd command %lx\n", SCpnt->request->flags); */
322                 return 0;
323         }
324
325         SCSI_LOG_HLQUEUE(2, printk("%s : %s %d/%ld 512 byte blocks.\n", 
326                 disk->disk_name, (rq_data_dir(SCpnt->request) == WRITE) ? 
327                 "writing" : "reading", this_count, SCpnt->request->nr_sectors));
328
329         SCpnt->cmnd[1] = 0;
330         
331         if (block > 0xffffffff) {
332                 SCpnt->cmnd[0] += READ_16 - READ_6;
333                 SCpnt->cmnd[2] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
334                 SCpnt->cmnd[3] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
335                 SCpnt->cmnd[4] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
336                 SCpnt->cmnd[5] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
337                 SCpnt->cmnd[6] = (unsigned char) (block >> 24) & 0xff;
338                 SCpnt->cmnd[7] = (unsigned char) (block >> 16) & 0xff;
339                 SCpnt->cmnd[8] = (unsigned char) (block >> 8) & 0xff;
340                 SCpnt->cmnd[9] = (unsigned char) block & 0xff;
341                 SCpnt->cmnd[10] = (unsigned char) (this_count >> 24) & 0xff;
342                 SCpnt->cmnd[11] = (unsigned char) (this_count >> 16) & 0xff;
343                 SCpnt->cmnd[12] = (unsigned char) (this_count >> 8) & 0xff;
344                 SCpnt->cmnd[13] = (unsigned char) this_count & 0xff;
345                 SCpnt->cmnd[14] = SCpnt->cmnd[15] = 0;
346         } else if ((this_count > 0xff) || (block > 0x1fffff) ||
347                    SCpnt->device->use_10_for_rw) {
348                 if (this_count > 0xffff)
349                         this_count = 0xffff;
350
351                 SCpnt->cmnd[0] += READ_10 - READ_6;
352                 SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
353                 SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
354                 SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
355                 SCpnt->cmnd[5] = (unsigned char) block & 0xff;
356                 SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
357                 SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
358                 SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
359         } else {
360                 if (this_count > 0xff)
361                         this_count = 0xff;
362
363                 SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f);
364                 SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff);
365                 SCpnt->cmnd[3] = (unsigned char) block & 0xff;
366                 SCpnt->cmnd[4] = (unsigned char) this_count;
367                 SCpnt->cmnd[5] = 0;
368         }
369         SCpnt->request_bufflen = SCpnt->bufflen =
370                         this_count * sdp->sector_size;
371
372         /*
373          * We shouldn't disconnect in the middle of a sector, so with a dumb
374          * host adapter, it's safe to assume that we can at least transfer
375          * this many bytes between each connect / disconnect.
376          */
377         SCpnt->transfersize = sdp->sector_size;
378         SCpnt->underflow = this_count << 9;
379
380 queue:
381         SCpnt->allowed = SD_MAX_RETRIES;
382         SCpnt->timeout_per_command = timeout;
383
384         /*
385          * This is the completion routine we use.  This is matched in terms
386          * of capability to this function.
387          */
388         SCpnt->done = sd_rw_intr;
389
390         /*
391          * This indicates that the command is ready from our end to be
392          * queued.
393          */
394         return 1;
395 }
396
397 /**
398  *      sd_open - open a scsi disk device
399  *      @inode: only i_rdev member may be used
400  *      @filp: only f_mode and f_flags may be used
401  *
402  *      Returns 0 if successful. Returns a negated errno value in case 
403  *      of error.
404  *
405  *      Note: This can be called from a user context (e.g. fsck(1) )
406  *      or from within the kernel (e.g. as a result of a mount(1) ).
407  *      In the latter case @inode and @filp carry an abridged amount
408  *      of information as noted above.
409  **/
410 static int sd_open(struct inode *inode, struct file *filp)
411 {
412         struct gendisk *disk = inode->i_bdev->bd_disk;
413         struct scsi_disk *sdkp;
414         struct scsi_device *sdev;
415         int retval;
416
417         if (!(sdkp = scsi_disk_get(disk)))
418                 return -ENXIO;
419
420
421         SCSI_LOG_HLQUEUE(3, printk("sd_open: disk=%s\n", disk->disk_name));
422
423         sdev = sdkp->device;
424
425         /*
426          * If the device is in error recovery, wait until it is done.
427          * If the device is offline, then disallow any access to it.
428          */
429         retval = -ENXIO;
430         if (!scsi_block_when_processing_errors(sdev))
431                 goto error_out;
432
433         if (sdev->removable || sdkp->write_prot)
434                 check_disk_change(inode->i_bdev);
435
436         /*
437          * If the drive is empty, just let the open fail.
438          */
439         retval = -ENOMEDIUM;
440         if (sdev->removable && !sdkp->media_present &&
441             !(filp->f_flags & O_NDELAY))
442                 goto error_out;
443
444         /*
445          * If the device has the write protect tab set, have the open fail
446          * if the user expects to be able to write to the thing.
447          */
448         retval = -EROFS;
449         if (sdkp->write_prot && (filp->f_mode & FMODE_WRITE))
450                 goto error_out;
451
452         /*
453          * It is possible that the disk changing stuff resulted in
454          * the device being taken offline.  If this is the case,
455          * report this to the user, and don't pretend that the
456          * open actually succeeded.
457          */
458         retval = -ENXIO;
459         if (!scsi_device_online(sdev))
460                 goto error_out;
461
462         if (!sdkp->openers++ && sdev->removable) {
463                 if (scsi_block_when_processing_errors(sdev))
464                         scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
465         }
466
467         return 0;
468
469 error_out:
470         scsi_disk_put(sdkp);
471         return retval;  
472 }
473
474 /**
475  *      sd_release - invoked when the (last) close(2) is called on this
476  *      scsi disk.
477  *      @inode: only i_rdev member may be used
478  *      @filp: only f_mode and f_flags may be used
479  *
480  *      Returns 0. 
481  *
482  *      Note: may block (uninterruptible) if error recovery is underway
483  *      on this disk.
484  **/
485 static int sd_release(struct inode *inode, struct file *filp)
486 {
487         struct gendisk *disk = inode->i_bdev->bd_disk;
488         struct scsi_disk *sdkp = scsi_disk(disk);
489         struct scsi_device *sdev = sdkp->device;
490
491         SCSI_LOG_HLQUEUE(3, printk("sd_release: disk=%s\n", disk->disk_name));
492
493         if (!--sdkp->openers && sdev->removable) {
494                 if (scsi_block_when_processing_errors(sdev))
495                         scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
496         }
497
498         /*
499          * XXX and what if there are packets in flight and this close()
500          * XXX is followed by a "rmmod sd_mod"?
501          */
502         scsi_disk_put(sdkp);
503         return 0;
504 }
505
506 static int sd_hdio_getgeo(struct block_device *bdev, struct hd_geometry *loc)
507 {
508         struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
509         struct scsi_device *sdp = sdkp->device;
510         struct Scsi_Host *host = sdp->host;
511         int diskinfo[4];
512
513         /* default to most commonly used values */
514         diskinfo[0] = 0x40;     /* 1 << 6 */
515         diskinfo[1] = 0x20;     /* 1 << 5 */
516         diskinfo[2] = sdkp->capacity >> 11;
517         
518         /* override with calculated, extended default, or driver values */
519         if (host->hostt->bios_param)
520                 host->hostt->bios_param(sdp, bdev, sdkp->capacity, diskinfo);
521         else
522                 scsicam_bios_param(bdev, sdkp->capacity, diskinfo);
523
524         if (put_user(diskinfo[0], &loc->heads))
525                 return -EFAULT;
526         if (put_user(diskinfo[1], &loc->sectors))
527                 return -EFAULT;
528         if (put_user(diskinfo[2], &loc->cylinders))
529                 return -EFAULT;
530         if (put_user((unsigned)get_start_sect(bdev),
531                      (unsigned long *)&loc->start))
532                 return -EFAULT;
533         return 0;
534 }
535
536 /**
537  *      sd_ioctl - process an ioctl
538  *      @inode: only i_rdev/i_bdev members may be used
539  *      @filp: only f_mode and f_flags may be used
540  *      @cmd: ioctl command number
541  *      @arg: this is third argument given to ioctl(2) system call.
542  *      Often contains a pointer.
543  *
544  *      Returns 0 if successful (some ioctls return postive numbers on
545  *      success as well). Returns a negated errno value in case of error.
546  *
547  *      Note: most ioctls are forward onto the block subsystem or further
548  *      down in the scsi subsytem.
549  **/
550 static int sd_ioctl(struct inode * inode, struct file * filp, 
551                     unsigned int cmd, unsigned long arg)
552 {
553         struct block_device *bdev = inode->i_bdev;
554         struct gendisk *disk = bdev->bd_disk;
555         struct scsi_device *sdp = scsi_disk(disk)->device;
556         int error;
557     
558         SCSI_LOG_IOCTL(1, printk("sd_ioctl: disk=%s, cmd=0x%x\n",
559                                                 disk->disk_name, cmd));
560
561         /*
562          * If we are in the middle of error recovery, don't let anyone
563          * else try and use this device.  Also, if error recovery fails, it
564          * may try and take the device offline, in which case all further
565          * access to the device is prohibited.
566          */
567         if (!scsi_block_when_processing_errors(sdp))
568                 return -ENODEV;
569
570         if (cmd == HDIO_GETGEO) {
571                 if (!arg)
572                         return -EINVAL;
573                 return sd_hdio_getgeo(bdev, (struct hd_geometry *)arg);
574         }
575
576         /*
577          * Send SCSI addressing ioctls directly to mid level, send other
578          * ioctls to block level and then onto mid level if they can't be
579          * resolved.
580          */
581         switch (cmd) {
582                 case SCSI_IOCTL_GET_IDLUN:
583                 case SCSI_IOCTL_GET_BUS_NUMBER:
584                         return scsi_ioctl(sdp, cmd, (void *)arg);
585                 default:
586                         error = scsi_cmd_ioctl(disk, cmd, arg);
587                         if (error != -ENOTTY)
588                                 return error;
589         }
590         return scsi_ioctl(sdp, cmd, (void *)arg);
591 }
592
593 static void set_media_not_present(struct scsi_disk *sdkp)
594 {
595         sdkp->media_present = 0;
596         sdkp->capacity = 0;
597         sdkp->device->changed = 1;
598 }
599
600 /**
601  *      sd_media_changed - check if our medium changed
602  *      @disk: kernel device descriptor 
603  *
604  *      Returns 0 if not applicable or no change; 1 if change
605  *
606  *      Note: this function is invoked from the block subsystem.
607  **/
608 static int sd_media_changed(struct gendisk *disk)
609 {
610         struct scsi_disk *sdkp = scsi_disk(disk);
611         struct scsi_device *sdp = sdkp->device;
612         int retval;
613
614         SCSI_LOG_HLQUEUE(3, printk("sd_media_changed: disk=%s\n",
615                                                 disk->disk_name));
616
617         if (!sdp->removable)
618                 return 0;
619
620         /*
621          * If the device is offline, don't send any commands - just pretend as
622          * if the command failed.  If the device ever comes back online, we
623          * can deal with it then.  It is only because of unrecoverable errors
624          * that we would ever take a device offline in the first place.
625          */
626         if (!scsi_device_online(sdp))
627                 goto not_present;
628
629         /*
630          * Using TEST_UNIT_READY enables differentiation between drive with
631          * no cartridge loaded - NOT READY, drive with changed cartridge -
632          * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
633          *
634          * Drives that auto spin down. eg iomega jaz 1G, will be started
635          * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
636          * sd_revalidate() is called.
637          */
638         retval = -ENODEV;
639         if (scsi_block_when_processing_errors(sdp))
640                 retval = scsi_ioctl(sdp, SCSI_IOCTL_TEST_UNIT_READY, NULL);
641
642         /*
643          * Unable to test, unit probably not ready.   This usually
644          * means there is no disc in the drive.  Mark as changed,
645          * and we will figure it out later once the drive is
646          * available again.
647          */
648         if (retval)
649                  goto not_present;
650
651         /*
652          * For removable scsi disk we have to recognise the presence
653          * of a disk in the drive. This is kept in the struct scsi_disk
654          * struct and tested at open !  Daniel Roche (dan@lectra.fr)
655          */
656         sdkp->media_present = 1;
657
658         retval = sdp->changed;
659         sdp->changed = 0;
660
661         return retval;
662
663 not_present:
664         set_media_not_present(sdkp);
665         return 1;
666 }
667
668 static void sd_rescan(struct device *dev)
669 {
670         struct scsi_disk *sdkp = dev_get_drvdata(dev);
671         sd_revalidate_disk(sdkp->disk);
672 }
673
674 static struct block_device_operations sd_fops = {
675         .owner                  = THIS_MODULE,
676         .open                   = sd_open,
677         .release                = sd_release,
678         .ioctl                  = sd_ioctl,
679         .media_changed          = sd_media_changed,
680         .revalidate_disk        = sd_revalidate_disk,
681 };
682
683 /**
684  *      sd_rw_intr - bottom half handler: called when the lower level
685  *      driver has completed (successfully or otherwise) a scsi command.
686  *      @SCpnt: mid-level's per command structure.
687  *
688  *      Note: potentially run from within an ISR. Must not block.
689  **/
690 static void sd_rw_intr(struct scsi_cmnd * SCpnt)
691 {
692         int result = SCpnt->result;
693         int this_count = SCpnt->bufflen;
694         int good_bytes = (result == 0 ? this_count : 0);
695         sector_t block_sectors = 1;
696         sector_t error_sector;
697 #ifdef CONFIG_SCSI_LOGGING
698         SCSI_LOG_HLCOMPLETE(1, printk("sd_rw_intr: %s: res=0x%x\n", 
699                                 SCpnt->request->rq_disk->disk_name, result));
700         if (0 != result) {
701                 SCSI_LOG_HLCOMPLETE(1, printk("sd_rw_intr: sb[0,2,asc,ascq]"
702                                 "=%x,%x,%x,%x\n", SCpnt->sense_buffer[0],
703                         SCpnt->sense_buffer[2], SCpnt->sense_buffer[12],
704                         SCpnt->sense_buffer[13]));
705         }
706 #endif
707         /*
708            Handle MEDIUM ERRORs that indicate partial success.  Since this is a
709            relatively rare error condition, no care is taken to avoid
710            unnecessary additional work such as memcpy's that could be avoided.
711          */
712
713         /* An error occurred */
714         if (driver_byte(result) != 0 &&         /* An error occurred */
715             (SCpnt->sense_buffer[0] & 0x7f) == 0x70) { /* Sense current */
716                 switch (SCpnt->sense_buffer[2]) {
717                 case MEDIUM_ERROR:
718                         if (!(SCpnt->sense_buffer[0] & 0x80))
719                                 break;
720                         if (!blk_fs_request(SCpnt->request))
721                                 break;
722                         error_sector = (SCpnt->sense_buffer[3] << 24) |
723                         (SCpnt->sense_buffer[4] << 16) |
724                         (SCpnt->sense_buffer[5] << 8) |
725                         SCpnt->sense_buffer[6];
726                         if (SCpnt->request->bio != NULL)
727                                 block_sectors = bio_sectors(SCpnt->request->bio);
728                         switch (SCpnt->device->sector_size) {
729                         case 1024:
730                                 error_sector <<= 1;
731                                 if (block_sectors < 2)
732                                         block_sectors = 2;
733                                 break;
734                         case 2048:
735                                 error_sector <<= 2;
736                                 if (block_sectors < 4)
737                                         block_sectors = 4;
738                                 break;
739                         case 4096:
740                                 error_sector <<=3;
741                                 if (block_sectors < 8)
742                                         block_sectors = 8;
743                                 break;
744                         case 256:
745                                 error_sector >>= 1;
746                                 break;
747                         default:
748                                 break;
749                         }
750
751                         error_sector &= ~(block_sectors - 1);
752                         good_bytes = (error_sector - SCpnt->request->sector) << 9;
753                         if (good_bytes < 0 || good_bytes >= this_count)
754                                 good_bytes = 0;
755                         break;
756
757                 case RECOVERED_ERROR:
758                         /*
759                          * An error occurred, but it recovered.  Inform the
760                          * user, but make sure that it's not treated as a
761                          * hard error.
762                          */
763                         print_sense("sd", SCpnt);
764                         SCpnt->result = 0;
765                         SCpnt->sense_buffer[0] = 0x0;
766                         good_bytes = this_count;
767                         break;
768
769                 case ILLEGAL_REQUEST:
770                         if (SCpnt->device->use_10_for_rw &&
771                             (SCpnt->cmnd[0] == READ_10 ||
772                              SCpnt->cmnd[0] == WRITE_10))
773                                 SCpnt->device->use_10_for_rw = 0;
774                         if (SCpnt->device->use_10_for_ms &&
775                             (SCpnt->cmnd[0] == MODE_SENSE_10 ||
776                              SCpnt->cmnd[0] == MODE_SELECT_10))
777                                 SCpnt->device->use_10_for_ms = 0;
778                         break;
779
780                 default:
781                         break;
782                 }
783         }
784         /*
785          * This calls the generic completion function, now that we know
786          * how many actual sectors finished, and how many sectors we need
787          * to say have failed.
788          */
789         scsi_io_completion(SCpnt, good_bytes, block_sectors << 9);
790 }
791
792 static int media_not_present(struct scsi_disk *sdkp, struct scsi_request *srp)
793 {
794         if (!srp->sr_result)
795                 return 0;
796         if (!(driver_byte(srp->sr_result) & DRIVER_SENSE))
797                 return 0;
798         if (srp->sr_sense_buffer[2] != NOT_READY &&
799             srp->sr_sense_buffer[2] != UNIT_ATTENTION)
800                 return 0;
801         if (srp->sr_sense_buffer[12] != 0x3A) /* medium not present */
802                 return 0;
803
804         set_media_not_present(sdkp);
805         return 1;
806 }
807
808 /*
809  * spinup disk - called only in sd_revalidate_disk()
810  */
811 static void
812 sd_spinup_disk(struct scsi_disk *sdkp, char *diskname,
813                struct scsi_request *SRpnt, unsigned char *buffer) {
814         unsigned char cmd[10];
815         unsigned long spintime_value = 0;
816         int retries, spintime;
817         unsigned int the_result;
818
819         spintime = 0;
820
821         /* Spin up drives, as required.  Only do this at boot time */
822         /* Spinup needs to be done for module loads too. */
823         do {
824                 retries = 0;
825
826                 do {
827                         cmd[0] = TEST_UNIT_READY;
828                         memset((void *) &cmd[1], 0, 9);
829
830                         SRpnt->sr_cmd_len = 0;
831                         SRpnt->sr_sense_buffer[0] = 0;
832                         SRpnt->sr_sense_buffer[2] = 0;
833                         SRpnt->sr_data_direction = DMA_NONE;
834
835                         scsi_wait_req (SRpnt, (void *) cmd, (void *) buffer,
836                                        0/*512*/, SD_TIMEOUT, SD_MAX_RETRIES);
837
838                         the_result = SRpnt->sr_result;
839                         retries++;
840                 } while (retries < 3 && 
841                          (!scsi_status_is_good(the_result) ||
842                           ((driver_byte(the_result) & DRIVER_SENSE) &&
843                            SRpnt->sr_sense_buffer[2] == UNIT_ATTENTION)));
844
845                 /*
846                  * If the drive has indicated to us that it doesn't have
847                  * any media in it, don't bother with any of the rest of
848                  * this crap.
849                  */
850                 if (media_not_present(sdkp, SRpnt))
851                         return;
852
853                 if ((driver_byte(the_result) & DRIVER_SENSE) == 0) {
854                         /* no sense, TUR either succeeded or failed
855                          * with a status error */
856                         if(!spintime && !scsi_status_is_good(the_result))
857                                 printk(KERN_NOTICE "%s: Unit Not Ready, error = 0x%x\n", diskname, the_result);
858                         break;
859                 }
860                                         
861                 /*
862                  * The device does not want the automatic start to be issued.
863                  */
864                 if (sdkp->device->no_start_on_add) {
865                         break;
866                 }
867
868                 /*
869                  * If manual intervention is required, or this is an
870                  * absent USB storage device, a spinup is meaningless.
871                  */
872                 if (SRpnt->sr_sense_buffer[2] == NOT_READY &&
873                     SRpnt->sr_sense_buffer[12] == 4 /* not ready */ &&
874                     SRpnt->sr_sense_buffer[13] == 3) {
875                         break;          /* manual intervention required */
876
877                 /*
878                  * Issue command to spin up drive when not ready
879                  */
880                 } else if (SRpnt->sr_sense_buffer[2] == NOT_READY) {
881                         unsigned long time1;
882                         if (!spintime) {
883                                 printk(KERN_NOTICE "%s: Spinning up disk...",
884                                        diskname);
885                                 cmd[0] = START_STOP;
886                                 cmd[1] = 1;     /* Return immediately */
887                                 memset((void *) &cmd[2], 0, 8);
888                                 cmd[4] = 1;     /* Start spin cycle */
889                                 SRpnt->sr_cmd_len = 0;
890                                 SRpnt->sr_sense_buffer[0] = 0;
891                                 SRpnt->sr_sense_buffer[2] = 0;
892
893                                 SRpnt->sr_data_direction = DMA_NONE;
894                                 scsi_wait_req(SRpnt, (void *)cmd, 
895                                               (void *) buffer, 0/*512*/, 
896                                               SD_TIMEOUT, SD_MAX_RETRIES);
897                                 spintime_value = jiffies;
898                         }
899                         spintime = 1;
900                         time1 = HZ;
901                         /* Wait 1 second for next try */
902                         do {
903                                 current->state = TASK_UNINTERRUPTIBLE;
904                                 time1 = schedule_timeout(time1);
905                         } while(time1);
906                         printk(".");
907                 } else {
908                         /* we don't understand the sense code, so it's
909                          * probably pointless to loop */
910                         if(!spintime) {
911                                 printk(KERN_NOTICE "%s: Unit Not Ready, sense:\n", diskname);
912                                 print_req_sense("", SRpnt);
913                         }
914                         break;
915                 }
916                                 
917         } while (spintime &&
918                  time_after(spintime_value + 100 * HZ, jiffies));
919
920         if (spintime) {
921                 if (scsi_status_is_good(the_result))
922                         printk("ready\n");
923                 else
924                         printk("not responding...\n");
925         }
926 }
927
928 /*
929  * read disk capacity
930  */
931 static void
932 sd_read_capacity(struct scsi_disk *sdkp, char *diskname,
933                  struct scsi_request *SRpnt, unsigned char *buffer) {
934         unsigned char cmd[16];
935         struct scsi_device *sdp = sdkp->device;
936         int the_result, retries;
937         int sector_size = 0;
938         int longrc = 0;
939
940 repeat:
941         retries = 3;
942         do {
943                 if (longrc) {
944                         memset((void *) cmd, 0, 16);
945                         cmd[0] = SERVICE_ACTION_IN;
946                         cmd[1] = SAI_READ_CAPACITY_16;
947                         cmd[13] = 12;
948                         memset((void *) buffer, 0, 12);
949                 } else {
950                         cmd[0] = READ_CAPACITY;
951                         memset((void *) &cmd[1], 0, 9);
952                         memset((void *) buffer, 0, 8);
953                 }
954                 
955                 SRpnt->sr_cmd_len = 0;
956                 SRpnt->sr_sense_buffer[0] = 0;
957                 SRpnt->sr_sense_buffer[2] = 0;
958                 SRpnt->sr_data_direction = DMA_FROM_DEVICE;
959
960                 scsi_wait_req(SRpnt, (void *) cmd, (void *) buffer,
961                               longrc ? 12 : 8, SD_TIMEOUT, SD_MAX_RETRIES);
962
963                 if (media_not_present(sdkp, SRpnt))
964                         return;
965
966                 the_result = SRpnt->sr_result;
967                 retries--;
968
969         } while (the_result && retries);
970
971         if (the_result && !longrc) {
972                 printk(KERN_NOTICE "%s : READ CAPACITY failed.\n"
973                        "%s : status=%x, message=%02x, host=%d, driver=%02x \n",
974                        diskname, diskname,
975                        status_byte(the_result),
976                        msg_byte(the_result),
977                        host_byte(the_result),
978                        driver_byte(the_result));
979
980                 if (driver_byte(the_result) & DRIVER_SENSE)
981                         print_req_sense("sd", SRpnt);
982                 else
983                         printk("%s : sense not available. \n", diskname);
984
985                 /* Set dirty bit for removable devices if not ready -
986                  * sometimes drives will not report this properly. */
987                 if (sdp->removable &&
988                     SRpnt->sr_sense_buffer[2] == NOT_READY)
989                         sdp->changed = 1;
990
991                 /* Either no media are present but the drive didn't tell us,
992                    or they are present but the read capacity command fails */
993                 /* sdkp->media_present = 0; -- not always correct */
994                 sdkp->capacity = 0x200000; /* 1 GB - random */
995
996                 return;
997         } else if (the_result && longrc) {
998                 /* READ CAPACITY(16) has been failed */
999                 printk(KERN_NOTICE "%s : READ CAPACITY(16) failed.\n"
1000                        "%s : status=%x, message=%02x, host=%d, driver=%02x \n",
1001                        diskname, diskname,
1002                        status_byte(the_result),
1003                        msg_byte(the_result),
1004                        host_byte(the_result),
1005                        driver_byte(the_result));
1006                 printk(KERN_NOTICE "%s : use 0xffffffff as device size\n",
1007                        diskname);
1008                 
1009                 sdkp->capacity = 1 + (sector_t) 0xffffffff;             
1010                 goto got_data;
1011         }       
1012         
1013         if (!longrc) {
1014                 sector_size = (buffer[4] << 24) |
1015                         (buffer[5] << 16) | (buffer[6] << 8) | buffer[7];
1016                 if (buffer[0] == 0xff && buffer[1] == 0xff &&
1017                     buffer[2] == 0xff && buffer[3] == 0xff) {
1018                         if(sizeof(sdkp->capacity) > 4) {
1019                                 printk(KERN_NOTICE "%s : very big device. try to use"
1020                                        " READ CAPACITY(16).\n", diskname);
1021                                 longrc = 1;
1022                                 goto repeat;
1023                         } else {
1024                                 printk(KERN_ERR "%s: too big for kernel.  Assuming maximum 2Tb\n", diskname);
1025                         }
1026                 }
1027                 sdkp->capacity = 1 + (((sector_t)buffer[0] << 24) |
1028                         (buffer[1] << 16) |
1029                         (buffer[2] << 8) |
1030                         buffer[3]);                     
1031         } else {
1032                 sdkp->capacity = 1 + (((u64)buffer[0] << 56) |
1033                         ((u64)buffer[1] << 48) |
1034                         ((u64)buffer[2] << 40) |
1035                         ((u64)buffer[3] << 32) |
1036                         ((sector_t)buffer[4] << 24) |
1037                         ((sector_t)buffer[5] << 16) |
1038                         ((sector_t)buffer[6] << 8)  |
1039                         (sector_t)buffer[7]);
1040                         
1041                 sector_size = (buffer[8] << 24) |
1042                         (buffer[9] << 16) | (buffer[10] << 8) | buffer[11];
1043         }       
1044
1045 got_data:
1046         if (sector_size == 0) {
1047                 sector_size = 512;
1048                 printk(KERN_NOTICE "%s : sector size 0 reported, "
1049                        "assuming 512.\n", diskname);
1050         }
1051
1052         if (sector_size != 512 &&
1053             sector_size != 1024 &&
1054             sector_size != 2048 &&
1055             sector_size != 4096 &&
1056             sector_size != 256) {
1057                 printk(KERN_NOTICE "%s : unsupported sector size "
1058                        "%d.\n", diskname, sector_size);
1059                 /*
1060                  * The user might want to re-format the drive with
1061                  * a supported sectorsize.  Once this happens, it
1062                  * would be relatively trivial to set the thing up.
1063                  * For this reason, we leave the thing in the table.
1064                  */
1065                 sdkp->capacity = 0;
1066         }
1067         {
1068                 /*
1069                  * The msdos fs needs to know the hardware sector size
1070                  * So I have created this table. See ll_rw_blk.c
1071                  * Jacques Gelinas (Jacques@solucorp.qc.ca)
1072                  */
1073                 int hard_sector = sector_size;
1074                 sector_t sz = sdkp->capacity * (hard_sector/256);
1075                 request_queue_t *queue = sdp->request_queue;
1076                 sector_t mb;
1077
1078                 blk_queue_hardsect_size(queue, hard_sector);
1079                 /* avoid 64-bit division on 32-bit platforms */
1080                 mb = sz >> 1;
1081                 sector_div(sz, 1250);
1082                 mb -= sz - 974;
1083                 sector_div(mb, 1950);
1084
1085                 printk(KERN_NOTICE "SCSI device %s: "
1086                        "%llu %d-byte hdwr sectors (%llu MB)\n",
1087                        diskname, (unsigned long long)sdkp->capacity,
1088                        hard_sector, (unsigned long long)mb);
1089         }
1090
1091         /* Rescale capacity to 512-byte units */
1092         if (sector_size == 4096)
1093                 sdkp->capacity <<= 3;
1094         else if (sector_size == 2048)
1095                 sdkp->capacity <<= 2;
1096         else if (sector_size == 1024)
1097                 sdkp->capacity <<= 1;
1098         else if (sector_size == 256)
1099                 sdkp->capacity >>= 1;
1100
1101         sdkp->device->sector_size = sector_size;
1102 }
1103
1104 /* called with buffer of length 512 */
1105 static inline int
1106 sd_do_mode_sense(struct scsi_request *SRpnt, int dbd, int modepage,
1107                  unsigned char *buffer, int len, struct scsi_mode_data *data)
1108 {
1109         return __scsi_mode_sense(SRpnt, dbd, modepage, buffer, len,
1110                                  SD_TIMEOUT, SD_MAX_RETRIES, data);
1111 }
1112
1113 /*
1114  * read write protect setting, if possible - called only in sd_revalidate_disk()
1115  * called with buffer of length 512
1116  */
1117 static void
1118 sd_read_write_protect_flag(struct scsi_disk *sdkp, char *diskname,
1119                    struct scsi_request *SRpnt, unsigned char *buffer) {
1120         int res;
1121         struct scsi_mode_data data;
1122
1123         set_disk_ro(sdkp->disk, 0);
1124         if (sdkp->device->skip_ms_page_3f) {
1125                 printk(KERN_NOTICE "%s: assuming Write Enabled\n", diskname);
1126                 return;
1127         }
1128
1129         if (sdkp->device->use_192_bytes_for_3f) {
1130                 res = sd_do_mode_sense(SRpnt, 0, 0x3F, buffer, 192, &data);
1131         } else {
1132                 /*
1133                  * First attempt: ask for all pages (0x3F), but only 4 bytes.
1134                  * We have to start carefully: some devices hang if we ask
1135                  * for more than is available.
1136                  */
1137                 res = sd_do_mode_sense(SRpnt, 0, 0x3F, buffer, 4, &data);
1138
1139                 /*
1140                  * Second attempt: ask for page 0 When only page 0 is
1141                  * implemented, a request for page 3F may return Sense Key
1142                  * 5: Illegal Request, Sense Code 24: Invalid field in
1143                  * CDB.
1144                  */
1145                 if (!scsi_status_is_good(res))
1146                         res = sd_do_mode_sense(SRpnt, 0, 0, buffer, 4, &data);
1147
1148                 /*
1149                  * Third attempt: ask 255 bytes, as we did earlier.
1150                  */
1151                 if (!scsi_status_is_good(res))
1152                         res = sd_do_mode_sense(SRpnt, 0, 0x3F, buffer, 255,
1153                                                &data);
1154         }
1155
1156         if (!scsi_status_is_good(res)) {
1157                 printk(KERN_WARNING
1158                        "%s: test WP failed, assume Write Enabled\n", diskname);
1159         } else {
1160                 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
1161                 set_disk_ro(sdkp->disk, sdkp->write_prot);
1162                 printk(KERN_NOTICE "%s: Write Protect is %s\n", diskname,
1163                        sdkp->write_prot ? "on" : "off");
1164                 printk(KERN_DEBUG "%s: Mode Sense: %02x %02x %02x %02x\n",
1165                        diskname, buffer[0], buffer[1], buffer[2], buffer[3]);
1166         }
1167 }
1168
1169 /*
1170  * sd_read_cache_type - called only from sd_revalidate_disk()
1171  * called with buffer of length 512
1172  */
1173 static void
1174 sd_read_cache_type(struct scsi_disk *sdkp, char *diskname,
1175                    struct scsi_request *SRpnt, unsigned char *buffer) {
1176         int len = 0, res;
1177
1178         const int dbd = 0;         /* DBD */
1179         const int modepage = 0x08; /* current values, cache page */
1180         struct scsi_mode_data data;
1181
1182         if (sdkp->device->skip_ms_page_8)
1183                 goto defaults;
1184
1185         /* cautiously ask */
1186         res = sd_do_mode_sense(SRpnt, dbd, modepage, buffer, 4, &data);
1187
1188         if (!scsi_status_is_good(res))
1189                 goto bad_sense;
1190
1191         /* that went OK, now ask for the proper length */
1192         len = data.length;
1193
1194         /*
1195          * We're only interested in the first three bytes, actually.
1196          * But the data cache page is defined for the first 20.
1197          */
1198         if (len < 3)
1199                 goto bad_sense;
1200         if (len > 20)
1201                 len = 20;
1202
1203         /* Take headers and block descriptors into account */
1204         len += data.header_length + data.block_descriptor_length;
1205
1206         /* Get the data */
1207         res = sd_do_mode_sense(SRpnt, dbd, modepage, buffer, len, &data);
1208
1209         if (scsi_status_is_good(res)) {
1210                 const char *types[] = {
1211                         "write through", "none", "write back",
1212                         "write back, no read (daft)"
1213                 };
1214                 int ct = 0;
1215                 int offset = data.header_length +
1216                         data.block_descriptor_length + 2;
1217
1218                 sdkp->WCE = ((buffer[offset] & 0x04) != 0);
1219                 sdkp->RCD = ((buffer[offset] & 0x01) != 0);
1220
1221                 ct =  sdkp->RCD + 2*sdkp->WCE;
1222
1223                 printk(KERN_NOTICE "SCSI device %s: drive cache: %s\n",
1224                        diskname, types[ct]);
1225
1226                 return;
1227         }
1228
1229 bad_sense:
1230         if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70
1231              && (SRpnt->sr_sense_buffer[2] & 0x0f) == ILLEGAL_REQUEST
1232              /* ASC 0x24 ASCQ 0x00: Invalid field in CDB */
1233              && SRpnt->sr_sense_buffer[12] == 0x24
1234              && SRpnt->sr_sense_buffer[13] == 0x00) {
1235                 printk(KERN_NOTICE "%s: cache data unavailable\n",
1236                        diskname);
1237         } else {
1238                 printk(KERN_ERR "%s: asking for cache data failed\n",
1239                        diskname);
1240         }
1241
1242 defaults:
1243         printk(KERN_ERR "%s: assuming drive cache: write through\n",
1244                diskname);
1245         sdkp->WCE = 0;
1246         sdkp->RCD = 0;
1247 }
1248
1249 /**
1250  *      sd_revalidate_disk - called the first time a new disk is seen,
1251  *      performs disk spin up, read_capacity, etc.
1252  *      @disk: struct gendisk we care about
1253  **/
1254 static int sd_revalidate_disk(struct gendisk *disk)
1255 {
1256         struct scsi_disk *sdkp = scsi_disk(disk);
1257         struct scsi_device *sdp = sdkp->device;
1258         struct scsi_request *sreq;
1259         unsigned char *buffer;
1260
1261         SCSI_LOG_HLQUEUE(3, printk("sd_revalidate_disk: disk=%s\n", disk->disk_name));
1262
1263         /*
1264          * If the device is offline, don't try and read capacity or any
1265          * of the other niceties.
1266          */
1267         if (!scsi_device_online(sdp))
1268                 goto out;
1269
1270         sreq = scsi_allocate_request(sdp, GFP_KERNEL);
1271         if (!sreq) {
1272                 printk(KERN_WARNING "(sd_revalidate_disk:) Request allocation "
1273                        "failure.\n");
1274                 goto out;
1275         }
1276
1277         buffer = kmalloc(512, GFP_KERNEL | __GFP_DMA);
1278         if (!buffer) {
1279                 printk(KERN_WARNING "(sd_revalidate_disk:) Memory allocation "
1280                        "failure.\n");
1281                 goto out_release_request;
1282         }
1283
1284         /* defaults, until the device tells us otherwise */
1285         sdp->sector_size = 512;
1286         sdkp->capacity = 0;
1287         sdkp->media_present = 1;
1288         sdkp->write_prot = 0;
1289         sdkp->WCE = 0;
1290         sdkp->RCD = 0;
1291
1292         sd_spinup_disk(sdkp, disk->disk_name, sreq, buffer);
1293
1294         /*
1295          * Without media there is no reason to ask; moreover, some devices
1296          * react badly if we do.
1297          */
1298         if (sdkp->media_present) {
1299                 sd_read_capacity(sdkp, disk->disk_name, sreq, buffer);
1300                 if (sdp->removable)
1301                         sd_read_write_protect_flag(sdkp, disk->disk_name,
1302                                         sreq, buffer);
1303                 sd_read_cache_type(sdkp, disk->disk_name, sreq, buffer);
1304         }
1305                 
1306         set_capacity(disk, sdkp->capacity);
1307         kfree(buffer);
1308
1309  out_release_request: 
1310         scsi_release_request(sreq);
1311  out:
1312         return 0;
1313 }
1314
1315 /**
1316  *      sd_probe - called during driver initialization and whenever a
1317  *      new scsi device is attached to the system. It is called once
1318  *      for each scsi device (not just disks) present.
1319  *      @dev: pointer to device object
1320  *
1321  *      Returns 0 if successful (or not interested in this scsi device 
1322  *      (e.g. scanner)); 1 when there is an error.
1323  *
1324  *      Note: this function is invoked from the scsi mid-level.
1325  *      This function sets up the mapping between a given 
1326  *      <host,channel,id,lun> (found in sdp) and new device name 
1327  *      (e.g. /dev/sda). More precisely it is the block device major 
1328  *      and minor number that is chosen here.
1329  *
1330  *      Assume sd_attach is not re-entrant (for time being)
1331  *      Also think about sd_attach() and sd_remove() running coincidentally.
1332  **/
1333 static int sd_probe(struct device *dev)
1334 {
1335         struct scsi_device *sdp = to_scsi_device(dev);
1336         struct scsi_disk *sdkp;
1337         struct gendisk *gd;
1338         u32 index;
1339         int error, devno;
1340
1341         error = -ENODEV;
1342         if ((sdp->type != TYPE_DISK) && (sdp->type != TYPE_MOD))
1343                 goto out;
1344
1345         if ((error = scsi_device_get(sdp)) != 0)
1346                 goto out;
1347
1348         SCSI_LOG_HLQUEUE(3, printk("sd_attach: scsi device: <%d,%d,%d,%d>\n", 
1349                          sdp->host->host_no, sdp->channel, sdp->id, sdp->lun));
1350
1351         error = -ENOMEM;
1352         sdkp = kmalloc(sizeof(*sdkp), GFP_KERNEL);
1353         if (!sdkp)
1354                 goto out_put_sdev;
1355
1356         memset (sdkp, 0, sizeof(*sdkp));
1357         kref_init(&sdkp->kref, scsi_disk_release);
1358
1359         /* Note: We can accomodate 64 partitions, but the genhd code
1360          * assumes partitions allocate consecutive minors, which they don't.
1361          * So for now stay with max 16 partitions and leave two spare bits. 
1362          * Later, we may change the genhd code and the alloc_disk() call
1363          * and the ->minors assignment here.    KG, 2004-02-10
1364          */ 
1365         gd = alloc_disk(16);
1366         if (!gd)
1367                 goto out_free;
1368
1369         spin_lock(&sd_index_lock);
1370         index = find_first_zero_bit(sd_index_bits, SD_DISKS);
1371         if (index == SD_DISKS) {
1372                 spin_unlock(&sd_index_lock);
1373                 error = -EBUSY;
1374                 goto out_put;
1375         }
1376         __set_bit(index, sd_index_bits);
1377         spin_unlock(&sd_index_lock);
1378
1379         sdkp->device = sdp;
1380         sdkp->driver = &sd_template;
1381         sdkp->disk = gd;
1382         sdkp->index = index;
1383         sdkp->openers = 0;
1384
1385         devno = make_sd_dev(index, 0);
1386         gd->major = MAJOR(devno);
1387         gd->first_minor = MINOR(devno);
1388         gd->minors = 16;
1389         gd->fops = &sd_fops;
1390
1391         if (index < 26) {
1392                 sprintf(gd->disk_name, "sd%c", 'a' + index % 26);
1393         } else if (index < (26*27)) {
1394                 sprintf(gd->disk_name, "sd%c%c",
1395                         'a' + index / 26 - 1,'a' + index % 26);
1396         } else {
1397                 const unsigned int m1 = (index / 26 - 1) / 26 - 1;
1398                 const unsigned int m2 = (index / 26 - 1) % 26;
1399                 const unsigned int m3 =  index % 26;
1400                 sprintf(gd->disk_name, "sd%c%c%c",
1401                         'a' + m1, 'a' + m2, 'a' + m3);
1402         }
1403
1404         strcpy(gd->devfs_name, sdp->devfs_name);
1405
1406         gd->private_data = &sdkp->driver;
1407
1408         sd_revalidate_disk(gd);
1409
1410         gd->driverfs_dev = &sdp->sdev_gendev;
1411         gd->flags = GENHD_FL_DRIVERFS;
1412         if (sdp->removable)
1413                 gd->flags |= GENHD_FL_REMOVABLE;
1414         gd->queue = sdkp->device->request_queue;
1415
1416         dev_set_drvdata(dev, sdkp);
1417         add_disk(gd);
1418
1419         printk(KERN_NOTICE "Attached scsi %sdisk %s at scsi%d, channel %d, "
1420                "id %d, lun %d\n", sdp->removable ? "removable " : "",
1421                gd->disk_name, sdp->host->host_no, sdp->channel,
1422                sdp->id, sdp->lun);
1423
1424         return 0;
1425
1426 out_put:
1427         put_disk(gd);
1428 out_free:
1429         kfree(sdkp);
1430 out_put_sdev:
1431         scsi_device_put(sdp);
1432 out:
1433         return error;
1434 }
1435
1436 /**
1437  *      sd_remove - called whenever a scsi disk (previously recognized by
1438  *      sd_probe) is detached from the system. It is called (potentially
1439  *      multiple times) during sd module unload.
1440  *      @sdp: pointer to mid level scsi device object
1441  *
1442  *      Note: this function is invoked from the scsi mid-level.
1443  *      This function potentially frees up a device name (e.g. /dev/sdc)
1444  *      that could be re-used by a subsequent sd_probe().
1445  *      This function is not called when the built-in sd driver is "exit-ed".
1446  **/
1447 static int sd_remove(struct device *dev)
1448 {
1449         struct scsi_disk *sdkp = dev_get_drvdata(dev);
1450
1451         del_gendisk(sdkp->disk);
1452         sd_shutdown(dev);
1453         scsi_disk_put(sdkp);
1454
1455         return 0;
1456 }
1457
1458 /**
1459  *      scsi_disk_release - Called to free the scsi_disk structure
1460  *      @kref: pointer to embedded kref
1461  *
1462  *      sd_ref_sem must be held entering this routine.  Because it is
1463  *      called on last put, you should always use the scsi_disk_get()
1464  *      scsi_disk_put() helpers which manipulate the semaphore directly
1465  *      and never do a direct kref_put().
1466  **/
1467 static void scsi_disk_release(struct kref *kref)
1468 {
1469         struct scsi_disk *sdkp = to_scsi_disk(kref);
1470         struct scsi_device *sdev = sdkp->device;
1471         struct gendisk *disk = sdkp->disk;
1472         
1473         spin_lock(&sd_index_lock);
1474         clear_bit(sdkp->index, sd_index_bits);
1475         spin_unlock(&sd_index_lock);
1476
1477         disk->private_data = NULL;
1478
1479         put_disk(disk);
1480
1481         kfree(sdkp);
1482
1483         scsi_device_put(sdev);
1484 }
1485
1486 /*
1487  * Send a SYNCHRONIZE CACHE instruction down to the device through
1488  * the normal SCSI command structure.  Wait for the command to
1489  * complete.
1490  */
1491 static void sd_shutdown(struct device *dev)
1492 {
1493         struct scsi_device *sdp = to_scsi_device(dev);
1494         struct scsi_disk *sdkp;
1495         struct scsi_request *sreq;
1496         int retries, res;
1497
1498         sdkp = dev_get_drvdata(dev);
1499         if (!sdkp)
1500                return;         /* this can happen */
1501
1502         if (!scsi_device_online(sdp) || !sdkp->WCE)
1503                 return;
1504
1505         printk(KERN_NOTICE "Synchronizing SCSI cache for disk %s: ",
1506                         sdkp->disk->disk_name);
1507
1508         sreq = scsi_allocate_request(sdp, GFP_KERNEL);
1509         if (!sreq) {
1510                 printk("FAILED\n  No memory for request\n");
1511                 return;
1512         }
1513
1514         sreq->sr_data_direction = DMA_NONE;
1515         for (retries = 3; retries > 0; --retries) {
1516                 unsigned char cmd[10] = { 0 };
1517
1518                 cmd[0] = SYNCHRONIZE_CACHE;
1519                 /*
1520                  * Leave the rest of the command zero to indicate
1521                  * flush everything.
1522                  */
1523                 scsi_wait_req(sreq, cmd, NULL, 0, SD_TIMEOUT, SD_MAX_RETRIES);
1524                 if (sreq->sr_result == 0)
1525                         break;
1526         }
1527
1528         res = sreq->sr_result;
1529         if (res) {
1530                 printk(KERN_WARNING "FAILED\n  status = %x, message = %02x, "
1531                                     "host = %d, driver = %02x\n  ",
1532                                     status_byte(res), msg_byte(res),
1533                                     host_byte(res), driver_byte(res));
1534                         if (driver_byte(res) & DRIVER_SENSE)
1535                                 print_req_sense("sd", sreq);
1536         }
1537         
1538         scsi_release_request(sreq);
1539         printk("\n");
1540 }       
1541
1542 /**
1543  *      init_sd - entry point for this driver (both when built in or when
1544  *      a module).
1545  *
1546  *      Note: this function registers this driver with the scsi mid-level.
1547  **/
1548 static int __init init_sd(void)
1549 {
1550         int majors = 0, i;
1551
1552         SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
1553
1554         for (i = 0; i < SD_MAJORS; i++)
1555                 if (register_blkdev(sd_major(i), "sd") == 0)
1556                         majors++;
1557
1558         if (!majors)
1559                 return -ENODEV;
1560
1561         return scsi_register_driver(&sd_template.gendrv);
1562 }
1563
1564 /**
1565  *      exit_sd - exit point for this driver (when it is a module).
1566  *
1567  *      Note: this function unregisters this driver from the scsi mid-level.
1568  **/
1569 static void __exit exit_sd(void)
1570 {
1571         int i;
1572
1573         SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
1574
1575         scsi_unregister_driver(&sd_template.gendrv);
1576         for (i = 0; i < SD_MAJORS; i++)
1577                 unregister_blkdev(sd_major(i), "sd");
1578 }
1579
1580 MODULE_LICENSE("GPL");
1581 MODULE_AUTHOR("Eric Youngdale");
1582 MODULE_DESCRIPTION("SCSI disk (sd) driver");
1583
1584 module_init(init_sd);
1585 module_exit(exit_sd);