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