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