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