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