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