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