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