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