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