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