2 * sd.c Copyright (C) 1992 Drew Eckhardt
3 * Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
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.
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.
35 #include <linux/module.h>
37 #include <linux/kernel.h>
39 #include <linux/bio.h>
40 #include <linux/genhd.h>
41 #include <linux/hdreg.h>
42 #include <linux/errno.h>
43 #include <linux/idr.h>
44 #include <linux/interrupt.h>
45 #include <linux/init.h>
46 #include <linux/blkdev.h>
47 #include <linux/blkpg.h>
48 #include <linux/delay.h>
49 #include <linux/mutex.h>
50 #include <linux/string_helpers.h>
51 #include <linux/async.h>
52 #include <asm/uaccess.h>
53 #include <asm/unaligned.h>
55 #include <scsi/scsi.h>
56 #include <scsi/scsi_cmnd.h>
57 #include <scsi/scsi_dbg.h>
58 #include <scsi/scsi_device.h>
59 #include <scsi/scsi_driver.h>
60 #include <scsi/scsi_eh.h>
61 #include <scsi/scsi_host.h>
62 #include <scsi/scsi_ioctl.h>
63 #include <scsi/scsicam.h>
66 #include "scsi_logging.h"
68 MODULE_AUTHOR("Eric Youngdale");
69 MODULE_DESCRIPTION("SCSI disk (sd) driver");
70 MODULE_LICENSE("GPL");
72 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
73 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
74 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
75 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
76 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
77 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
78 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
79 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
80 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
81 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
82 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
88 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
89 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
90 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
92 #if !defined(CONFIG_DEBUG_BLOCK_EXT_DEVT)
98 static int sd_revalidate_disk(struct gendisk *);
99 static int sd_probe(struct device *);
100 static int sd_remove(struct device *);
101 static void sd_shutdown(struct device *);
102 static int sd_suspend(struct device *, pm_message_t state);
103 static int sd_resume(struct device *);
104 static void sd_rescan(struct device *);
105 static int sd_done(struct scsi_cmnd *);
106 static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer);
107 static void scsi_disk_release(struct device *cdev);
108 static void sd_print_sense_hdr(struct scsi_disk *, struct scsi_sense_hdr *);
109 static void sd_print_result(struct scsi_disk *, int);
111 static DEFINE_SPINLOCK(sd_index_lock);
112 static DEFINE_IDA(sd_index_ida);
114 /* This semaphore is used to mediate the 0->1 reference get in the
115 * face of object destruction (i.e. we can't allow a get on an
116 * object after last put) */
117 static DEFINE_MUTEX(sd_ref_mutex);
119 static const char *sd_cache_types[] = {
120 "write through", "none", "write back",
121 "write back, no read (daft)"
125 sd_store_cache_type(struct device *dev, struct device_attribute *attr,
126 const char *buf, size_t count)
128 int i, ct = -1, rcd, wce, sp;
129 struct scsi_disk *sdkp = to_scsi_disk(dev);
130 struct scsi_device *sdp = sdkp->device;
133 struct scsi_mode_data data;
134 struct scsi_sense_hdr sshdr;
137 if (sdp->type != TYPE_DISK)
138 /* no cache control on RBC devices; theoretically they
139 * can do it, but there's probably so many exceptions
140 * it's not worth the risk */
143 for (i = 0; i < ARRAY_SIZE(sd_cache_types); i++) {
144 const int len = strlen(sd_cache_types[i]);
145 if (strncmp(sd_cache_types[i], buf, len) == 0 &&
153 rcd = ct & 0x01 ? 1 : 0;
154 wce = ct & 0x02 ? 1 : 0;
155 if (scsi_mode_sense(sdp, 0x08, 8, buffer, sizeof(buffer), SD_TIMEOUT,
156 SD_MAX_RETRIES, &data, NULL))
158 len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
159 data.block_descriptor_length);
160 buffer_data = buffer + data.header_length +
161 data.block_descriptor_length;
162 buffer_data[2] &= ~0x05;
163 buffer_data[2] |= wce << 2 | rcd;
164 sp = buffer_data[0] & 0x80 ? 1 : 0;
166 if (scsi_mode_select(sdp, 1, sp, 8, buffer_data, len, SD_TIMEOUT,
167 SD_MAX_RETRIES, &data, &sshdr)) {
168 if (scsi_sense_valid(&sshdr))
169 sd_print_sense_hdr(sdkp, &sshdr);
172 revalidate_disk(sdkp->disk);
177 sd_store_manage_start_stop(struct device *dev, struct device_attribute *attr,
178 const char *buf, size_t count)
180 struct scsi_disk *sdkp = to_scsi_disk(dev);
181 struct scsi_device *sdp = sdkp->device;
183 if (!capable(CAP_SYS_ADMIN))
186 sdp->manage_start_stop = simple_strtoul(buf, NULL, 10);
192 sd_store_allow_restart(struct device *dev, struct device_attribute *attr,
193 const char *buf, size_t count)
195 struct scsi_disk *sdkp = to_scsi_disk(dev);
196 struct scsi_device *sdp = sdkp->device;
198 if (!capable(CAP_SYS_ADMIN))
201 if (sdp->type != TYPE_DISK)
204 sdp->allow_restart = simple_strtoul(buf, NULL, 10);
210 sd_show_cache_type(struct device *dev, struct device_attribute *attr,
213 struct scsi_disk *sdkp = to_scsi_disk(dev);
214 int ct = sdkp->RCD + 2*sdkp->WCE;
216 return snprintf(buf, 40, "%s\n", sd_cache_types[ct]);
220 sd_show_fua(struct device *dev, struct device_attribute *attr, char *buf)
222 struct scsi_disk *sdkp = to_scsi_disk(dev);
224 return snprintf(buf, 20, "%u\n", sdkp->DPOFUA);
228 sd_show_manage_start_stop(struct device *dev, struct device_attribute *attr,
231 struct scsi_disk *sdkp = to_scsi_disk(dev);
232 struct scsi_device *sdp = sdkp->device;
234 return snprintf(buf, 20, "%u\n", sdp->manage_start_stop);
238 sd_show_allow_restart(struct device *dev, struct device_attribute *attr,
241 struct scsi_disk *sdkp = to_scsi_disk(dev);
243 return snprintf(buf, 40, "%d\n", sdkp->device->allow_restart);
247 sd_show_protection_type(struct device *dev, struct device_attribute *attr,
250 struct scsi_disk *sdkp = to_scsi_disk(dev);
252 return snprintf(buf, 20, "%u\n", sdkp->protection_type);
256 sd_show_app_tag_own(struct device *dev, struct device_attribute *attr,
259 struct scsi_disk *sdkp = to_scsi_disk(dev);
261 return snprintf(buf, 20, "%u\n", sdkp->ATO);
264 static struct device_attribute sd_disk_attrs[] = {
265 __ATTR(cache_type, S_IRUGO|S_IWUSR, sd_show_cache_type,
266 sd_store_cache_type),
267 __ATTR(FUA, S_IRUGO, sd_show_fua, NULL),
268 __ATTR(allow_restart, S_IRUGO|S_IWUSR, sd_show_allow_restart,
269 sd_store_allow_restart),
270 __ATTR(manage_start_stop, S_IRUGO|S_IWUSR, sd_show_manage_start_stop,
271 sd_store_manage_start_stop),
272 __ATTR(protection_type, S_IRUGO, sd_show_protection_type, NULL),
273 __ATTR(app_tag_own, S_IRUGO, sd_show_app_tag_own, NULL),
277 static struct class sd_disk_class = {
279 .owner = THIS_MODULE,
280 .dev_release = scsi_disk_release,
281 .dev_attrs = sd_disk_attrs,
284 static struct scsi_driver sd_template = {
285 .owner = THIS_MODULE,
290 .suspend = sd_suspend,
292 .shutdown = sd_shutdown,
299 * Device no to disk mapping:
301 * major disc2 disc p1
302 * |............|.............|....|....| <- dev_t
305 * Inside a major, we have 16k disks, however mapped non-
306 * contiguously. The first 16 disks are for major0, the next
307 * ones with major1, ... Disk 256 is for major0 again, disk 272
309 * As we stay compatible with our numbering scheme, we can reuse
310 * the well-know SCSI majors 8, 65--71, 136--143.
312 static int sd_major(int major_idx)
316 return SCSI_DISK0_MAJOR;
318 return SCSI_DISK1_MAJOR + major_idx - 1;
320 return SCSI_DISK8_MAJOR + major_idx - 8;
323 return 0; /* shut up gcc */
327 static struct scsi_disk *__scsi_disk_get(struct gendisk *disk)
329 struct scsi_disk *sdkp = NULL;
331 if (disk->private_data) {
332 sdkp = scsi_disk(disk);
333 if (scsi_device_get(sdkp->device) == 0)
334 get_device(&sdkp->dev);
341 static struct scsi_disk *scsi_disk_get(struct gendisk *disk)
343 struct scsi_disk *sdkp;
345 mutex_lock(&sd_ref_mutex);
346 sdkp = __scsi_disk_get(disk);
347 mutex_unlock(&sd_ref_mutex);
351 static struct scsi_disk *scsi_disk_get_from_dev(struct device *dev)
353 struct scsi_disk *sdkp;
355 mutex_lock(&sd_ref_mutex);
356 sdkp = dev_get_drvdata(dev);
358 sdkp = __scsi_disk_get(sdkp->disk);
359 mutex_unlock(&sd_ref_mutex);
363 static void scsi_disk_put(struct scsi_disk *sdkp)
365 struct scsi_device *sdev = sdkp->device;
367 mutex_lock(&sd_ref_mutex);
368 put_device(&sdkp->dev);
369 scsi_device_put(sdev);
370 mutex_unlock(&sd_ref_mutex);
373 static void sd_prot_op(struct scsi_cmnd *scmd, unsigned int dif)
375 unsigned int prot_op = SCSI_PROT_NORMAL;
376 unsigned int dix = scsi_prot_sg_count(scmd);
378 if (scmd->sc_data_direction == DMA_FROM_DEVICE) {
380 prot_op = SCSI_PROT_READ_PASS;
381 else if (dif && !dix)
382 prot_op = SCSI_PROT_READ_STRIP;
383 else if (!dif && dix)
384 prot_op = SCSI_PROT_READ_INSERT;
387 prot_op = SCSI_PROT_WRITE_PASS;
388 else if (dif && !dix)
389 prot_op = SCSI_PROT_WRITE_INSERT;
390 else if (!dif && dix)
391 prot_op = SCSI_PROT_WRITE_STRIP;
394 scsi_set_prot_op(scmd, prot_op);
395 scsi_set_prot_type(scmd, dif);
399 * sd_init_command - build a scsi (read or write) command from
400 * information in the request structure.
401 * @SCpnt: pointer to mid-level's per scsi command structure that
402 * contains request and into which the scsi command is written
404 * Returns 1 if successful and 0 if error (or cannot be done now).
406 static int sd_prep_fn(struct request_queue *q, struct request *rq)
408 struct scsi_cmnd *SCpnt;
409 struct scsi_device *sdp = q->queuedata;
410 struct gendisk *disk = rq->rq_disk;
411 struct scsi_disk *sdkp;
412 sector_t block = blk_rq_pos(rq);
414 unsigned int this_count = blk_rq_sectors(rq);
417 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
418 ret = scsi_setup_blk_pc_cmnd(sdp, rq);
420 } else if (rq->cmd_type != REQ_TYPE_FS) {
424 ret = scsi_setup_fs_cmnd(sdp, rq);
425 if (ret != BLKPREP_OK)
428 sdkp = scsi_disk(disk);
430 /* from here on until we're complete, any goto out
431 * is used for a killable error condition */
434 SCSI_LOG_HLQUEUE(1, scmd_printk(KERN_INFO, SCpnt,
435 "sd_init_command: block=%llu, "
437 (unsigned long long)block,
440 if (!sdp || !scsi_device_online(sdp) ||
441 block + blk_rq_sectors(rq) > get_capacity(disk)) {
442 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
443 "Finishing %u sectors\n",
444 blk_rq_sectors(rq)));
445 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
446 "Retry with 0x%p\n", SCpnt));
452 * quietly refuse to do anything to a changed disc until
453 * the changed bit has been reset
455 /* printk("SCSI disk has been changed. Prohibiting further I/O.\n"); */
460 * Some SD card readers can't handle multi-sector accesses which touch
461 * the last one or two hardware sectors. Split accesses as needed.
463 threshold = get_capacity(disk) - SD_LAST_BUGGY_SECTORS *
464 (sdp->sector_size / 512);
466 if (unlikely(sdp->last_sector_bug && block + this_count > threshold)) {
467 if (block < threshold) {
468 /* Access up to the threshold but not beyond */
469 this_count = threshold - block;
471 /* Access only a single hardware sector */
472 this_count = sdp->sector_size / 512;
476 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "block=%llu\n",
477 (unsigned long long)block));
480 * If we have a 1K hardware sectorsize, prevent access to single
481 * 512 byte sectors. In theory we could handle this - in fact
482 * the scsi cdrom driver must be able to handle this because
483 * we typically use 1K blocksizes, and cdroms typically have
484 * 2K hardware sectorsizes. Of course, things are simpler
485 * with the cdrom, since it is read-only. For performance
486 * reasons, the filesystems should be able to handle this
487 * and not force the scsi disk driver to use bounce buffers
490 if (sdp->sector_size == 1024) {
491 if ((block & 1) || (blk_rq_sectors(rq) & 1)) {
492 scmd_printk(KERN_ERR, SCpnt,
493 "Bad block number requested\n");
497 this_count = this_count >> 1;
500 if (sdp->sector_size == 2048) {
501 if ((block & 3) || (blk_rq_sectors(rq) & 3)) {
502 scmd_printk(KERN_ERR, SCpnt,
503 "Bad block number requested\n");
507 this_count = this_count >> 2;
510 if (sdp->sector_size == 4096) {
511 if ((block & 7) || (blk_rq_sectors(rq) & 7)) {
512 scmd_printk(KERN_ERR, SCpnt,
513 "Bad block number requested\n");
517 this_count = this_count >> 3;
520 if (rq_data_dir(rq) == WRITE) {
521 if (!sdp->writeable) {
524 SCpnt->cmnd[0] = WRITE_6;
525 SCpnt->sc_data_direction = DMA_TO_DEVICE;
527 if (blk_integrity_rq(rq) &&
528 sd_dif_prepare(rq, block, sdp->sector_size) == -EIO)
531 } else if (rq_data_dir(rq) == READ) {
532 SCpnt->cmnd[0] = READ_6;
533 SCpnt->sc_data_direction = DMA_FROM_DEVICE;
535 scmd_printk(KERN_ERR, SCpnt, "Unknown command %x\n", rq->cmd_flags);
539 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
540 "%s %d/%u 512 byte blocks.\n",
541 (rq_data_dir(rq) == WRITE) ?
542 "writing" : "reading", this_count,
543 blk_rq_sectors(rq)));
545 /* Set RDPROTECT/WRPROTECT if disk is formatted with DIF */
546 host_dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
548 SCpnt->cmnd[1] = 1 << 5;
552 if (block > 0xffffffff) {
553 SCpnt->cmnd[0] += READ_16 - READ_6;
554 SCpnt->cmnd[1] |= blk_fua_rq(rq) ? 0x8 : 0;
555 SCpnt->cmnd[2] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
556 SCpnt->cmnd[3] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
557 SCpnt->cmnd[4] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
558 SCpnt->cmnd[5] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
559 SCpnt->cmnd[6] = (unsigned char) (block >> 24) & 0xff;
560 SCpnt->cmnd[7] = (unsigned char) (block >> 16) & 0xff;
561 SCpnt->cmnd[8] = (unsigned char) (block >> 8) & 0xff;
562 SCpnt->cmnd[9] = (unsigned char) block & 0xff;
563 SCpnt->cmnd[10] = (unsigned char) (this_count >> 24) & 0xff;
564 SCpnt->cmnd[11] = (unsigned char) (this_count >> 16) & 0xff;
565 SCpnt->cmnd[12] = (unsigned char) (this_count >> 8) & 0xff;
566 SCpnt->cmnd[13] = (unsigned char) this_count & 0xff;
567 SCpnt->cmnd[14] = SCpnt->cmnd[15] = 0;
568 } else if ((this_count > 0xff) || (block > 0x1fffff) ||
569 scsi_device_protection(SCpnt->device) ||
570 SCpnt->device->use_10_for_rw) {
571 if (this_count > 0xffff)
574 SCpnt->cmnd[0] += READ_10 - READ_6;
575 SCpnt->cmnd[1] |= blk_fua_rq(rq) ? 0x8 : 0;
576 SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
577 SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
578 SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
579 SCpnt->cmnd[5] = (unsigned char) block & 0xff;
580 SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
581 SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
582 SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
584 if (unlikely(blk_fua_rq(rq))) {
586 * This happens only if this drive failed
587 * 10byte rw command with ILLEGAL_REQUEST
588 * during operation and thus turned off
591 scmd_printk(KERN_ERR, SCpnt,
592 "FUA write on READ/WRITE(6) drive\n");
596 SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f);
597 SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff);
598 SCpnt->cmnd[3] = (unsigned char) block & 0xff;
599 SCpnt->cmnd[4] = (unsigned char) this_count;
602 SCpnt->sdb.length = this_count * sdp->sector_size;
604 /* If DIF or DIX is enabled, tell HBA how to handle request */
605 if (host_dif || scsi_prot_sg_count(SCpnt))
606 sd_prot_op(SCpnt, host_dif);
609 * We shouldn't disconnect in the middle of a sector, so with a dumb
610 * host adapter, it's safe to assume that we can at least transfer
611 * this many bytes between each connect / disconnect.
613 SCpnt->transfersize = sdp->sector_size;
614 SCpnt->underflow = this_count << 9;
615 SCpnt->allowed = SD_MAX_RETRIES;
618 * This indicates that the command is ready from our end to be
623 return scsi_prep_return(q, rq, ret);
627 * sd_open - open a scsi disk device
628 * @inode: only i_rdev member may be used
629 * @filp: only f_mode and f_flags may be used
631 * Returns 0 if successful. Returns a negated errno value in case
634 * Note: This can be called from a user context (e.g. fsck(1) )
635 * or from within the kernel (e.g. as a result of a mount(1) ).
636 * In the latter case @inode and @filp carry an abridged amount
637 * of information as noted above.
639 static int sd_open(struct block_device *bdev, fmode_t mode)
641 struct scsi_disk *sdkp = scsi_disk_get(bdev->bd_disk);
642 struct scsi_device *sdev;
648 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
653 * If the device is in error recovery, wait until it is done.
654 * If the device is offline, then disallow any access to it.
657 if (!scsi_block_when_processing_errors(sdev))
660 if (sdev->removable || sdkp->write_prot)
661 check_disk_change(bdev);
664 * If the drive is empty, just let the open fail.
667 if (sdev->removable && !sdkp->media_present && !(mode & FMODE_NDELAY))
671 * If the device has the write protect tab set, have the open fail
672 * if the user expects to be able to write to the thing.
675 if (sdkp->write_prot && (mode & FMODE_WRITE))
679 * It is possible that the disk changing stuff resulted in
680 * the device being taken offline. If this is the case,
681 * report this to the user, and don't pretend that the
682 * open actually succeeded.
685 if (!scsi_device_online(sdev))
688 if (!sdkp->openers++ && sdev->removable) {
689 if (scsi_block_when_processing_errors(sdev))
690 scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
701 * sd_release - invoked when the (last) close(2) is called on this
703 * @inode: only i_rdev member may be used
704 * @filp: only f_mode and f_flags may be used
708 * Note: may block (uninterruptible) if error recovery is underway
711 static int sd_release(struct gendisk *disk, fmode_t mode)
713 struct scsi_disk *sdkp = scsi_disk(disk);
714 struct scsi_device *sdev = sdkp->device;
716 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
718 if (!--sdkp->openers && sdev->removable) {
719 if (scsi_block_when_processing_errors(sdev))
720 scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
724 * XXX and what if there are packets in flight and this close()
725 * XXX is followed by a "rmmod sd_mod"?
731 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
733 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
734 struct scsi_device *sdp = sdkp->device;
735 struct Scsi_Host *host = sdp->host;
738 /* default to most commonly used values */
739 diskinfo[0] = 0x40; /* 1 << 6 */
740 diskinfo[1] = 0x20; /* 1 << 5 */
741 diskinfo[2] = sdkp->capacity >> 11;
743 /* override with calculated, extended default, or driver values */
744 if (host->hostt->bios_param)
745 host->hostt->bios_param(sdp, bdev, sdkp->capacity, diskinfo);
747 scsicam_bios_param(bdev, sdkp->capacity, diskinfo);
749 geo->heads = diskinfo[0];
750 geo->sectors = diskinfo[1];
751 geo->cylinders = diskinfo[2];
756 * sd_ioctl - process an ioctl
757 * @inode: only i_rdev/i_bdev members may be used
758 * @filp: only f_mode and f_flags may be used
759 * @cmd: ioctl command number
760 * @arg: this is third argument given to ioctl(2) system call.
761 * Often contains a pointer.
763 * Returns 0 if successful (some ioctls return postive numbers on
764 * success as well). Returns a negated errno value in case of error.
766 * Note: most ioctls are forward onto the block subsystem or further
767 * down in the scsi subsystem.
769 static int sd_ioctl(struct block_device *bdev, fmode_t mode,
770 unsigned int cmd, unsigned long arg)
772 struct gendisk *disk = bdev->bd_disk;
773 struct scsi_device *sdp = scsi_disk(disk)->device;
774 void __user *p = (void __user *)arg;
777 SCSI_LOG_IOCTL(1, printk("sd_ioctl: disk=%s, cmd=0x%x\n",
778 disk->disk_name, cmd));
781 * If we are in the middle of error recovery, don't let anyone
782 * else try and use this device. Also, if error recovery fails, it
783 * may try and take the device offline, in which case all further
784 * access to the device is prohibited.
786 error = scsi_nonblockable_ioctl(sdp, cmd, p,
787 (mode & FMODE_NDELAY) != 0);
788 if (!scsi_block_when_processing_errors(sdp) || !error)
792 * Send SCSI addressing ioctls directly to mid level, send other
793 * ioctls to block level and then onto mid level if they can't be
797 case SCSI_IOCTL_GET_IDLUN:
798 case SCSI_IOCTL_GET_BUS_NUMBER:
799 return scsi_ioctl(sdp, cmd, p);
801 error = scsi_cmd_ioctl(disk->queue, disk, mode, cmd, p);
802 if (error != -ENOTTY)
805 return scsi_ioctl(sdp, cmd, p);
808 static void set_media_not_present(struct scsi_disk *sdkp)
810 sdkp->media_present = 0;
812 sdkp->device->changed = 1;
816 * sd_media_changed - check if our medium changed
817 * @disk: kernel device descriptor
819 * Returns 0 if not applicable or no change; 1 if change
821 * Note: this function is invoked from the block subsystem.
823 static int sd_media_changed(struct gendisk *disk)
825 struct scsi_disk *sdkp = scsi_disk(disk);
826 struct scsi_device *sdp = sdkp->device;
827 struct scsi_sense_hdr *sshdr = NULL;
830 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_media_changed\n"));
836 * If the device is offline, don't send any commands - just pretend as
837 * if the command failed. If the device ever comes back online, we
838 * can deal with it then. It is only because of unrecoverable errors
839 * that we would ever take a device offline in the first place.
841 if (!scsi_device_online(sdp)) {
842 set_media_not_present(sdkp);
848 * Using TEST_UNIT_READY enables differentiation between drive with
849 * no cartridge loaded - NOT READY, drive with changed cartridge -
850 * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
852 * Drives that auto spin down. eg iomega jaz 1G, will be started
853 * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
854 * sd_revalidate() is called.
858 if (scsi_block_when_processing_errors(sdp)) {
859 sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL);
860 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, SD_MAX_RETRIES,
865 * Unable to test, unit probably not ready. This usually
866 * means there is no disc in the drive. Mark as changed,
867 * and we will figure it out later once the drive is
870 if (retval || (scsi_sense_valid(sshdr) &&
871 /* 0x3a is medium not present */
872 sshdr->asc == 0x3a)) {
873 set_media_not_present(sdkp);
879 * For removable scsi disk we have to recognise the presence
880 * of a disk in the drive. This is kept in the struct scsi_disk
881 * struct and tested at open ! Daniel Roche (dan@lectra.fr)
883 sdkp->media_present = 1;
885 retval = sdp->changed;
888 if (retval != sdkp->previous_state)
889 sdev_evt_send_simple(sdp, SDEV_EVT_MEDIA_CHANGE, GFP_KERNEL);
890 sdkp->previous_state = retval;
895 static int sd_sync_cache(struct scsi_disk *sdkp)
898 struct scsi_device *sdp = sdkp->device;
899 struct scsi_sense_hdr sshdr;
901 if (!scsi_device_online(sdp))
905 for (retries = 3; retries > 0; --retries) {
906 unsigned char cmd[10] = { 0 };
908 cmd[0] = SYNCHRONIZE_CACHE;
910 * Leave the rest of the command zero to indicate
913 res = scsi_execute_req(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
914 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
920 sd_print_result(sdkp, res);
921 if (driver_byte(res) & DRIVER_SENSE)
922 sd_print_sense_hdr(sdkp, &sshdr);
930 static void sd_prepare_flush(struct request_queue *q, struct request *rq)
932 rq->cmd_type = REQ_TYPE_BLOCK_PC;
933 rq->timeout = SD_TIMEOUT;
934 rq->cmd[0] = SYNCHRONIZE_CACHE;
938 static void sd_rescan(struct device *dev)
940 struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
943 revalidate_disk(sdkp->disk);
951 * This gets directly called from VFS. When the ioctl
952 * is not recognized we go back to the other translation paths.
954 static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode,
955 unsigned int cmd, unsigned long arg)
957 struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device;
960 * If we are in the middle of error recovery, don't let anyone
961 * else try and use this device. Also, if error recovery fails, it
962 * may try and take the device offline, in which case all further
963 * access to the device is prohibited.
965 if (!scsi_block_when_processing_errors(sdev))
968 if (sdev->host->hostt->compat_ioctl) {
971 ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg);
977 * Let the static ioctl translation table take care of it.
983 static const struct block_device_operations sd_fops = {
984 .owner = THIS_MODULE,
986 .release = sd_release,
987 .locked_ioctl = sd_ioctl,
990 .compat_ioctl = sd_compat_ioctl,
992 .media_changed = sd_media_changed,
993 .revalidate_disk = sd_revalidate_disk,
996 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
998 u64 start_lba = blk_rq_pos(scmd->request);
999 u64 end_lba = blk_rq_pos(scmd->request) + (scsi_bufflen(scmd) / 512);
1003 if (!blk_fs_request(scmd->request))
1006 info_valid = scsi_get_sense_info_fld(scmd->sense_buffer,
1007 SCSI_SENSE_BUFFERSIZE,
1012 if (scsi_bufflen(scmd) <= scmd->device->sector_size)
1015 if (scmd->device->sector_size < 512) {
1016 /* only legitimate sector_size here is 256 */
1020 /* be careful ... don't want any overflows */
1021 u64 factor = scmd->device->sector_size / 512;
1022 do_div(start_lba, factor);
1023 do_div(end_lba, factor);
1026 /* The bad lba was reported incorrectly, we have no idea where
1029 if (bad_lba < start_lba || bad_lba >= end_lba)
1032 /* This computation should always be done in terms of
1033 * the resolution of the device's medium.
1035 return (bad_lba - start_lba) * scmd->device->sector_size;
1039 * sd_done - bottom half handler: called when the lower level
1040 * driver has completed (successfully or otherwise) a scsi command.
1041 * @SCpnt: mid-level's per command structure.
1043 * Note: potentially run from within an ISR. Must not block.
1045 static int sd_done(struct scsi_cmnd *SCpnt)
1047 int result = SCpnt->result;
1048 unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
1049 struct scsi_sense_hdr sshdr;
1050 int sense_valid = 0;
1051 int sense_deferred = 0;
1054 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
1056 sense_deferred = scsi_sense_is_deferred(&sshdr);
1058 #ifdef CONFIG_SCSI_LOGGING
1059 SCSI_LOG_HLCOMPLETE(1, scsi_print_result(SCpnt));
1061 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
1062 "sd_done: sb[respc,sk,asc,"
1063 "ascq]=%x,%x,%x,%x\n",
1064 sshdr.response_code,
1065 sshdr.sense_key, sshdr.asc,
1069 if (driver_byte(result) != DRIVER_SENSE &&
1070 (!sense_valid || sense_deferred))
1073 switch (sshdr.sense_key) {
1074 case HARDWARE_ERROR:
1076 good_bytes = sd_completed_bytes(SCpnt);
1078 case RECOVERED_ERROR:
1079 good_bytes = scsi_bufflen(SCpnt);
1082 /* This indicates a false check condition, so ignore it. An
1083 * unknown amount of data was transferred so treat it as an
1086 scsi_print_sense("sd", SCpnt);
1088 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1090 case ABORTED_COMMAND:
1091 if (sshdr.asc == 0x10) { /* DIF: Disk detected corruption */
1092 scsi_print_result(SCpnt);
1093 scsi_print_sense("sd", SCpnt);
1094 good_bytes = sd_completed_bytes(SCpnt);
1097 case ILLEGAL_REQUEST:
1098 if (sshdr.asc == 0x10) { /* DIX: HBA detected corruption */
1099 scsi_print_result(SCpnt);
1100 scsi_print_sense("sd", SCpnt);
1101 good_bytes = sd_completed_bytes(SCpnt);
1108 if (rq_data_dir(SCpnt->request) == READ && scsi_prot_sg_count(SCpnt))
1109 sd_dif_complete(SCpnt, good_bytes);
1114 static int media_not_present(struct scsi_disk *sdkp,
1115 struct scsi_sense_hdr *sshdr)
1118 if (!scsi_sense_valid(sshdr))
1120 /* not invoked for commands that could return deferred errors */
1121 if (sshdr->sense_key != NOT_READY &&
1122 sshdr->sense_key != UNIT_ATTENTION)
1124 if (sshdr->asc != 0x3A) /* medium not present */
1127 set_media_not_present(sdkp);
1132 * spinup disk - called only in sd_revalidate_disk()
1135 sd_spinup_disk(struct scsi_disk *sdkp)
1137 unsigned char cmd[10];
1138 unsigned long spintime_expire = 0;
1139 int retries, spintime;
1140 unsigned int the_result;
1141 struct scsi_sense_hdr sshdr;
1142 int sense_valid = 0;
1146 /* Spin up drives, as required. Only do this at boot time */
1147 /* Spinup needs to be done for module loads too. */
1152 cmd[0] = TEST_UNIT_READY;
1153 memset((void *) &cmd[1], 0, 9);
1155 the_result = scsi_execute_req(sdkp->device, cmd,
1158 SD_MAX_RETRIES, NULL);
1161 * If the drive has indicated to us that it
1162 * doesn't have any media in it, don't bother
1163 * with any more polling.
1165 if (media_not_present(sdkp, &sshdr))
1169 sense_valid = scsi_sense_valid(&sshdr);
1171 } while (retries < 3 &&
1172 (!scsi_status_is_good(the_result) ||
1173 ((driver_byte(the_result) & DRIVER_SENSE) &&
1174 sense_valid && sshdr.sense_key == UNIT_ATTENTION)));
1176 if ((driver_byte(the_result) & DRIVER_SENSE) == 0) {
1177 /* no sense, TUR either succeeded or failed
1178 * with a status error */
1179 if(!spintime && !scsi_status_is_good(the_result)) {
1180 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
1181 sd_print_result(sdkp, the_result);
1187 * The device does not want the automatic start to be issued.
1189 if (sdkp->device->no_start_on_add)
1192 if (sense_valid && sshdr.sense_key == NOT_READY) {
1193 if (sshdr.asc == 4 && sshdr.ascq == 3)
1194 break; /* manual intervention required */
1195 if (sshdr.asc == 4 && sshdr.ascq == 0xb)
1196 break; /* standby */
1197 if (sshdr.asc == 4 && sshdr.ascq == 0xc)
1198 break; /* unavailable */
1200 * Issue command to spin up drive when not ready
1203 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
1204 cmd[0] = START_STOP;
1205 cmd[1] = 1; /* Return immediately */
1206 memset((void *) &cmd[2], 0, 8);
1207 cmd[4] = 1; /* Start spin cycle */
1208 if (sdkp->device->start_stop_pwr_cond)
1210 scsi_execute_req(sdkp->device, cmd, DMA_NONE,
1212 SD_TIMEOUT, SD_MAX_RETRIES,
1214 spintime_expire = jiffies + 100 * HZ;
1217 /* Wait 1 second for next try */
1222 * Wait for USB flash devices with slow firmware.
1223 * Yes, this sense key/ASC combination shouldn't
1224 * occur here. It's characteristic of these devices.
1226 } else if (sense_valid &&
1227 sshdr.sense_key == UNIT_ATTENTION &&
1228 sshdr.asc == 0x28) {
1230 spintime_expire = jiffies + 5 * HZ;
1233 /* Wait 1 second for next try */
1236 /* we don't understand the sense code, so it's
1237 * probably pointless to loop */
1239 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
1240 sd_print_sense_hdr(sdkp, &sshdr);
1245 } while (spintime && time_before_eq(jiffies, spintime_expire));
1248 if (scsi_status_is_good(the_result))
1251 printk("not responding...\n");
1257 * Determine whether disk supports Data Integrity Field.
1259 void sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
1261 struct scsi_device *sdp = sdkp->device;
1264 if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0)
1267 type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
1269 if (type == sdkp->protection_type || !sdkp->first_scan)
1272 sdkp->protection_type = type;
1275 case SD_DIF_TYPE1_PROTECTION:
1276 case SD_DIF_TYPE3_PROTECTION:
1280 sd_printk(KERN_ERR, sdkp, "formatted with unsupported " \
1281 "protection type %u. Disabling disk!\n", type);
1286 if (scsi_host_dif_capable(sdp->host, type))
1287 sd_printk(KERN_NOTICE, sdkp,
1288 "Enabling DIF Type %u protection\n", type);
1290 sd_printk(KERN_NOTICE, sdkp,
1291 "Disabling DIF Type %u protection\n", type);
1294 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
1295 struct scsi_sense_hdr *sshdr, int sense_valid,
1298 sd_print_result(sdkp, the_result);
1299 if (driver_byte(the_result) & DRIVER_SENSE)
1300 sd_print_sense_hdr(sdkp, sshdr);
1302 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
1305 * Set dirty bit for removable devices if not ready -
1306 * sometimes drives will not report this properly.
1308 if (sdp->removable &&
1309 sense_valid && sshdr->sense_key == NOT_READY)
1313 * We used to set media_present to 0 here to indicate no media
1314 * in the drive, but some drives fail read capacity even with
1315 * media present, so we can't do that.
1317 sdkp->capacity = 0; /* unknown mapped to zero - as usual */
1321 #if RC16_LEN > SD_BUF_SIZE
1322 #error RC16_LEN must not be more than SD_BUF_SIZE
1325 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
1326 unsigned char *buffer)
1328 unsigned char cmd[16];
1329 struct scsi_sense_hdr sshdr;
1330 int sense_valid = 0;
1333 unsigned int alignment;
1334 unsigned long long lba;
1335 unsigned sector_size;
1339 cmd[0] = SERVICE_ACTION_IN;
1340 cmd[1] = SAI_READ_CAPACITY_16;
1342 memset(buffer, 0, RC16_LEN);
1344 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
1345 buffer, RC16_LEN, &sshdr,
1346 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
1348 if (media_not_present(sdkp, &sshdr))
1352 sense_valid = scsi_sense_valid(&sshdr);
1354 sshdr.sense_key == ILLEGAL_REQUEST &&
1355 (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
1357 /* Invalid Command Operation Code or
1358 * Invalid Field in CDB, just retry
1359 * silently with RC10 */
1364 } while (the_result && retries);
1367 sd_printk(KERN_NOTICE, sdkp, "READ CAPACITY(16) failed\n");
1368 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
1372 sector_size = get_unaligned_be32(&buffer[8]);
1373 lba = get_unaligned_be64(&buffer[0]);
1375 sd_read_protection_type(sdkp, buffer);
1377 if ((sizeof(sdkp->capacity) == 4) && (lba >= 0xffffffffULL)) {
1378 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
1379 "kernel compiled with support for large block "
1385 /* Logical blocks per physical block exponent */
1386 sdkp->hw_sector_size = (1 << (buffer[13] & 0xf)) * sector_size;
1388 /* Lowest aligned logical block */
1389 alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
1390 blk_queue_alignment_offset(sdp->request_queue, alignment);
1391 if (alignment && sdkp->first_scan)
1392 sd_printk(KERN_NOTICE, sdkp,
1393 "physical block alignment offset: %u\n", alignment);
1395 sdkp->capacity = lba + 1;
1399 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
1400 unsigned char *buffer)
1402 unsigned char cmd[16];
1403 struct scsi_sense_hdr sshdr;
1404 int sense_valid = 0;
1408 unsigned sector_size;
1411 cmd[0] = READ_CAPACITY;
1412 memset(&cmd[1], 0, 9);
1413 memset(buffer, 0, 8);
1415 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
1417 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
1419 if (media_not_present(sdkp, &sshdr))
1423 sense_valid = scsi_sense_valid(&sshdr);
1426 } while (the_result && retries);
1429 sd_printk(KERN_NOTICE, sdkp, "READ CAPACITY failed\n");
1430 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
1434 sector_size = get_unaligned_be32(&buffer[4]);
1435 lba = get_unaligned_be32(&buffer[0]);
1437 if ((sizeof(sdkp->capacity) == 4) && (lba == 0xffffffff)) {
1438 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
1439 "kernel compiled with support for large block "
1445 sdkp->capacity = lba + 1;
1446 sdkp->hw_sector_size = sector_size;
1450 static int sd_try_rc16_first(struct scsi_device *sdp)
1452 if (sdp->scsi_level > SCSI_SPC_2)
1454 if (scsi_device_protection(sdp))
1460 * read disk capacity
1463 sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer)
1466 struct scsi_device *sdp = sdkp->device;
1467 sector_t old_capacity = sdkp->capacity;
1469 if (sd_try_rc16_first(sdp)) {
1470 sector_size = read_capacity_16(sdkp, sdp, buffer);
1471 if (sector_size == -EOVERFLOW)
1473 if (sector_size == -ENODEV)
1475 if (sector_size < 0)
1476 sector_size = read_capacity_10(sdkp, sdp, buffer);
1477 if (sector_size < 0)
1480 sector_size = read_capacity_10(sdkp, sdp, buffer);
1481 if (sector_size == -EOVERFLOW)
1483 if (sector_size < 0)
1485 if ((sizeof(sdkp->capacity) > 4) &&
1486 (sdkp->capacity > 0xffffffffULL)) {
1487 int old_sector_size = sector_size;
1488 sd_printk(KERN_NOTICE, sdkp, "Very big device. "
1489 "Trying to use READ CAPACITY(16).\n");
1490 sector_size = read_capacity_16(sdkp, sdp, buffer);
1491 if (sector_size < 0) {
1492 sd_printk(KERN_NOTICE, sdkp,
1493 "Using 0xffffffff as device size\n");
1494 sdkp->capacity = 1 + (sector_t) 0xffffffff;
1495 sector_size = old_sector_size;
1501 /* Some devices are known to return the total number of blocks,
1502 * not the highest block number. Some devices have versions
1503 * which do this and others which do not. Some devices we might
1504 * suspect of doing this but we don't know for certain.
1506 * If we know the reported capacity is wrong, decrement it. If
1507 * we can only guess, then assume the number of blocks is even
1508 * (usually true but not always) and err on the side of lowering
1511 if (sdp->fix_capacity ||
1512 (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
1513 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
1514 "from its reported value: %llu\n",
1515 (unsigned long long) sdkp->capacity);
1520 if (sector_size == 0) {
1522 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
1526 if (sector_size != 512 &&
1527 sector_size != 1024 &&
1528 sector_size != 2048 &&
1529 sector_size != 4096 &&
1530 sector_size != 256) {
1531 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
1534 * The user might want to re-format the drive with
1535 * a supported sectorsize. Once this happens, it
1536 * would be relatively trivial to set the thing up.
1537 * For this reason, we leave the thing in the table.
1541 * set a bogus sector size so the normal read/write
1542 * logic in the block layer will eventually refuse any
1543 * request on this device without tripping over power
1544 * of two sector size assumptions
1548 blk_queue_logical_block_size(sdp->request_queue, sector_size);
1551 char cap_str_2[10], cap_str_10[10];
1552 u64 sz = (u64)sdkp->capacity << ilog2(sector_size);
1554 string_get_size(sz, STRING_UNITS_2, cap_str_2,
1556 string_get_size(sz, STRING_UNITS_10, cap_str_10,
1557 sizeof(cap_str_10));
1559 if (sdkp->first_scan || old_capacity != sdkp->capacity) {
1560 sd_printk(KERN_NOTICE, sdkp,
1561 "%llu %d-byte logical blocks: (%s/%s)\n",
1562 (unsigned long long)sdkp->capacity,
1563 sector_size, cap_str_10, cap_str_2);
1565 if (sdkp->hw_sector_size != sector_size)
1566 sd_printk(KERN_NOTICE, sdkp,
1567 "%u-byte physical blocks\n",
1568 sdkp->hw_sector_size);
1572 /* Rescale capacity to 512-byte units */
1573 if (sector_size == 4096)
1574 sdkp->capacity <<= 3;
1575 else if (sector_size == 2048)
1576 sdkp->capacity <<= 2;
1577 else if (sector_size == 1024)
1578 sdkp->capacity <<= 1;
1579 else if (sector_size == 256)
1580 sdkp->capacity >>= 1;
1582 blk_queue_physical_block_size(sdp->request_queue, sdkp->hw_sector_size);
1583 sdkp->device->sector_size = sector_size;
1586 /* called with buffer of length 512 */
1588 sd_do_mode_sense(struct scsi_device *sdp, int dbd, int modepage,
1589 unsigned char *buffer, int len, struct scsi_mode_data *data,
1590 struct scsi_sense_hdr *sshdr)
1592 return scsi_mode_sense(sdp, dbd, modepage, buffer, len,
1593 SD_TIMEOUT, SD_MAX_RETRIES, data,
1598 * read write protect setting, if possible - called only in sd_revalidate_disk()
1599 * called with buffer of length SD_BUF_SIZE
1602 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
1605 struct scsi_device *sdp = sdkp->device;
1606 struct scsi_mode_data data;
1607 int old_wp = sdkp->write_prot;
1609 set_disk_ro(sdkp->disk, 0);
1610 if (sdp->skip_ms_page_3f) {
1611 sd_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
1615 if (sdp->use_192_bytes_for_3f) {
1616 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 192, &data, NULL);
1619 * First attempt: ask for all pages (0x3F), but only 4 bytes.
1620 * We have to start carefully: some devices hang if we ask
1621 * for more than is available.
1623 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 4, &data, NULL);
1626 * Second attempt: ask for page 0 When only page 0 is
1627 * implemented, a request for page 3F may return Sense Key
1628 * 5: Illegal Request, Sense Code 24: Invalid field in
1631 if (!scsi_status_is_good(res))
1632 res = sd_do_mode_sense(sdp, 0, 0, buffer, 4, &data, NULL);
1635 * Third attempt: ask 255 bytes, as we did earlier.
1637 if (!scsi_status_is_good(res))
1638 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 255,
1642 if (!scsi_status_is_good(res)) {
1643 sd_printk(KERN_WARNING, sdkp,
1644 "Test WP failed, assume Write Enabled\n");
1646 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
1647 set_disk_ro(sdkp->disk, sdkp->write_prot);
1648 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
1649 sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
1650 sdkp->write_prot ? "on" : "off");
1651 sd_printk(KERN_DEBUG, sdkp,
1652 "Mode Sense: %02x %02x %02x %02x\n",
1653 buffer[0], buffer[1], buffer[2], buffer[3]);
1659 * sd_read_cache_type - called only from sd_revalidate_disk()
1660 * called with buffer of length SD_BUF_SIZE
1663 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
1666 struct scsi_device *sdp = sdkp->device;
1670 struct scsi_mode_data data;
1671 struct scsi_sense_hdr sshdr;
1672 int old_wce = sdkp->WCE;
1673 int old_rcd = sdkp->RCD;
1674 int old_dpofua = sdkp->DPOFUA;
1676 if (sdp->skip_ms_page_8)
1679 if (sdp->type == TYPE_RBC) {
1687 /* cautiously ask */
1688 res = sd_do_mode_sense(sdp, dbd, modepage, buffer, 4, &data, &sshdr);
1690 if (!scsi_status_is_good(res))
1693 if (!data.header_length) {
1695 sd_printk(KERN_ERR, sdkp, "Missing header in MODE_SENSE response\n");
1698 /* that went OK, now ask for the proper length */
1702 * We're only interested in the first three bytes, actually.
1703 * But the data cache page is defined for the first 20.
1710 /* Take headers and block descriptors into account */
1711 len += data.header_length + data.block_descriptor_length;
1712 if (len > SD_BUF_SIZE)
1716 res = sd_do_mode_sense(sdp, dbd, modepage, buffer, len, &data, &sshdr);
1718 if (scsi_status_is_good(res)) {
1719 int offset = data.header_length + data.block_descriptor_length;
1721 if (offset >= SD_BUF_SIZE - 2) {
1722 sd_printk(KERN_ERR, sdkp, "Malformed MODE SENSE response\n");
1726 if ((buffer[offset] & 0x3f) != modepage) {
1727 sd_printk(KERN_ERR, sdkp, "Got wrong page\n");
1731 if (modepage == 8) {
1732 sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
1733 sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
1735 sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
1739 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
1740 if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw) {
1741 sd_printk(KERN_NOTICE, sdkp,
1742 "Uses READ/WRITE(6), disabling FUA\n");
1746 if (sdkp->first_scan || old_wce != sdkp->WCE ||
1747 old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
1748 sd_printk(KERN_NOTICE, sdkp,
1749 "Write cache: %s, read cache: %s, %s\n",
1750 sdkp->WCE ? "enabled" : "disabled",
1751 sdkp->RCD ? "disabled" : "enabled",
1752 sdkp->DPOFUA ? "supports DPO and FUA"
1753 : "doesn't support DPO or FUA");
1759 if (scsi_sense_valid(&sshdr) &&
1760 sshdr.sense_key == ILLEGAL_REQUEST &&
1761 sshdr.asc == 0x24 && sshdr.ascq == 0x0)
1762 /* Invalid field in CDB */
1763 sd_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
1765 sd_printk(KERN_ERR, sdkp, "Asking for cache data failed\n");
1768 sd_printk(KERN_ERR, sdkp, "Assuming drive cache: write through\n");
1775 * The ATO bit indicates whether the DIF application tag is available
1776 * for use by the operating system.
1778 void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
1781 struct scsi_device *sdp = sdkp->device;
1782 struct scsi_mode_data data;
1783 struct scsi_sense_hdr sshdr;
1785 if (sdp->type != TYPE_DISK)
1788 if (sdkp->protection_type == 0)
1791 res = scsi_mode_sense(sdp, 1, 0x0a, buffer, 36, SD_TIMEOUT,
1792 SD_MAX_RETRIES, &data, &sshdr);
1794 if (!scsi_status_is_good(res) || !data.header_length ||
1796 sd_printk(KERN_WARNING, sdkp,
1797 "getting Control mode page failed, assume no ATO\n");
1799 if (scsi_sense_valid(&sshdr))
1800 sd_print_sense_hdr(sdkp, &sshdr);
1805 offset = data.header_length + data.block_descriptor_length;
1807 if ((buffer[offset] & 0x3f) != 0x0a) {
1808 sd_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
1812 if ((buffer[offset + 5] & 0x80) == 0)
1821 * sd_read_block_limits - Query disk device for preferred I/O sizes.
1822 * @disk: disk to query
1824 static void sd_read_block_limits(struct scsi_disk *sdkp)
1826 unsigned int sector_sz = sdkp->device->sector_size;
1829 /* Block Limits VPD */
1830 buffer = scsi_get_vpd_page(sdkp->device, 0xb0);
1835 blk_queue_io_min(sdkp->disk->queue,
1836 get_unaligned_be16(&buffer[6]) * sector_sz);
1837 blk_queue_io_opt(sdkp->disk->queue,
1838 get_unaligned_be32(&buffer[12]) * sector_sz);
1844 * sd_read_block_characteristics - Query block dev. characteristics
1845 * @disk: disk to query
1847 static void sd_read_block_characteristics(struct scsi_disk *sdkp)
1852 /* Block Device Characteristics VPD */
1853 buffer = scsi_get_vpd_page(sdkp->device, 0xb1);
1858 rot = get_unaligned_be16(&buffer[4]);
1861 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, sdkp->disk->queue);
1866 static int sd_try_extended_inquiry(struct scsi_device *sdp)
1869 * Although VPD inquiries can go to SCSI-2 type devices,
1870 * some USB ones crash on receiving them, and the pages
1871 * we currently ask for are for SPC-3 and beyond
1873 if (sdp->scsi_level > SCSI_SPC_2)
1879 * sd_revalidate_disk - called the first time a new disk is seen,
1880 * performs disk spin up, read_capacity, etc.
1881 * @disk: struct gendisk we care about
1883 static int sd_revalidate_disk(struct gendisk *disk)
1885 struct scsi_disk *sdkp = scsi_disk(disk);
1886 struct scsi_device *sdp = sdkp->device;
1887 unsigned char *buffer;
1890 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
1891 "sd_revalidate_disk\n"));
1894 * If the device is offline, don't try and read capacity or any
1895 * of the other niceties.
1897 if (!scsi_device_online(sdp))
1900 buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
1902 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
1903 "allocation failure.\n");
1907 sd_spinup_disk(sdkp);
1910 * Without media there is no reason to ask; moreover, some devices
1911 * react badly if we do.
1913 if (sdkp->media_present) {
1914 sd_read_capacity(sdkp, buffer);
1916 if (sd_try_extended_inquiry(sdp)) {
1917 sd_read_block_limits(sdkp);
1918 sd_read_block_characteristics(sdkp);
1921 sd_read_write_protect_flag(sdkp, buffer);
1922 sd_read_cache_type(sdkp, buffer);
1923 sd_read_app_tag_own(sdkp, buffer);
1926 sdkp->first_scan = 0;
1929 * We now have all cache related info, determine how we deal
1930 * with ordered requests. Note that as the current SCSI
1931 * dispatch function can alter request order, we cannot use
1932 * QUEUE_ORDERED_TAG_* even when ordered tag is supported.
1935 ordered = sdkp->DPOFUA
1936 ? QUEUE_ORDERED_DRAIN_FUA : QUEUE_ORDERED_DRAIN_FLUSH;
1938 ordered = QUEUE_ORDERED_DRAIN;
1940 blk_queue_ordered(sdkp->disk->queue, ordered, sd_prepare_flush);
1942 set_capacity(disk, sdkp->capacity);
1950 * sd_format_disk_name - format disk name
1951 * @prefix: name prefix - ie. "sd" for SCSI disks
1952 * @index: index of the disk to format name for
1953 * @buf: output buffer
1954 * @buflen: length of the output buffer
1956 * SCSI disk names starts at sda. The 26th device is sdz and the
1957 * 27th is sdaa. The last one for two lettered suffix is sdzz
1958 * which is followed by sdaaa.
1960 * This is basically 26 base counting with one extra 'nil' entry
1961 * at the beggining from the second digit on and can be
1962 * determined using similar method as 26 base conversion with the
1963 * index shifted -1 after each digit is computed.
1969 * 0 on success, -errno on failure.
1971 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
1973 const int base = 'z' - 'a' + 1;
1974 char *begin = buf + strlen(prefix);
1975 char *end = buf + buflen;
1985 *--p = 'a' + (index % unit);
1986 index = (index / unit) - 1;
1987 } while (index >= 0);
1989 memmove(begin, p, end - p);
1990 memcpy(buf, prefix, strlen(prefix));
1996 * The asynchronous part of sd_probe
1998 static void sd_probe_async(void *data, async_cookie_t cookie)
2000 struct scsi_disk *sdkp = data;
2001 struct scsi_device *sdp;
2008 index = sdkp->index;
2009 dev = &sdp->sdev_gendev;
2011 if (index < SD_MAX_DISKS) {
2012 gd->major = sd_major((index & 0xf0) >> 4);
2013 gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
2014 gd->minors = SD_MINORS;
2016 gd->fops = &sd_fops;
2017 gd->private_data = &sdkp->driver;
2018 gd->queue = sdkp->device->request_queue;
2020 /* defaults, until the device tells us otherwise */
2021 sdp->sector_size = 512;
2023 sdkp->media_present = 1;
2024 sdkp->write_prot = 0;
2028 sdkp->first_scan = 1;
2030 sd_revalidate_disk(gd);
2032 blk_queue_prep_rq(sdp->request_queue, sd_prep_fn);
2034 gd->driverfs_dev = &sdp->sdev_gendev;
2035 gd->flags = GENHD_FL_EXT_DEVT | GENHD_FL_DRIVERFS;
2037 gd->flags |= GENHD_FL_REMOVABLE;
2039 dev_set_drvdata(dev, sdkp);
2041 sd_dif_config_host(sdkp);
2043 sd_revalidate_disk(gd);
2045 sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
2046 sdp->removable ? "removable " : "");
2047 put_device(&sdkp->dev);
2051 * sd_probe - called during driver initialization and whenever a
2052 * new scsi device is attached to the system. It is called once
2053 * for each scsi device (not just disks) present.
2054 * @dev: pointer to device object
2056 * Returns 0 if successful (or not interested in this scsi device
2057 * (e.g. scanner)); 1 when there is an error.
2059 * Note: this function is invoked from the scsi mid-level.
2060 * This function sets up the mapping between a given
2061 * <host,channel,id,lun> (found in sdp) and new device name
2062 * (e.g. /dev/sda). More precisely it is the block device major
2063 * and minor number that is chosen here.
2065 * Assume sd_attach is not re-entrant (for time being)
2066 * Also think about sd_attach() and sd_remove() running coincidentally.
2068 static int sd_probe(struct device *dev)
2070 struct scsi_device *sdp = to_scsi_device(dev);
2071 struct scsi_disk *sdkp;
2077 if (sdp->type != TYPE_DISK && sdp->type != TYPE_MOD && sdp->type != TYPE_RBC)
2080 SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
2084 sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
2088 gd = alloc_disk(SD_MINORS);
2093 if (!ida_pre_get(&sd_index_ida, GFP_KERNEL))
2096 spin_lock(&sd_index_lock);
2097 error = ida_get_new(&sd_index_ida, &index);
2098 spin_unlock(&sd_index_lock);
2099 } while (error == -EAGAIN);
2104 error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
2106 goto out_free_index;
2109 sdkp->driver = &sd_template;
2111 sdkp->index = index;
2113 sdkp->previous_state = 1;
2115 if (!sdp->request_queue->rq_timeout) {
2116 if (sdp->type != TYPE_MOD)
2117 blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
2119 blk_queue_rq_timeout(sdp->request_queue,
2123 device_initialize(&sdkp->dev);
2124 sdkp->dev.parent = &sdp->sdev_gendev;
2125 sdkp->dev.class = &sd_disk_class;
2126 dev_set_name(&sdkp->dev, dev_name(&sdp->sdev_gendev));
2128 if (device_add(&sdkp->dev))
2129 goto out_free_index;
2131 get_device(&sdp->sdev_gendev);
2133 get_device(&sdkp->dev); /* prevent release before async_schedule */
2134 async_schedule(sd_probe_async, sdkp);
2139 spin_lock(&sd_index_lock);
2140 ida_remove(&sd_index_ida, index);
2141 spin_unlock(&sd_index_lock);
2151 * sd_remove - called whenever a scsi disk (previously recognized by
2152 * sd_probe) is detached from the system. It is called (potentially
2153 * multiple times) during sd module unload.
2154 * @sdp: pointer to mid level scsi device object
2156 * Note: this function is invoked from the scsi mid-level.
2157 * This function potentially frees up a device name (e.g. /dev/sdc)
2158 * that could be re-used by a subsequent sd_probe().
2159 * This function is not called when the built-in sd driver is "exit-ed".
2161 static int sd_remove(struct device *dev)
2163 struct scsi_disk *sdkp;
2165 async_synchronize_full();
2166 sdkp = dev_get_drvdata(dev);
2167 blk_queue_prep_rq(sdkp->device->request_queue, scsi_prep_fn);
2168 device_del(&sdkp->dev);
2169 del_gendisk(sdkp->disk);
2172 mutex_lock(&sd_ref_mutex);
2173 dev_set_drvdata(dev, NULL);
2174 put_device(&sdkp->dev);
2175 mutex_unlock(&sd_ref_mutex);
2181 * scsi_disk_release - Called to free the scsi_disk structure
2182 * @dev: pointer to embedded class device
2184 * sd_ref_mutex must be held entering this routine. Because it is
2185 * called on last put, you should always use the scsi_disk_get()
2186 * scsi_disk_put() helpers which manipulate the semaphore directly
2187 * and never do a direct put_device.
2189 static void scsi_disk_release(struct device *dev)
2191 struct scsi_disk *sdkp = to_scsi_disk(dev);
2192 struct gendisk *disk = sdkp->disk;
2194 spin_lock(&sd_index_lock);
2195 ida_remove(&sd_index_ida, sdkp->index);
2196 spin_unlock(&sd_index_lock);
2198 disk->private_data = NULL;
2200 put_device(&sdkp->device->sdev_gendev);
2205 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
2207 unsigned char cmd[6] = { START_STOP }; /* START_VALID */
2208 struct scsi_sense_hdr sshdr;
2209 struct scsi_device *sdp = sdkp->device;
2213 cmd[4] |= 1; /* START */
2215 if (sdp->start_stop_pwr_cond)
2216 cmd[4] |= start ? 1 << 4 : 3 << 4; /* Active or Standby */
2218 if (!scsi_device_online(sdp))
2221 res = scsi_execute_req(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
2222 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
2224 sd_printk(KERN_WARNING, sdkp, "START_STOP FAILED\n");
2225 sd_print_result(sdkp, res);
2226 if (driver_byte(res) & DRIVER_SENSE)
2227 sd_print_sense_hdr(sdkp, &sshdr);
2234 * Send a SYNCHRONIZE CACHE instruction down to the device through
2235 * the normal SCSI command structure. Wait for the command to
2238 static void sd_shutdown(struct device *dev)
2240 struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
2243 return; /* this can happen */
2246 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
2247 sd_sync_cache(sdkp);
2250 if (system_state != SYSTEM_RESTART && sdkp->device->manage_start_stop) {
2251 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
2252 sd_start_stop_device(sdkp, 0);
2255 scsi_disk_put(sdkp);
2258 static int sd_suspend(struct device *dev, pm_message_t mesg)
2260 struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
2264 return 0; /* this can happen */
2267 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
2268 ret = sd_sync_cache(sdkp);
2273 if ((mesg.event & PM_EVENT_SLEEP) && sdkp->device->manage_start_stop) {
2274 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
2275 ret = sd_start_stop_device(sdkp, 0);
2279 scsi_disk_put(sdkp);
2283 static int sd_resume(struct device *dev)
2285 struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
2288 if (!sdkp->device->manage_start_stop)
2291 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
2292 ret = sd_start_stop_device(sdkp, 1);
2295 scsi_disk_put(sdkp);
2300 * init_sd - entry point for this driver (both when built in or when
2303 * Note: this function registers this driver with the scsi mid-level.
2305 static int __init init_sd(void)
2307 int majors = 0, i, err;
2309 SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
2311 for (i = 0; i < SD_MAJORS; i++)
2312 if (register_blkdev(sd_major(i), "sd") == 0)
2318 err = class_register(&sd_disk_class);
2322 err = scsi_register_driver(&sd_template.gendrv);
2329 class_unregister(&sd_disk_class);
2331 for (i = 0; i < SD_MAJORS; i++)
2332 unregister_blkdev(sd_major(i), "sd");
2337 * exit_sd - exit point for this driver (when it is a module).
2339 * Note: this function unregisters this driver from the scsi mid-level.
2341 static void __exit exit_sd(void)
2345 SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
2347 scsi_unregister_driver(&sd_template.gendrv);
2348 class_unregister(&sd_disk_class);
2350 for (i = 0; i < SD_MAJORS; i++)
2351 unregister_blkdev(sd_major(i), "sd");
2354 module_init(init_sd);
2355 module_exit(exit_sd);
2357 static void sd_print_sense_hdr(struct scsi_disk *sdkp,
2358 struct scsi_sense_hdr *sshdr)
2360 sd_printk(KERN_INFO, sdkp, "");
2361 scsi_show_sense_hdr(sshdr);
2362 sd_printk(KERN_INFO, sdkp, "");
2363 scsi_show_extd_sense(sshdr->asc, sshdr->ascq);
2366 static void sd_print_result(struct scsi_disk *sdkp, int result)
2368 sd_printk(KERN_INFO, sdkp, "");
2369 scsi_show_result(result);