1 // SPDX-License-Identifier: GPL-2.0-only
3 * sd.c Copyright (C) 1992 Drew Eckhardt
4 * Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
6 * Linux scsi disk driver
7 * Initial versions: Drew Eckhardt
8 * Subsequent revisions: Eric Youngdale
9 * Modification history:
12 * outstanding request, and other enhancements.
13 * Support loadable low-level scsi drivers.
15 * eight major numbers.
18 * sd_init and cleanups.
20 * not being read in sd_open. Fix problem where removable media
21 * could be ejected after sd_open.
25 * Support 32k/1M disks.
27 * Logging policy (needs CONFIG_SCSI_LOGGING defined):
28 * - setting up transfer: SCSI_LOG_HLQUEUE levels 1 and 2
29 * - end of transfer (bh + scsi_lib): SCSI_LOG_HLCOMPLETE level 1
30 * - entering sd_ioctl: SCSI_LOG_IOCTL level 1
31 * - entering other commands: SCSI_LOG_HLQUEUE level 3
32 * Note: when the logging level is set by the user, it must be greater
33 * than the level indicated above to trigger output.
36 #include <linux/module.h>
38 #include <linux/kernel.h>
40 #include <linux/bio.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/blk-pm.h>
49 #include <linux/delay.h>
50 #include <linux/rw_hint.h>
51 #include <linux/major.h>
52 #include <linux/mutex.h>
53 #include <linux/string_helpers.h>
54 #include <linux/slab.h>
55 #include <linux/sed-opal.h>
56 #include <linux/pm_runtime.h>
58 #include <linux/t10-pi.h>
59 #include <linux/uaccess.h>
60 #include <asm/unaligned.h>
62 #include <scsi/scsi.h>
63 #include <scsi/scsi_cmnd.h>
64 #include <scsi/scsi_dbg.h>
65 #include <scsi/scsi_device.h>
66 #include <scsi/scsi_driver.h>
67 #include <scsi/scsi_eh.h>
68 #include <scsi/scsi_host.h>
69 #include <scsi/scsi_ioctl.h>
70 #include <scsi/scsicam.h>
71 #include <scsi/scsi_common.h>
74 #include "scsi_priv.h"
75 #include "scsi_logging.h"
77 MODULE_AUTHOR("Eric Youngdale");
78 MODULE_DESCRIPTION("SCSI disk (sd) driver");
79 MODULE_LICENSE("GPL");
81 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
82 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
88 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
89 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
90 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
91 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
92 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
93 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
94 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
95 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
96 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
97 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
98 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
99 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
100 MODULE_ALIAS_SCSI_DEVICE(TYPE_ZBC);
104 static void sd_config_discard(struct scsi_disk *sdkp, struct queue_limits *lim,
106 static void sd_config_write_same(struct scsi_disk *sdkp,
107 struct queue_limits *lim);
108 static int sd_revalidate_disk(struct gendisk *);
109 static void sd_unlock_native_capacity(struct gendisk *disk);
110 static void sd_shutdown(struct device *);
111 static void scsi_disk_release(struct device *cdev);
113 static DEFINE_IDA(sd_index_ida);
115 static mempool_t *sd_page_pool;
116 static struct lock_class_key sd_bio_compl_lkclass;
118 static const char *sd_cache_types[] = {
119 "write through", "none", "write back",
120 "write back, no read (daft)"
123 static void sd_set_flush_flag(struct scsi_disk *sdkp,
124 struct queue_limits *lim)
127 lim->features |= BLK_FEAT_WRITE_CACHE;
129 lim->features |= BLK_FEAT_FUA;
131 lim->features &= ~BLK_FEAT_FUA;
133 lim->features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
138 cache_type_store(struct device *dev, struct device_attribute *attr,
139 const char *buf, size_t count)
141 int ct, rcd, wce, sp;
142 struct scsi_disk *sdkp = to_scsi_disk(dev);
143 struct scsi_device *sdp = sdkp->device;
146 struct scsi_mode_data data;
147 struct scsi_sense_hdr sshdr;
148 static const char temp[] = "temporary ";
151 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
152 /* no cache control on RBC devices; theoretically they
153 * can do it, but there's probably so many exceptions
154 * it's not worth the risk */
157 if (strncmp(buf, temp, sizeof(temp) - 1) == 0) {
158 buf += sizeof(temp) - 1;
159 sdkp->cache_override = 1;
161 sdkp->cache_override = 0;
164 ct = sysfs_match_string(sd_cache_types, buf);
168 rcd = ct & 0x01 ? 1 : 0;
169 wce = (ct & 0x02) && !sdkp->write_prot ? 1 : 0;
171 if (sdkp->cache_override) {
172 struct queue_limits lim;
177 lim = queue_limits_start_update(sdkp->disk->queue);
178 sd_set_flush_flag(sdkp, &lim);
179 blk_mq_freeze_queue(sdkp->disk->queue);
180 ret = queue_limits_commit_update(sdkp->disk->queue, &lim);
181 blk_mq_unfreeze_queue(sdkp->disk->queue);
187 if (scsi_mode_sense(sdp, 0x08, 8, 0, buffer, sizeof(buffer), SD_TIMEOUT,
188 sdkp->max_retries, &data, NULL))
190 len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
191 data.block_descriptor_length);
192 buffer_data = buffer + data.header_length +
193 data.block_descriptor_length;
194 buffer_data[2] &= ~0x05;
195 buffer_data[2] |= wce << 2 | rcd;
196 sp = buffer_data[0] & 0x80 ? 1 : 0;
197 buffer_data[0] &= ~0x80;
200 * Ensure WP, DPOFUA, and RESERVED fields are cleared in
201 * received mode parameter buffer before doing MODE SELECT.
203 data.device_specific = 0;
205 ret = scsi_mode_select(sdp, 1, sp, buffer_data, len, SD_TIMEOUT,
206 sdkp->max_retries, &data, &sshdr);
208 if (ret > 0 && scsi_sense_valid(&sshdr))
209 sd_print_sense_hdr(sdkp, &sshdr);
212 sd_revalidate_disk(sdkp->disk);
217 manage_start_stop_show(struct device *dev,
218 struct device_attribute *attr, char *buf)
220 struct scsi_disk *sdkp = to_scsi_disk(dev);
221 struct scsi_device *sdp = sdkp->device;
223 return sysfs_emit(buf, "%u\n",
224 sdp->manage_system_start_stop &&
225 sdp->manage_runtime_start_stop &&
226 sdp->manage_shutdown);
228 static DEVICE_ATTR_RO(manage_start_stop);
231 manage_system_start_stop_show(struct device *dev,
232 struct device_attribute *attr, char *buf)
234 struct scsi_disk *sdkp = to_scsi_disk(dev);
235 struct scsi_device *sdp = sdkp->device;
237 return sysfs_emit(buf, "%u\n", sdp->manage_system_start_stop);
241 manage_system_start_stop_store(struct device *dev,
242 struct device_attribute *attr,
243 const char *buf, size_t count)
245 struct scsi_disk *sdkp = to_scsi_disk(dev);
246 struct scsi_device *sdp = sdkp->device;
249 if (!capable(CAP_SYS_ADMIN))
252 if (kstrtobool(buf, &v))
255 sdp->manage_system_start_stop = v;
259 static DEVICE_ATTR_RW(manage_system_start_stop);
262 manage_runtime_start_stop_show(struct device *dev,
263 struct device_attribute *attr, char *buf)
265 struct scsi_disk *sdkp = to_scsi_disk(dev);
266 struct scsi_device *sdp = sdkp->device;
268 return sysfs_emit(buf, "%u\n", sdp->manage_runtime_start_stop);
272 manage_runtime_start_stop_store(struct device *dev,
273 struct device_attribute *attr,
274 const char *buf, size_t count)
276 struct scsi_disk *sdkp = to_scsi_disk(dev);
277 struct scsi_device *sdp = sdkp->device;
280 if (!capable(CAP_SYS_ADMIN))
283 if (kstrtobool(buf, &v))
286 sdp->manage_runtime_start_stop = v;
290 static DEVICE_ATTR_RW(manage_runtime_start_stop);
292 static ssize_t manage_shutdown_show(struct device *dev,
293 struct device_attribute *attr, char *buf)
295 struct scsi_disk *sdkp = to_scsi_disk(dev);
296 struct scsi_device *sdp = sdkp->device;
298 return sysfs_emit(buf, "%u\n", sdp->manage_shutdown);
301 static ssize_t manage_shutdown_store(struct device *dev,
302 struct device_attribute *attr,
303 const char *buf, size_t count)
305 struct scsi_disk *sdkp = to_scsi_disk(dev);
306 struct scsi_device *sdp = sdkp->device;
309 if (!capable(CAP_SYS_ADMIN))
312 if (kstrtobool(buf, &v))
315 sdp->manage_shutdown = v;
319 static DEVICE_ATTR_RW(manage_shutdown);
322 allow_restart_show(struct device *dev, struct device_attribute *attr, char *buf)
324 struct scsi_disk *sdkp = to_scsi_disk(dev);
326 return sprintf(buf, "%u\n", sdkp->device->allow_restart);
330 allow_restart_store(struct device *dev, struct device_attribute *attr,
331 const char *buf, size_t count)
334 struct scsi_disk *sdkp = to_scsi_disk(dev);
335 struct scsi_device *sdp = sdkp->device;
337 if (!capable(CAP_SYS_ADMIN))
340 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
343 if (kstrtobool(buf, &v))
346 sdp->allow_restart = v;
350 static DEVICE_ATTR_RW(allow_restart);
353 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
355 struct scsi_disk *sdkp = to_scsi_disk(dev);
356 int ct = sdkp->RCD + 2*sdkp->WCE;
358 return sprintf(buf, "%s\n", sd_cache_types[ct]);
360 static DEVICE_ATTR_RW(cache_type);
363 FUA_show(struct device *dev, struct device_attribute *attr, char *buf)
365 struct scsi_disk *sdkp = to_scsi_disk(dev);
367 return sprintf(buf, "%u\n", sdkp->DPOFUA);
369 static DEVICE_ATTR_RO(FUA);
372 protection_type_show(struct device *dev, struct device_attribute *attr,
375 struct scsi_disk *sdkp = to_scsi_disk(dev);
377 return sprintf(buf, "%u\n", sdkp->protection_type);
381 protection_type_store(struct device *dev, struct device_attribute *attr,
382 const char *buf, size_t count)
384 struct scsi_disk *sdkp = to_scsi_disk(dev);
388 if (!capable(CAP_SYS_ADMIN))
391 err = kstrtouint(buf, 10, &val);
396 if (val <= T10_PI_TYPE3_PROTECTION)
397 sdkp->protection_type = val;
401 static DEVICE_ATTR_RW(protection_type);
404 protection_mode_show(struct device *dev, struct device_attribute *attr,
407 struct scsi_disk *sdkp = to_scsi_disk(dev);
408 struct scsi_device *sdp = sdkp->device;
409 unsigned int dif, dix;
411 dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
412 dix = scsi_host_dix_capable(sdp->host, sdkp->protection_type);
414 if (!dix && scsi_host_dix_capable(sdp->host, T10_PI_TYPE0_PROTECTION)) {
420 return sprintf(buf, "none\n");
422 return sprintf(buf, "%s%u\n", dix ? "dix" : "dif", dif);
424 static DEVICE_ATTR_RO(protection_mode);
427 app_tag_own_show(struct device *dev, struct device_attribute *attr, char *buf)
429 struct scsi_disk *sdkp = to_scsi_disk(dev);
431 return sprintf(buf, "%u\n", sdkp->ATO);
433 static DEVICE_ATTR_RO(app_tag_own);
436 thin_provisioning_show(struct device *dev, struct device_attribute *attr,
439 struct scsi_disk *sdkp = to_scsi_disk(dev);
441 return sprintf(buf, "%u\n", sdkp->lbpme);
443 static DEVICE_ATTR_RO(thin_provisioning);
445 /* sysfs_match_string() requires dense arrays */
446 static const char *lbp_mode[] = {
447 [SD_LBP_FULL] = "full",
448 [SD_LBP_UNMAP] = "unmap",
449 [SD_LBP_WS16] = "writesame_16",
450 [SD_LBP_WS10] = "writesame_10",
451 [SD_LBP_ZERO] = "writesame_zero",
452 [SD_LBP_DISABLE] = "disabled",
456 provisioning_mode_show(struct device *dev, struct device_attribute *attr,
459 struct scsi_disk *sdkp = to_scsi_disk(dev);
461 return sprintf(buf, "%s\n", lbp_mode[sdkp->provisioning_mode]);
465 provisioning_mode_store(struct device *dev, struct device_attribute *attr,
466 const char *buf, size_t count)
468 struct scsi_disk *sdkp = to_scsi_disk(dev);
469 struct scsi_device *sdp = sdkp->device;
470 struct queue_limits lim;
473 if (!capable(CAP_SYS_ADMIN))
476 if (sdp->type != TYPE_DISK)
479 mode = sysfs_match_string(lbp_mode, buf);
483 lim = queue_limits_start_update(sdkp->disk->queue);
484 sd_config_discard(sdkp, &lim, mode);
485 blk_mq_freeze_queue(sdkp->disk->queue);
486 err = queue_limits_commit_update(sdkp->disk->queue, &lim);
487 blk_mq_unfreeze_queue(sdkp->disk->queue);
492 static DEVICE_ATTR_RW(provisioning_mode);
494 /* sysfs_match_string() requires dense arrays */
495 static const char *zeroing_mode[] = {
496 [SD_ZERO_WRITE] = "write",
497 [SD_ZERO_WS] = "writesame",
498 [SD_ZERO_WS16_UNMAP] = "writesame_16_unmap",
499 [SD_ZERO_WS10_UNMAP] = "writesame_10_unmap",
503 zeroing_mode_show(struct device *dev, struct device_attribute *attr,
506 struct scsi_disk *sdkp = to_scsi_disk(dev);
508 return sprintf(buf, "%s\n", zeroing_mode[sdkp->zeroing_mode]);
512 zeroing_mode_store(struct device *dev, struct device_attribute *attr,
513 const char *buf, size_t count)
515 struct scsi_disk *sdkp = to_scsi_disk(dev);
518 if (!capable(CAP_SYS_ADMIN))
521 mode = sysfs_match_string(zeroing_mode, buf);
525 sdkp->zeroing_mode = mode;
529 static DEVICE_ATTR_RW(zeroing_mode);
532 max_medium_access_timeouts_show(struct device *dev,
533 struct device_attribute *attr, char *buf)
535 struct scsi_disk *sdkp = to_scsi_disk(dev);
537 return sprintf(buf, "%u\n", sdkp->max_medium_access_timeouts);
541 max_medium_access_timeouts_store(struct device *dev,
542 struct device_attribute *attr, const char *buf,
545 struct scsi_disk *sdkp = to_scsi_disk(dev);
548 if (!capable(CAP_SYS_ADMIN))
551 err = kstrtouint(buf, 10, &sdkp->max_medium_access_timeouts);
553 return err ? err : count;
555 static DEVICE_ATTR_RW(max_medium_access_timeouts);
558 max_write_same_blocks_show(struct device *dev, struct device_attribute *attr,
561 struct scsi_disk *sdkp = to_scsi_disk(dev);
563 return sprintf(buf, "%u\n", sdkp->max_ws_blocks);
567 max_write_same_blocks_store(struct device *dev, struct device_attribute *attr,
568 const char *buf, size_t count)
570 struct scsi_disk *sdkp = to_scsi_disk(dev);
571 struct scsi_device *sdp = sdkp->device;
572 struct queue_limits lim;
576 if (!capable(CAP_SYS_ADMIN))
579 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
582 err = kstrtoul(buf, 10, &max);
588 sdp->no_write_same = 1;
589 else if (max <= SD_MAX_WS16_BLOCKS) {
590 sdp->no_write_same = 0;
591 sdkp->max_ws_blocks = max;
594 lim = queue_limits_start_update(sdkp->disk->queue);
595 sd_config_write_same(sdkp, &lim);
596 blk_mq_freeze_queue(sdkp->disk->queue);
597 err = queue_limits_commit_update(sdkp->disk->queue, &lim);
598 blk_mq_unfreeze_queue(sdkp->disk->queue);
603 static DEVICE_ATTR_RW(max_write_same_blocks);
606 zoned_cap_show(struct device *dev, struct device_attribute *attr, char *buf)
608 struct scsi_disk *sdkp = to_scsi_disk(dev);
610 if (sdkp->device->type == TYPE_ZBC)
611 return sprintf(buf, "host-managed\n");
612 if (sdkp->zoned == 1)
613 return sprintf(buf, "host-aware\n");
614 if (sdkp->zoned == 2)
615 return sprintf(buf, "drive-managed\n");
616 return sprintf(buf, "none\n");
618 static DEVICE_ATTR_RO(zoned_cap);
621 max_retries_store(struct device *dev, struct device_attribute *attr,
622 const char *buf, size_t count)
624 struct scsi_disk *sdkp = to_scsi_disk(dev);
625 struct scsi_device *sdev = sdkp->device;
628 err = kstrtoint(buf, 10, &retries);
632 if (retries == SCSI_CMD_RETRIES_NO_LIMIT || retries <= SD_MAX_RETRIES) {
633 sdkp->max_retries = retries;
637 sdev_printk(KERN_ERR, sdev, "max_retries must be between -1 and %d\n",
643 max_retries_show(struct device *dev, struct device_attribute *attr,
646 struct scsi_disk *sdkp = to_scsi_disk(dev);
648 return sprintf(buf, "%d\n", sdkp->max_retries);
651 static DEVICE_ATTR_RW(max_retries);
653 static struct attribute *sd_disk_attrs[] = {
654 &dev_attr_cache_type.attr,
656 &dev_attr_allow_restart.attr,
657 &dev_attr_manage_start_stop.attr,
658 &dev_attr_manage_system_start_stop.attr,
659 &dev_attr_manage_runtime_start_stop.attr,
660 &dev_attr_manage_shutdown.attr,
661 &dev_attr_protection_type.attr,
662 &dev_attr_protection_mode.attr,
663 &dev_attr_app_tag_own.attr,
664 &dev_attr_thin_provisioning.attr,
665 &dev_attr_provisioning_mode.attr,
666 &dev_attr_zeroing_mode.attr,
667 &dev_attr_max_write_same_blocks.attr,
668 &dev_attr_max_medium_access_timeouts.attr,
669 &dev_attr_zoned_cap.attr,
670 &dev_attr_max_retries.attr,
673 ATTRIBUTE_GROUPS(sd_disk);
675 static struct class sd_disk_class = {
677 .dev_release = scsi_disk_release,
678 .dev_groups = sd_disk_groups,
682 * Don't request a new module, as that could deadlock in multipath
685 static void sd_default_probe(dev_t devt)
690 * Device no to disk mapping:
692 * major disc2 disc p1
693 * |............|.............|....|....| <- dev_t
696 * Inside a major, we have 16k disks, however mapped non-
697 * contiguously. The first 16 disks are for major0, the next
698 * ones with major1, ... Disk 256 is for major0 again, disk 272
700 * As we stay compatible with our numbering scheme, we can reuse
701 * the well-know SCSI majors 8, 65--71, 136--143.
703 static int sd_major(int major_idx)
707 return SCSI_DISK0_MAJOR;
709 return SCSI_DISK1_MAJOR + major_idx - 1;
711 return SCSI_DISK8_MAJOR + major_idx - 8;
714 return 0; /* shut up gcc */
718 #ifdef CONFIG_BLK_SED_OPAL
719 static int sd_sec_submit(void *data, u16 spsp, u8 secp, void *buffer,
720 size_t len, bool send)
722 struct scsi_disk *sdkp = data;
723 struct scsi_device *sdev = sdkp->device;
725 const struct scsi_exec_args exec_args = {
726 .req_flags = BLK_MQ_REQ_PM,
730 cdb[0] = send ? SECURITY_PROTOCOL_OUT : SECURITY_PROTOCOL_IN;
732 put_unaligned_be16(spsp, &cdb[2]);
733 put_unaligned_be32(len, &cdb[6]);
735 ret = scsi_execute_cmd(sdev, cdb, send ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN,
736 buffer, len, SD_TIMEOUT, sdkp->max_retries,
738 return ret <= 0 ? ret : -EIO;
740 #endif /* CONFIG_BLK_SED_OPAL */
743 * Look up the DIX operation based on whether the command is read or
744 * write and whether dix and dif are enabled.
746 static unsigned int sd_prot_op(bool write, bool dix, bool dif)
748 /* Lookup table: bit 2 (write), bit 1 (dix), bit 0 (dif) */
749 static const unsigned int ops[] = { /* wrt dix dif */
750 SCSI_PROT_NORMAL, /* 0 0 0 */
751 SCSI_PROT_READ_STRIP, /* 0 0 1 */
752 SCSI_PROT_READ_INSERT, /* 0 1 0 */
753 SCSI_PROT_READ_PASS, /* 0 1 1 */
754 SCSI_PROT_NORMAL, /* 1 0 0 */
755 SCSI_PROT_WRITE_INSERT, /* 1 0 1 */
756 SCSI_PROT_WRITE_STRIP, /* 1 1 0 */
757 SCSI_PROT_WRITE_PASS, /* 1 1 1 */
760 return ops[write << 2 | dix << 1 | dif];
764 * Returns a mask of the protection flags that are valid for a given DIX
767 static unsigned int sd_prot_flag_mask(unsigned int prot_op)
769 static const unsigned int flag_mask[] = {
770 [SCSI_PROT_NORMAL] = 0,
772 [SCSI_PROT_READ_STRIP] = SCSI_PROT_TRANSFER_PI |
773 SCSI_PROT_GUARD_CHECK |
774 SCSI_PROT_REF_CHECK |
775 SCSI_PROT_REF_INCREMENT,
777 [SCSI_PROT_READ_INSERT] = SCSI_PROT_REF_INCREMENT |
778 SCSI_PROT_IP_CHECKSUM,
780 [SCSI_PROT_READ_PASS] = SCSI_PROT_TRANSFER_PI |
781 SCSI_PROT_GUARD_CHECK |
782 SCSI_PROT_REF_CHECK |
783 SCSI_PROT_REF_INCREMENT |
784 SCSI_PROT_IP_CHECKSUM,
786 [SCSI_PROT_WRITE_INSERT] = SCSI_PROT_TRANSFER_PI |
787 SCSI_PROT_REF_INCREMENT,
789 [SCSI_PROT_WRITE_STRIP] = SCSI_PROT_GUARD_CHECK |
790 SCSI_PROT_REF_CHECK |
791 SCSI_PROT_REF_INCREMENT |
792 SCSI_PROT_IP_CHECKSUM,
794 [SCSI_PROT_WRITE_PASS] = SCSI_PROT_TRANSFER_PI |
795 SCSI_PROT_GUARD_CHECK |
796 SCSI_PROT_REF_CHECK |
797 SCSI_PROT_REF_INCREMENT |
798 SCSI_PROT_IP_CHECKSUM,
801 return flag_mask[prot_op];
804 static unsigned char sd_setup_protect_cmnd(struct scsi_cmnd *scmd,
805 unsigned int dix, unsigned int dif)
807 struct request *rq = scsi_cmd_to_rq(scmd);
808 struct bio *bio = rq->bio;
809 unsigned int prot_op = sd_prot_op(rq_data_dir(rq), dix, dif);
810 unsigned int protect = 0;
812 if (dix) { /* DIX Type 0, 1, 2, 3 */
813 if (bio_integrity_flagged(bio, BIP_IP_CHECKSUM))
814 scmd->prot_flags |= SCSI_PROT_IP_CHECKSUM;
816 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
817 scmd->prot_flags |= SCSI_PROT_GUARD_CHECK;
820 if (dif != T10_PI_TYPE3_PROTECTION) { /* DIX/DIF Type 0, 1, 2 */
821 scmd->prot_flags |= SCSI_PROT_REF_INCREMENT;
823 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
824 scmd->prot_flags |= SCSI_PROT_REF_CHECK;
827 if (dif) { /* DIX/DIF Type 1, 2, 3 */
828 scmd->prot_flags |= SCSI_PROT_TRANSFER_PI;
830 if (bio_integrity_flagged(bio, BIP_DISK_NOCHECK))
831 protect = 3 << 5; /* Disable target PI checking */
833 protect = 1 << 5; /* Enable target PI checking */
836 scsi_set_prot_op(scmd, prot_op);
837 scsi_set_prot_type(scmd, dif);
838 scmd->prot_flags &= sd_prot_flag_mask(prot_op);
843 static void sd_disable_discard(struct scsi_disk *sdkp)
845 sdkp->provisioning_mode = SD_LBP_DISABLE;
846 blk_queue_disable_discard(sdkp->disk->queue);
849 static void sd_config_discard(struct scsi_disk *sdkp, struct queue_limits *lim,
852 unsigned int logical_block_size = sdkp->device->sector_size;
853 unsigned int max_blocks = 0;
855 lim->discard_alignment = sdkp->unmap_alignment * logical_block_size;
856 lim->discard_granularity = max(sdkp->physical_block_size,
857 sdkp->unmap_granularity * logical_block_size);
858 sdkp->provisioning_mode = mode;
867 max_blocks = min_not_zero(sdkp->max_unmap_blocks,
868 (u32)SD_MAX_WS16_BLOCKS);
872 if (sdkp->device->unmap_limit_for_ws)
873 max_blocks = sdkp->max_unmap_blocks;
875 max_blocks = sdkp->max_ws_blocks;
877 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS16_BLOCKS);
881 if (sdkp->device->unmap_limit_for_ws)
882 max_blocks = sdkp->max_unmap_blocks;
884 max_blocks = sdkp->max_ws_blocks;
886 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS10_BLOCKS);
890 max_blocks = min_not_zero(sdkp->max_ws_blocks,
891 (u32)SD_MAX_WS10_BLOCKS);
895 lim->max_hw_discard_sectors = max_blocks *
896 (logical_block_size >> SECTOR_SHIFT);
899 static void *sd_set_special_bvec(struct request *rq, unsigned int data_len)
903 page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
906 clear_highpage(page);
907 bvec_set_page(&rq->special_vec, page, data_len, 0);
908 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
909 return bvec_virt(&rq->special_vec);
912 static blk_status_t sd_setup_unmap_cmnd(struct scsi_cmnd *cmd)
914 struct scsi_device *sdp = cmd->device;
915 struct request *rq = scsi_cmd_to_rq(cmd);
916 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
917 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
918 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
919 unsigned int data_len = 24;
922 buf = sd_set_special_bvec(rq, data_len);
924 return BLK_STS_RESOURCE;
927 cmd->cmnd[0] = UNMAP;
930 put_unaligned_be16(6 + 16, &buf[0]);
931 put_unaligned_be16(16, &buf[2]);
932 put_unaligned_be64(lba, &buf[8]);
933 put_unaligned_be32(nr_blocks, &buf[16]);
935 cmd->allowed = sdkp->max_retries;
936 cmd->transfersize = data_len;
937 rq->timeout = SD_TIMEOUT;
939 return scsi_alloc_sgtables(cmd);
942 static blk_status_t sd_setup_write_same16_cmnd(struct scsi_cmnd *cmd,
945 struct scsi_device *sdp = cmd->device;
946 struct request *rq = scsi_cmd_to_rq(cmd);
947 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
948 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
949 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
950 u32 data_len = sdp->sector_size;
952 if (!sd_set_special_bvec(rq, data_len))
953 return BLK_STS_RESOURCE;
956 cmd->cmnd[0] = WRITE_SAME_16;
958 cmd->cmnd[1] = 0x8; /* UNMAP */
959 put_unaligned_be64(lba, &cmd->cmnd[2]);
960 put_unaligned_be32(nr_blocks, &cmd->cmnd[10]);
962 cmd->allowed = sdkp->max_retries;
963 cmd->transfersize = data_len;
964 rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
966 return scsi_alloc_sgtables(cmd);
969 static blk_status_t sd_setup_write_same10_cmnd(struct scsi_cmnd *cmd,
972 struct scsi_device *sdp = cmd->device;
973 struct request *rq = scsi_cmd_to_rq(cmd);
974 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
975 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
976 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
977 u32 data_len = sdp->sector_size;
979 if (!sd_set_special_bvec(rq, data_len))
980 return BLK_STS_RESOURCE;
983 cmd->cmnd[0] = WRITE_SAME;
985 cmd->cmnd[1] = 0x8; /* UNMAP */
986 put_unaligned_be32(lba, &cmd->cmnd[2]);
987 put_unaligned_be16(nr_blocks, &cmd->cmnd[7]);
989 cmd->allowed = sdkp->max_retries;
990 cmd->transfersize = data_len;
991 rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
993 return scsi_alloc_sgtables(cmd);
996 static blk_status_t sd_setup_write_zeroes_cmnd(struct scsi_cmnd *cmd)
998 struct request *rq = scsi_cmd_to_rq(cmd);
999 struct scsi_device *sdp = cmd->device;
1000 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1001 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1002 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1004 if (!(rq->cmd_flags & REQ_NOUNMAP)) {
1005 switch (sdkp->zeroing_mode) {
1006 case SD_ZERO_WS16_UNMAP:
1007 return sd_setup_write_same16_cmnd(cmd, true);
1008 case SD_ZERO_WS10_UNMAP:
1009 return sd_setup_write_same10_cmnd(cmd, true);
1013 if (sdp->no_write_same) {
1014 rq->rq_flags |= RQF_QUIET;
1015 return BLK_STS_TARGET;
1018 if (sdkp->ws16 || lba > 0xffffffff || nr_blocks > 0xffff)
1019 return sd_setup_write_same16_cmnd(cmd, false);
1021 return sd_setup_write_same10_cmnd(cmd, false);
1024 static void sd_disable_write_same(struct scsi_disk *sdkp)
1026 sdkp->device->no_write_same = 1;
1027 sdkp->max_ws_blocks = 0;
1028 blk_queue_disable_write_zeroes(sdkp->disk->queue);
1031 static void sd_config_write_same(struct scsi_disk *sdkp,
1032 struct queue_limits *lim)
1034 unsigned int logical_block_size = sdkp->device->sector_size;
1036 if (sdkp->device->no_write_same) {
1037 sdkp->max_ws_blocks = 0;
1041 /* Some devices can not handle block counts above 0xffff despite
1042 * supporting WRITE SAME(16). Consequently we default to 64k
1043 * blocks per I/O unless the device explicitly advertises a
1046 if (sdkp->max_ws_blocks > SD_MAX_WS10_BLOCKS)
1047 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
1048 (u32)SD_MAX_WS16_BLOCKS);
1049 else if (sdkp->ws16 || sdkp->ws10 || sdkp->device->no_report_opcodes)
1050 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
1051 (u32)SD_MAX_WS10_BLOCKS);
1053 sdkp->device->no_write_same = 1;
1054 sdkp->max_ws_blocks = 0;
1057 if (sdkp->lbprz && sdkp->lbpws)
1058 sdkp->zeroing_mode = SD_ZERO_WS16_UNMAP;
1059 else if (sdkp->lbprz && sdkp->lbpws10)
1060 sdkp->zeroing_mode = SD_ZERO_WS10_UNMAP;
1061 else if (sdkp->max_ws_blocks)
1062 sdkp->zeroing_mode = SD_ZERO_WS;
1064 sdkp->zeroing_mode = SD_ZERO_WRITE;
1066 if (sdkp->max_ws_blocks &&
1067 sdkp->physical_block_size > logical_block_size) {
1069 * Reporting a maximum number of blocks that is not aligned
1070 * on the device physical size would cause a large write same
1071 * request to be split into physically unaligned chunks by
1072 * __blkdev_issue_write_zeroes() even if the caller of this
1073 * functions took care to align the large request. So make sure
1074 * the maximum reported is aligned to the device physical block
1075 * size. This is only an optional optimization for regular
1076 * disks, but this is mandatory to avoid failure of large write
1077 * same requests directed at sequential write required zones of
1078 * host-managed ZBC disks.
1080 sdkp->max_ws_blocks =
1081 round_down(sdkp->max_ws_blocks,
1082 bytes_to_logical(sdkp->device,
1083 sdkp->physical_block_size));
1087 lim->max_write_zeroes_sectors =
1088 sdkp->max_ws_blocks * (logical_block_size >> SECTOR_SHIFT);
1091 static blk_status_t sd_setup_flush_cmnd(struct scsi_cmnd *cmd)
1093 struct request *rq = scsi_cmd_to_rq(cmd);
1094 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1096 /* flush requests don't perform I/O, zero the S/G table */
1097 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1099 if (cmd->device->use_16_for_sync) {
1100 cmd->cmnd[0] = SYNCHRONIZE_CACHE_16;
1103 cmd->cmnd[0] = SYNCHRONIZE_CACHE;
1106 cmd->transfersize = 0;
1107 cmd->allowed = sdkp->max_retries;
1109 rq->timeout = rq->q->rq_timeout * SD_FLUSH_TIMEOUT_MULTIPLIER;
1114 * sd_group_number() - Compute the GROUP NUMBER field
1115 * @cmd: SCSI command for which to compute the value of the six-bit GROUP NUMBER
1118 * From SBC-5 r05 (https://www.t10.org/cgi-bin/ac.pl?t=f&f=sbc5r05.pdf):
1119 * 0: no relative lifetime.
1120 * 1: shortest relative lifetime.
1121 * 2: second shortest relative lifetime.
1122 * 3 - 0x3d: intermediate relative lifetimes.
1123 * 0x3e: second longest relative lifetime.
1124 * 0x3f: longest relative lifetime.
1126 static u8 sd_group_number(struct scsi_cmnd *cmd)
1128 const struct request *rq = scsi_cmd_to_rq(cmd);
1129 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1134 return min3((u32)rq->write_hint, (u32)sdkp->permanent_stream_count,
1138 static blk_status_t sd_setup_rw32_cmnd(struct scsi_cmnd *cmd, bool write,
1139 sector_t lba, unsigned int nr_blocks,
1140 unsigned char flags, unsigned int dld)
1142 cmd->cmd_len = SD_EXT_CDB_SIZE;
1143 cmd->cmnd[0] = VARIABLE_LENGTH_CMD;
1144 cmd->cmnd[6] = sd_group_number(cmd);
1145 cmd->cmnd[7] = 0x18; /* Additional CDB len */
1146 cmd->cmnd[9] = write ? WRITE_32 : READ_32;
1147 cmd->cmnd[10] = flags;
1148 cmd->cmnd[11] = dld & 0x07;
1149 put_unaligned_be64(lba, &cmd->cmnd[12]);
1150 put_unaligned_be32(lba, &cmd->cmnd[20]); /* Expected Indirect LBA */
1151 put_unaligned_be32(nr_blocks, &cmd->cmnd[28]);
1156 static blk_status_t sd_setup_rw16_cmnd(struct scsi_cmnd *cmd, bool write,
1157 sector_t lba, unsigned int nr_blocks,
1158 unsigned char flags, unsigned int dld)
1161 cmd->cmnd[0] = write ? WRITE_16 : READ_16;
1162 cmd->cmnd[1] = flags | ((dld >> 2) & 0x01);
1163 cmd->cmnd[14] = ((dld & 0x03) << 6) | sd_group_number(cmd);
1165 put_unaligned_be64(lba, &cmd->cmnd[2]);
1166 put_unaligned_be32(nr_blocks, &cmd->cmnd[10]);
1171 static blk_status_t sd_setup_rw10_cmnd(struct scsi_cmnd *cmd, bool write,
1172 sector_t lba, unsigned int nr_blocks,
1173 unsigned char flags)
1176 cmd->cmnd[0] = write ? WRITE_10 : READ_10;
1177 cmd->cmnd[1] = flags;
1178 cmd->cmnd[6] = sd_group_number(cmd);
1180 put_unaligned_be32(lba, &cmd->cmnd[2]);
1181 put_unaligned_be16(nr_blocks, &cmd->cmnd[7]);
1186 static blk_status_t sd_setup_rw6_cmnd(struct scsi_cmnd *cmd, bool write,
1187 sector_t lba, unsigned int nr_blocks,
1188 unsigned char flags)
1190 /* Avoid that 0 blocks gets translated into 256 blocks. */
1191 if (WARN_ON_ONCE(nr_blocks == 0))
1192 return BLK_STS_IOERR;
1194 if (unlikely(flags & 0x8)) {
1196 * This happens only if this drive failed 10byte rw
1197 * command with ILLEGAL_REQUEST during operation and
1198 * thus turned off use_10_for_rw.
1200 scmd_printk(KERN_ERR, cmd, "FUA write on READ/WRITE(6) drive\n");
1201 return BLK_STS_IOERR;
1205 cmd->cmnd[0] = write ? WRITE_6 : READ_6;
1206 cmd->cmnd[1] = (lba >> 16) & 0x1f;
1207 cmd->cmnd[2] = (lba >> 8) & 0xff;
1208 cmd->cmnd[3] = lba & 0xff;
1209 cmd->cmnd[4] = nr_blocks;
1216 * Check if a command has a duration limit set. If it does, and the target
1217 * device supports CDL and the feature is enabled, return the limit
1218 * descriptor index to use. Return 0 (no limit) otherwise.
1220 static int sd_cdl_dld(struct scsi_disk *sdkp, struct scsi_cmnd *scmd)
1222 struct scsi_device *sdp = sdkp->device;
1225 if (!sdp->cdl_supported || !sdp->cdl_enable)
1229 * Use "no limit" if the request ioprio does not specify a duration
1232 hint = IOPRIO_PRIO_HINT(req_get_ioprio(scsi_cmd_to_rq(scmd)));
1233 if (hint < IOPRIO_HINT_DEV_DURATION_LIMIT_1 ||
1234 hint > IOPRIO_HINT_DEV_DURATION_LIMIT_7)
1237 return (hint - IOPRIO_HINT_DEV_DURATION_LIMIT_1) + 1;
1240 static blk_status_t sd_setup_read_write_cmnd(struct scsi_cmnd *cmd)
1242 struct request *rq = scsi_cmd_to_rq(cmd);
1243 struct scsi_device *sdp = cmd->device;
1244 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1245 sector_t lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1247 unsigned int nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1248 unsigned int mask = logical_to_sectors(sdp, 1) - 1;
1249 bool write = rq_data_dir(rq) == WRITE;
1250 unsigned char protect, fua;
1256 ret = scsi_alloc_sgtables(cmd);
1257 if (ret != BLK_STS_OK)
1260 ret = BLK_STS_IOERR;
1261 if (!scsi_device_online(sdp) || sdp->changed) {
1262 scmd_printk(KERN_ERR, cmd, "device offline or changed\n");
1266 if (blk_rq_pos(rq) + blk_rq_sectors(rq) > get_capacity(rq->q->disk)) {
1267 scmd_printk(KERN_ERR, cmd, "access beyond end of device\n");
1271 if ((blk_rq_pos(rq) & mask) || (blk_rq_sectors(rq) & mask)) {
1272 scmd_printk(KERN_ERR, cmd, "request not aligned to the logical block size\n");
1277 * Some SD card readers can't handle accesses which touch the
1278 * last one or two logical blocks. Split accesses as needed.
1280 threshold = sdkp->capacity - SD_LAST_BUGGY_SECTORS;
1282 if (unlikely(sdp->last_sector_bug && lba + nr_blocks > threshold)) {
1283 if (lba < threshold) {
1284 /* Access up to the threshold but not beyond */
1285 nr_blocks = threshold - lba;
1287 /* Access only a single logical block */
1292 fua = rq->cmd_flags & REQ_FUA ? 0x8 : 0;
1293 dix = scsi_prot_sg_count(cmd);
1294 dif = scsi_host_dif_capable(cmd->device->host, sdkp->protection_type);
1295 dld = sd_cdl_dld(sdkp, cmd);
1298 protect = sd_setup_protect_cmnd(cmd, dix, dif);
1302 if (protect && sdkp->protection_type == T10_PI_TYPE2_PROTECTION) {
1303 ret = sd_setup_rw32_cmnd(cmd, write, lba, nr_blocks,
1304 protect | fua, dld);
1305 } else if (sdp->use_16_for_rw || (nr_blocks > 0xffff)) {
1306 ret = sd_setup_rw16_cmnd(cmd, write, lba, nr_blocks,
1307 protect | fua, dld);
1308 } else if ((nr_blocks > 0xff) || (lba > 0x1fffff) ||
1309 sdp->use_10_for_rw || protect || rq->write_hint) {
1310 ret = sd_setup_rw10_cmnd(cmd, write, lba, nr_blocks,
1313 ret = sd_setup_rw6_cmnd(cmd, write, lba, nr_blocks,
1317 if (unlikely(ret != BLK_STS_OK))
1321 * We shouldn't disconnect in the middle of a sector, so with a dumb
1322 * host adapter, it's safe to assume that we can at least transfer
1323 * this many bytes between each connect / disconnect.
1325 cmd->transfersize = sdp->sector_size;
1326 cmd->underflow = nr_blocks << 9;
1327 cmd->allowed = sdkp->max_retries;
1328 cmd->sdb.length = nr_blocks * sdp->sector_size;
1331 scmd_printk(KERN_INFO, cmd,
1332 "%s: block=%llu, count=%d\n", __func__,
1333 (unsigned long long)blk_rq_pos(rq),
1334 blk_rq_sectors(rq)));
1336 scmd_printk(KERN_INFO, cmd,
1337 "%s %d/%u 512 byte blocks.\n",
1338 write ? "writing" : "reading", nr_blocks,
1339 blk_rq_sectors(rq)));
1342 * This indicates that the command is ready from our end to be queued.
1346 scsi_free_sgtables(cmd);
1350 static blk_status_t sd_init_command(struct scsi_cmnd *cmd)
1352 struct request *rq = scsi_cmd_to_rq(cmd);
1354 switch (req_op(rq)) {
1355 case REQ_OP_DISCARD:
1356 switch (scsi_disk(rq->q->disk)->provisioning_mode) {
1358 return sd_setup_unmap_cmnd(cmd);
1360 return sd_setup_write_same16_cmnd(cmd, true);
1362 return sd_setup_write_same10_cmnd(cmd, true);
1364 return sd_setup_write_same10_cmnd(cmd, false);
1366 return BLK_STS_TARGET;
1368 case REQ_OP_WRITE_ZEROES:
1369 return sd_setup_write_zeroes_cmnd(cmd);
1371 return sd_setup_flush_cmnd(cmd);
1374 return sd_setup_read_write_cmnd(cmd);
1375 case REQ_OP_ZONE_RESET:
1376 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_RESET_WRITE_POINTER,
1378 case REQ_OP_ZONE_RESET_ALL:
1379 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_RESET_WRITE_POINTER,
1381 case REQ_OP_ZONE_OPEN:
1382 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_OPEN_ZONE, false);
1383 case REQ_OP_ZONE_CLOSE:
1384 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_CLOSE_ZONE, false);
1385 case REQ_OP_ZONE_FINISH:
1386 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_FINISH_ZONE, false);
1389 return BLK_STS_NOTSUPP;
1393 static void sd_uninit_command(struct scsi_cmnd *SCpnt)
1395 struct request *rq = scsi_cmd_to_rq(SCpnt);
1397 if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1398 mempool_free(rq->special_vec.bv_page, sd_page_pool);
1401 static bool sd_need_revalidate(struct gendisk *disk, struct scsi_disk *sdkp)
1403 if (sdkp->device->removable || sdkp->write_prot) {
1404 if (disk_check_media_change(disk))
1409 * Force a full rescan after ioctl(BLKRRPART). While the disk state has
1410 * nothing to do with partitions, BLKRRPART is used to force a full
1411 * revalidate after things like a format for historical reasons.
1413 return test_bit(GD_NEED_PART_SCAN, &disk->state);
1417 * sd_open - open a scsi disk device
1418 * @disk: disk to open
1421 * Returns 0 if successful. Returns a negated errno value in case
1424 * Note: This can be called from a user context (e.g. fsck(1) )
1425 * or from within the kernel (e.g. as a result of a mount(1) ).
1426 * In the latter case @inode and @filp carry an abridged amount
1427 * of information as noted above.
1429 * Locking: called with disk->open_mutex held.
1431 static int sd_open(struct gendisk *disk, blk_mode_t mode)
1433 struct scsi_disk *sdkp = scsi_disk(disk);
1434 struct scsi_device *sdev = sdkp->device;
1437 if (scsi_device_get(sdev))
1440 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
1443 * If the device is in error recovery, wait until it is done.
1444 * If the device is offline, then disallow any access to it.
1447 if (!scsi_block_when_processing_errors(sdev))
1450 if (sd_need_revalidate(disk, sdkp))
1451 sd_revalidate_disk(disk);
1454 * If the drive is empty, just let the open fail.
1456 retval = -ENOMEDIUM;
1457 if (sdev->removable && !sdkp->media_present &&
1458 !(mode & BLK_OPEN_NDELAY))
1462 * If the device has the write protect tab set, have the open fail
1463 * if the user expects to be able to write to the thing.
1466 if (sdkp->write_prot && (mode & BLK_OPEN_WRITE))
1470 * It is possible that the disk changing stuff resulted in
1471 * the device being taken offline. If this is the case,
1472 * report this to the user, and don't pretend that the
1473 * open actually succeeded.
1476 if (!scsi_device_online(sdev))
1479 if ((atomic_inc_return(&sdkp->openers) == 1) && sdev->removable) {
1480 if (scsi_block_when_processing_errors(sdev))
1481 scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
1487 scsi_device_put(sdev);
1492 * sd_release - invoked when the (last) close(2) is called on this
1494 * @disk: disk to release
1498 * Note: may block (uninterruptible) if error recovery is underway
1501 * Locking: called with disk->open_mutex held.
1503 static void sd_release(struct gendisk *disk)
1505 struct scsi_disk *sdkp = scsi_disk(disk);
1506 struct scsi_device *sdev = sdkp->device;
1508 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
1510 if (atomic_dec_return(&sdkp->openers) == 0 && sdev->removable) {
1511 if (scsi_block_when_processing_errors(sdev))
1512 scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
1515 scsi_device_put(sdev);
1518 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1520 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1521 struct scsi_device *sdp = sdkp->device;
1522 struct Scsi_Host *host = sdp->host;
1523 sector_t capacity = logical_to_sectors(sdp, sdkp->capacity);
1526 /* default to most commonly used values */
1527 diskinfo[0] = 0x40; /* 1 << 6 */
1528 diskinfo[1] = 0x20; /* 1 << 5 */
1529 diskinfo[2] = capacity >> 11;
1531 /* override with calculated, extended default, or driver values */
1532 if (host->hostt->bios_param)
1533 host->hostt->bios_param(sdp, bdev, capacity, diskinfo);
1535 scsicam_bios_param(bdev, capacity, diskinfo);
1537 geo->heads = diskinfo[0];
1538 geo->sectors = diskinfo[1];
1539 geo->cylinders = diskinfo[2];
1544 * sd_ioctl - process an ioctl
1545 * @bdev: target block device
1547 * @cmd: ioctl command number
1548 * @arg: this is third argument given to ioctl(2) system call.
1549 * Often contains a pointer.
1551 * Returns 0 if successful (some ioctls return positive numbers on
1552 * success as well). Returns a negated errno value in case of error.
1554 * Note: most ioctls are forward onto the block subsystem or further
1555 * down in the scsi subsystem.
1557 static int sd_ioctl(struct block_device *bdev, blk_mode_t mode,
1558 unsigned int cmd, unsigned long arg)
1560 struct gendisk *disk = bdev->bd_disk;
1561 struct scsi_disk *sdkp = scsi_disk(disk);
1562 struct scsi_device *sdp = sdkp->device;
1563 void __user *p = (void __user *)arg;
1566 SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, "
1567 "cmd=0x%x\n", disk->disk_name, cmd));
1569 if (bdev_is_partition(bdev) && !capable(CAP_SYS_RAWIO))
1570 return -ENOIOCTLCMD;
1573 * If we are in the middle of error recovery, don't let anyone
1574 * else try and use this device. Also, if error recovery fails, it
1575 * may try and take the device offline, in which case all further
1576 * access to the device is prohibited.
1578 error = scsi_ioctl_block_when_processing_errors(sdp, cmd,
1579 (mode & BLK_OPEN_NDELAY));
1583 if (is_sed_ioctl(cmd))
1584 return sed_ioctl(sdkp->opal_dev, cmd, p);
1585 return scsi_ioctl(sdp, mode & BLK_OPEN_WRITE, cmd, p);
1588 static void set_media_not_present(struct scsi_disk *sdkp)
1590 if (sdkp->media_present)
1591 sdkp->device->changed = 1;
1593 if (sdkp->device->removable) {
1594 sdkp->media_present = 0;
1599 static int media_not_present(struct scsi_disk *sdkp,
1600 struct scsi_sense_hdr *sshdr)
1602 if (!scsi_sense_valid(sshdr))
1605 /* not invoked for commands that could return deferred errors */
1606 switch (sshdr->sense_key) {
1607 case UNIT_ATTENTION:
1609 /* medium not present */
1610 if (sshdr->asc == 0x3A) {
1611 set_media_not_present(sdkp);
1619 * sd_check_events - check media events
1620 * @disk: kernel device descriptor
1621 * @clearing: disk events currently being cleared
1623 * Returns mask of DISK_EVENT_*.
1625 * Note: this function is invoked from the block subsystem.
1627 static unsigned int sd_check_events(struct gendisk *disk, unsigned int clearing)
1629 struct scsi_disk *sdkp = disk->private_data;
1630 struct scsi_device *sdp;
1638 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_check_events\n"));
1641 * If the device is offline, don't send any commands - just pretend as
1642 * if the command failed. If the device ever comes back online, we
1643 * can deal with it then. It is only because of unrecoverable errors
1644 * that we would ever take a device offline in the first place.
1646 if (!scsi_device_online(sdp)) {
1647 set_media_not_present(sdkp);
1652 * Using TEST_UNIT_READY enables differentiation between drive with
1653 * no cartridge loaded - NOT READY, drive with changed cartridge -
1654 * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
1656 * Drives that auto spin down. eg iomega jaz 1G, will be started
1657 * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
1658 * sd_revalidate() is called.
1660 if (scsi_block_when_processing_errors(sdp)) {
1661 struct scsi_sense_hdr sshdr = { 0, };
1663 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, sdkp->max_retries,
1666 /* failed to execute TUR, assume media not present */
1667 if (retval < 0 || host_byte(retval)) {
1668 set_media_not_present(sdkp);
1672 if (media_not_present(sdkp, &sshdr))
1677 * For removable scsi disk we have to recognise the presence
1678 * of a disk in the drive.
1680 if (!sdkp->media_present)
1682 sdkp->media_present = 1;
1685 * sdp->changed is set under the following conditions:
1687 * Medium present state has changed in either direction.
1688 * Device has indicated UNIT_ATTENTION.
1690 disk_changed = sdp->changed;
1692 return disk_changed ? DISK_EVENT_MEDIA_CHANGE : 0;
1695 static int sd_sync_cache(struct scsi_disk *sdkp)
1698 struct scsi_device *sdp = sdkp->device;
1699 const int timeout = sdp->request_queue->rq_timeout
1700 * SD_FLUSH_TIMEOUT_MULTIPLIER;
1701 /* Leave the rest of the command zero to indicate flush everything. */
1702 const unsigned char cmd[16] = { sdp->use_16_for_sync ?
1703 SYNCHRONIZE_CACHE_16 : SYNCHRONIZE_CACHE };
1704 struct scsi_sense_hdr sshdr;
1705 struct scsi_failure failure_defs[] = {
1708 .result = SCMD_FAILURE_RESULT_ANY,
1712 struct scsi_failures failures = {
1713 .failure_definitions = failure_defs,
1715 const struct scsi_exec_args exec_args = {
1716 .req_flags = BLK_MQ_REQ_PM,
1718 .failures = &failures,
1721 if (!scsi_device_online(sdp))
1724 res = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, NULL, 0, timeout,
1725 sdkp->max_retries, &exec_args);
1727 sd_print_result(sdkp, "Synchronize Cache(10) failed", res);
1732 if (scsi_status_is_check_condition(res) &&
1733 scsi_sense_valid(&sshdr)) {
1734 sd_print_sense_hdr(sdkp, &sshdr);
1736 /* we need to evaluate the error return */
1737 if (sshdr.asc == 0x3a || /* medium not present */
1738 sshdr.asc == 0x20 || /* invalid command */
1739 (sshdr.asc == 0x74 && sshdr.ascq == 0x71)) /* drive is password locked */
1740 /* this is no error here */
1743 * This drive doesn't support sync and there's not much
1744 * we can do because this is called during shutdown
1745 * or suspend so just return success so those operations
1748 if (sshdr.sense_key == ILLEGAL_REQUEST)
1752 switch (host_byte(res)) {
1753 /* ignore errors due to racing a disconnection */
1754 case DID_BAD_TARGET:
1755 case DID_NO_CONNECT:
1757 /* signal the upper layer it might try again */
1761 case DID_SOFT_ERROR:
1770 static void sd_rescan(struct device *dev)
1772 struct scsi_disk *sdkp = dev_get_drvdata(dev);
1774 sd_revalidate_disk(sdkp->disk);
1777 static int sd_get_unique_id(struct gendisk *disk, u8 id[16],
1778 enum blk_unique_id type)
1780 struct scsi_device *sdev = scsi_disk(disk)->device;
1781 const struct scsi_vpd *vpd;
1782 const unsigned char *d;
1783 int ret = -ENXIO, len;
1786 vpd = rcu_dereference(sdev->vpd_pg83);
1791 for (d = vpd->data + 4; d < vpd->data + vpd->len; d += d[3] + 4) {
1792 /* we only care about designators with LU association */
1793 if (((d[1] >> 4) & 0x3) != 0x00)
1795 if ((d[1] & 0xf) != type)
1799 * Only exit early if a 16-byte descriptor was found. Otherwise
1800 * keep looking as one with more entropy might still show up.
1803 if (len != 8 && len != 12 && len != 16)
1806 memcpy(id, d + 4, len);
1815 static int sd_scsi_to_pr_err(struct scsi_sense_hdr *sshdr, int result)
1817 switch (host_byte(result)) {
1818 case DID_TRANSPORT_MARGINAL:
1819 case DID_TRANSPORT_DISRUPTED:
1821 return PR_STS_RETRY_PATH_FAILURE;
1822 case DID_NO_CONNECT:
1823 return PR_STS_PATH_FAILED;
1824 case DID_TRANSPORT_FAILFAST:
1825 return PR_STS_PATH_FAST_FAILED;
1828 switch (status_byte(result)) {
1829 case SAM_STAT_RESERVATION_CONFLICT:
1830 return PR_STS_RESERVATION_CONFLICT;
1831 case SAM_STAT_CHECK_CONDITION:
1832 if (!scsi_sense_valid(sshdr))
1833 return PR_STS_IOERR;
1835 if (sshdr->sense_key == ILLEGAL_REQUEST &&
1836 (sshdr->asc == 0x26 || sshdr->asc == 0x24))
1841 return PR_STS_IOERR;
1845 static int sd_pr_in_command(struct block_device *bdev, u8 sa,
1846 unsigned char *data, int data_len)
1848 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1849 struct scsi_device *sdev = sdkp->device;
1850 struct scsi_sense_hdr sshdr;
1851 u8 cmd[10] = { PERSISTENT_RESERVE_IN, sa };
1852 struct scsi_failure failure_defs[] = {
1854 .sense = UNIT_ATTENTION,
1855 .asc = SCMD_FAILURE_ASC_ANY,
1856 .ascq = SCMD_FAILURE_ASCQ_ANY,
1858 .result = SAM_STAT_CHECK_CONDITION,
1862 struct scsi_failures failures = {
1863 .failure_definitions = failure_defs,
1865 const struct scsi_exec_args exec_args = {
1867 .failures = &failures,
1871 put_unaligned_be16(data_len, &cmd[7]);
1873 result = scsi_execute_cmd(sdev, cmd, REQ_OP_DRV_IN, data, data_len,
1874 SD_TIMEOUT, sdkp->max_retries, &exec_args);
1875 if (scsi_status_is_check_condition(result) &&
1876 scsi_sense_valid(&sshdr)) {
1877 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
1878 scsi_print_sense_hdr(sdev, NULL, &sshdr);
1884 return sd_scsi_to_pr_err(&sshdr, result);
1887 static int sd_pr_read_keys(struct block_device *bdev, struct pr_keys *keys_info)
1889 int result, i, data_offset, num_copy_keys;
1890 u32 num_keys = keys_info->num_keys;
1891 int data_len = num_keys * 8 + 8;
1894 data = kzalloc(data_len, GFP_KERNEL);
1898 result = sd_pr_in_command(bdev, READ_KEYS, data, data_len);
1902 keys_info->generation = get_unaligned_be32(&data[0]);
1903 keys_info->num_keys = get_unaligned_be32(&data[4]) / 8;
1906 num_copy_keys = min(num_keys, keys_info->num_keys);
1908 for (i = 0; i < num_copy_keys; i++) {
1909 keys_info->keys[i] = get_unaligned_be64(&data[data_offset]);
1918 static int sd_pr_read_reservation(struct block_device *bdev,
1919 struct pr_held_reservation *rsv)
1921 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1922 struct scsi_device *sdev = sdkp->device;
1926 result = sd_pr_in_command(bdev, READ_RESERVATION, data, sizeof(data));
1930 len = get_unaligned_be32(&data[4]);
1934 /* Make sure we have at least the key and type */
1936 sdev_printk(KERN_INFO, sdev,
1937 "READ RESERVATION failed due to short return buffer of %d bytes\n",
1942 rsv->generation = get_unaligned_be32(&data[0]);
1943 rsv->key = get_unaligned_be64(&data[8]);
1944 rsv->type = scsi_pr_type_to_block(data[21] & 0x0f);
1948 static int sd_pr_out_command(struct block_device *bdev, u8 sa, u64 key,
1949 u64 sa_key, enum scsi_pr_type type, u8 flags)
1951 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1952 struct scsi_device *sdev = sdkp->device;
1953 struct scsi_sense_hdr sshdr;
1954 struct scsi_failure failure_defs[] = {
1956 .sense = UNIT_ATTENTION,
1957 .asc = SCMD_FAILURE_ASC_ANY,
1958 .ascq = SCMD_FAILURE_ASCQ_ANY,
1960 .result = SAM_STAT_CHECK_CONDITION,
1964 struct scsi_failures failures = {
1965 .failure_definitions = failure_defs,
1967 const struct scsi_exec_args exec_args = {
1969 .failures = &failures,
1972 u8 cmd[16] = { 0, };
1973 u8 data[24] = { 0, };
1975 cmd[0] = PERSISTENT_RESERVE_OUT;
1978 put_unaligned_be32(sizeof(data), &cmd[5]);
1980 put_unaligned_be64(key, &data[0]);
1981 put_unaligned_be64(sa_key, &data[8]);
1984 result = scsi_execute_cmd(sdev, cmd, REQ_OP_DRV_OUT, &data,
1985 sizeof(data), SD_TIMEOUT, sdkp->max_retries,
1988 if (scsi_status_is_check_condition(result) &&
1989 scsi_sense_valid(&sshdr)) {
1990 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
1991 scsi_print_sense_hdr(sdev, NULL, &sshdr);
1997 return sd_scsi_to_pr_err(&sshdr, result);
2000 static int sd_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
2003 if (flags & ~PR_FL_IGNORE_KEY)
2005 return sd_pr_out_command(bdev, (flags & PR_FL_IGNORE_KEY) ? 0x06 : 0x00,
2006 old_key, new_key, 0,
2007 (1 << 0) /* APTPL */);
2010 static int sd_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
2015 return sd_pr_out_command(bdev, 0x01, key, 0,
2016 block_pr_type_to_scsi(type), 0);
2019 static int sd_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2021 return sd_pr_out_command(bdev, 0x02, key, 0,
2022 block_pr_type_to_scsi(type), 0);
2025 static int sd_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
2026 enum pr_type type, bool abort)
2028 return sd_pr_out_command(bdev, abort ? 0x05 : 0x04, old_key, new_key,
2029 block_pr_type_to_scsi(type), 0);
2032 static int sd_pr_clear(struct block_device *bdev, u64 key)
2034 return sd_pr_out_command(bdev, 0x03, key, 0, 0, 0);
2037 static const struct pr_ops sd_pr_ops = {
2038 .pr_register = sd_pr_register,
2039 .pr_reserve = sd_pr_reserve,
2040 .pr_release = sd_pr_release,
2041 .pr_preempt = sd_pr_preempt,
2042 .pr_clear = sd_pr_clear,
2043 .pr_read_keys = sd_pr_read_keys,
2044 .pr_read_reservation = sd_pr_read_reservation,
2047 static void scsi_disk_free_disk(struct gendisk *disk)
2049 struct scsi_disk *sdkp = scsi_disk(disk);
2051 put_device(&sdkp->disk_dev);
2054 static const struct block_device_operations sd_fops = {
2055 .owner = THIS_MODULE,
2057 .release = sd_release,
2059 .getgeo = sd_getgeo,
2060 .compat_ioctl = blkdev_compat_ptr_ioctl,
2061 .check_events = sd_check_events,
2062 .unlock_native_capacity = sd_unlock_native_capacity,
2063 .report_zones = sd_zbc_report_zones,
2064 .get_unique_id = sd_get_unique_id,
2065 .free_disk = scsi_disk_free_disk,
2066 .pr_ops = &sd_pr_ops,
2070 * sd_eh_reset - reset error handling callback
2071 * @scmd: sd-issued command that has failed
2073 * This function is called by the SCSI midlayer before starting
2074 * SCSI EH. When counting medium access failures we have to be
2075 * careful to register it only only once per device and SCSI EH run;
2076 * there might be several timed out commands which will cause the
2077 * 'max_medium_access_timeouts' counter to trigger after the first
2078 * SCSI EH run already and set the device to offline.
2079 * So this function resets the internal counter before starting SCSI EH.
2081 static void sd_eh_reset(struct scsi_cmnd *scmd)
2083 struct scsi_disk *sdkp = scsi_disk(scsi_cmd_to_rq(scmd)->q->disk);
2085 /* New SCSI EH run, reset gate variable */
2086 sdkp->ignore_medium_access_errors = false;
2090 * sd_eh_action - error handling callback
2091 * @scmd: sd-issued command that has failed
2092 * @eh_disp: The recovery disposition suggested by the midlayer
2094 * This function is called by the SCSI midlayer upon completion of an
2095 * error test command (currently TEST UNIT READY). The result of sending
2096 * the eh command is passed in eh_disp. We're looking for devices that
2097 * fail medium access commands but are OK with non access commands like
2098 * test unit ready (so wrongly see the device as having a successful
2101 static int sd_eh_action(struct scsi_cmnd *scmd, int eh_disp)
2103 struct scsi_disk *sdkp = scsi_disk(scsi_cmd_to_rq(scmd)->q->disk);
2104 struct scsi_device *sdev = scmd->device;
2106 if (!scsi_device_online(sdev) ||
2107 !scsi_medium_access_command(scmd) ||
2108 host_byte(scmd->result) != DID_TIME_OUT ||
2113 * The device has timed out executing a medium access command.
2114 * However, the TEST UNIT READY command sent during error
2115 * handling completed successfully. Either the device is in the
2116 * process of recovering or has it suffered an internal failure
2117 * that prevents access to the storage medium.
2119 if (!sdkp->ignore_medium_access_errors) {
2120 sdkp->medium_access_timed_out++;
2121 sdkp->ignore_medium_access_errors = true;
2125 * If the device keeps failing read/write commands but TEST UNIT
2126 * READY always completes successfully we assume that medium
2127 * access is no longer possible and take the device offline.
2129 if (sdkp->medium_access_timed_out >= sdkp->max_medium_access_timeouts) {
2130 scmd_printk(KERN_ERR, scmd,
2131 "Medium access timeout failure. Offlining disk!\n");
2132 mutex_lock(&sdev->state_mutex);
2133 scsi_device_set_state(sdev, SDEV_OFFLINE);
2134 mutex_unlock(&sdev->state_mutex);
2142 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
2144 struct request *req = scsi_cmd_to_rq(scmd);
2145 struct scsi_device *sdev = scmd->device;
2146 unsigned int transferred, good_bytes;
2147 u64 start_lba, end_lba, bad_lba;
2150 * Some commands have a payload smaller than the device logical
2151 * block size (e.g. INQUIRY on a 4K disk).
2153 if (scsi_bufflen(scmd) <= sdev->sector_size)
2156 /* Check if we have a 'bad_lba' information */
2157 if (!scsi_get_sense_info_fld(scmd->sense_buffer,
2158 SCSI_SENSE_BUFFERSIZE,
2163 * If the bad lba was reported incorrectly, we have no idea where
2166 start_lba = sectors_to_logical(sdev, blk_rq_pos(req));
2167 end_lba = start_lba + bytes_to_logical(sdev, scsi_bufflen(scmd));
2168 if (bad_lba < start_lba || bad_lba >= end_lba)
2172 * resid is optional but mostly filled in. When it's unused,
2173 * its value is zero, so we assume the whole buffer transferred
2175 transferred = scsi_bufflen(scmd) - scsi_get_resid(scmd);
2177 /* This computation should always be done in terms of the
2178 * resolution of the device's medium.
2180 good_bytes = logical_to_bytes(sdev, bad_lba - start_lba);
2182 return min(good_bytes, transferred);
2186 * sd_done - bottom half handler: called when the lower level
2187 * driver has completed (successfully or otherwise) a scsi command.
2188 * @SCpnt: mid-level's per command structure.
2190 * Note: potentially run from within an ISR. Must not block.
2192 static int sd_done(struct scsi_cmnd *SCpnt)
2194 int result = SCpnt->result;
2195 unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
2196 unsigned int sector_size = SCpnt->device->sector_size;
2198 struct scsi_sense_hdr sshdr;
2199 struct request *req = scsi_cmd_to_rq(SCpnt);
2200 struct scsi_disk *sdkp = scsi_disk(req->q->disk);
2201 int sense_valid = 0;
2202 int sense_deferred = 0;
2204 switch (req_op(req)) {
2205 case REQ_OP_DISCARD:
2206 case REQ_OP_WRITE_ZEROES:
2207 case REQ_OP_ZONE_RESET:
2208 case REQ_OP_ZONE_RESET_ALL:
2209 case REQ_OP_ZONE_OPEN:
2210 case REQ_OP_ZONE_CLOSE:
2211 case REQ_OP_ZONE_FINISH:
2213 good_bytes = blk_rq_bytes(req);
2214 scsi_set_resid(SCpnt, 0);
2217 scsi_set_resid(SCpnt, blk_rq_bytes(req));
2222 * In case of bogus fw or device, we could end up having
2223 * an unaligned partial completion. Check this here and force
2226 resid = scsi_get_resid(SCpnt);
2227 if (resid & (sector_size - 1)) {
2228 sd_printk(KERN_INFO, sdkp,
2229 "Unaligned partial completion (resid=%u, sector_sz=%u)\n",
2230 resid, sector_size);
2231 scsi_print_command(SCpnt);
2232 resid = min(scsi_bufflen(SCpnt),
2233 round_up(resid, sector_size));
2234 scsi_set_resid(SCpnt, resid);
2239 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
2241 sense_deferred = scsi_sense_is_deferred(&sshdr);
2243 sdkp->medium_access_timed_out = 0;
2245 if (!scsi_status_is_check_condition(result) &&
2246 (!sense_valid || sense_deferred))
2249 switch (sshdr.sense_key) {
2250 case HARDWARE_ERROR:
2252 good_bytes = sd_completed_bytes(SCpnt);
2254 case RECOVERED_ERROR:
2255 good_bytes = scsi_bufflen(SCpnt);
2258 /* This indicates a false check condition, so ignore it. An
2259 * unknown amount of data was transferred so treat it as an
2263 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
2265 case ABORTED_COMMAND:
2266 if (sshdr.asc == 0x10) /* DIF: Target detected corruption */
2267 good_bytes = sd_completed_bytes(SCpnt);
2269 case ILLEGAL_REQUEST:
2270 switch (sshdr.asc) {
2271 case 0x10: /* DIX: Host detected corruption */
2272 good_bytes = sd_completed_bytes(SCpnt);
2274 case 0x20: /* INVALID COMMAND OPCODE */
2275 case 0x24: /* INVALID FIELD IN CDB */
2276 switch (SCpnt->cmnd[0]) {
2278 sd_disable_discard(sdkp);
2282 if (SCpnt->cmnd[1] & 8) { /* UNMAP */
2283 sd_disable_discard(sdkp);
2285 sd_disable_write_same(sdkp);
2286 req->rq_flags |= RQF_QUIET;
2297 if (sdkp->device->type == TYPE_ZBC)
2298 good_bytes = sd_zbc_complete(SCpnt, good_bytes, &sshdr);
2300 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
2301 "sd_done: completed %d of %d bytes\n",
2302 good_bytes, scsi_bufflen(SCpnt)));
2308 * spinup disk - called only in sd_revalidate_disk()
2311 sd_spinup_disk(struct scsi_disk *sdkp)
2313 static const u8 cmd[10] = { TEST_UNIT_READY };
2314 unsigned long spintime_expire = 0;
2315 int spintime, sense_valid = 0;
2316 unsigned int the_result;
2317 struct scsi_sense_hdr sshdr;
2318 struct scsi_failure failure_defs[] = {
2319 /* Do not retry Medium Not Present */
2321 .sense = UNIT_ATTENTION,
2323 .ascq = SCMD_FAILURE_ASCQ_ANY,
2324 .result = SAM_STAT_CHECK_CONDITION,
2329 .ascq = SCMD_FAILURE_ASCQ_ANY,
2330 .result = SAM_STAT_CHECK_CONDITION,
2332 /* Retry when scsi_status_is_good would return false 3 times */
2334 .result = SCMD_FAILURE_STAT_ANY,
2339 struct scsi_failures failures = {
2340 .failure_definitions = failure_defs,
2342 const struct scsi_exec_args exec_args = {
2344 .failures = &failures,
2349 /* Spin up drives, as required. Only do this at boot time */
2350 /* Spinup needs to be done for module loads too. */
2352 bool media_was_present = sdkp->media_present;
2354 scsi_failures_reset_retries(&failures);
2356 the_result = scsi_execute_cmd(sdkp->device, cmd, REQ_OP_DRV_IN,
2357 NULL, 0, SD_TIMEOUT,
2358 sdkp->max_retries, &exec_args);
2361 if (the_result > 0) {
2363 * If the drive has indicated to us that it doesn't
2364 * have any media in it, don't bother with any more
2367 if (media_not_present(sdkp, &sshdr)) {
2368 if (media_was_present)
2369 sd_printk(KERN_NOTICE, sdkp,
2370 "Media removed, stopped polling\n");
2373 sense_valid = scsi_sense_valid(&sshdr);
2376 if (!scsi_status_is_check_condition(the_result)) {
2377 /* no sense, TUR either succeeded or failed
2378 * with a status error */
2379 if(!spintime && !scsi_status_is_good(the_result)) {
2380 sd_print_result(sdkp, "Test Unit Ready failed",
2387 * The device does not want the automatic start to be issued.
2389 if (sdkp->device->no_start_on_add)
2392 if (sense_valid && sshdr.sense_key == NOT_READY) {
2393 if (sshdr.asc == 4 && sshdr.ascq == 3)
2394 break; /* manual intervention required */
2395 if (sshdr.asc == 4 && sshdr.ascq == 0xb)
2396 break; /* standby */
2397 if (sshdr.asc == 4 && sshdr.ascq == 0xc)
2398 break; /* unavailable */
2399 if (sshdr.asc == 4 && sshdr.ascq == 0x1b)
2400 break; /* sanitize in progress */
2401 if (sshdr.asc == 4 && sshdr.ascq == 0x24)
2402 break; /* depopulation in progress */
2403 if (sshdr.asc == 4 && sshdr.ascq == 0x25)
2404 break; /* depopulation restoration in progress */
2406 * Issue command to spin up drive when not ready
2409 /* Return immediately and start spin cycle */
2410 const u8 start_cmd[10] = {
2413 [4] = sdkp->device->start_stop_pwr_cond ?
2417 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
2418 scsi_execute_cmd(sdkp->device, start_cmd,
2419 REQ_OP_DRV_IN, NULL, 0,
2420 SD_TIMEOUT, sdkp->max_retries,
2422 spintime_expire = jiffies + 100 * HZ;
2425 /* Wait 1 second for next try */
2427 printk(KERN_CONT ".");
2430 * Wait for USB flash devices with slow firmware.
2431 * Yes, this sense key/ASC combination shouldn't
2432 * occur here. It's characteristic of these devices.
2434 } else if (sense_valid &&
2435 sshdr.sense_key == UNIT_ATTENTION &&
2436 sshdr.asc == 0x28) {
2438 spintime_expire = jiffies + 5 * HZ;
2441 /* Wait 1 second for next try */
2444 /* we don't understand the sense code, so it's
2445 * probably pointless to loop */
2447 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
2448 sd_print_sense_hdr(sdkp, &sshdr);
2453 } while (spintime && time_before_eq(jiffies, spintime_expire));
2456 if (scsi_status_is_good(the_result))
2457 printk(KERN_CONT "ready\n");
2459 printk(KERN_CONT "not responding...\n");
2464 * Determine whether disk supports Data Integrity Field.
2466 static int sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
2468 struct scsi_device *sdp = sdkp->device;
2471 if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0) {
2472 sdkp->protection_type = 0;
2476 type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
2478 if (type > T10_PI_TYPE3_PROTECTION) {
2479 sd_printk(KERN_ERR, sdkp, "formatted with unsupported" \
2480 " protection type %u. Disabling disk!\n",
2482 sdkp->protection_type = 0;
2486 sdkp->protection_type = type;
2491 static void sd_config_protection(struct scsi_disk *sdkp,
2492 struct queue_limits *lim)
2494 struct scsi_device *sdp = sdkp->device;
2496 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY))
2497 sd_dif_config_host(sdkp, lim);
2499 if (!sdkp->protection_type)
2502 if (!scsi_host_dif_capable(sdp->host, sdkp->protection_type)) {
2503 sd_first_printk(KERN_NOTICE, sdkp,
2504 "Disabling DIF Type %u protection\n",
2505 sdkp->protection_type);
2506 sdkp->protection_type = 0;
2509 sd_first_printk(KERN_NOTICE, sdkp, "Enabling DIF Type %u protection\n",
2510 sdkp->protection_type);
2513 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
2514 struct scsi_sense_hdr *sshdr, int sense_valid,
2518 sd_print_sense_hdr(sdkp, sshdr);
2520 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
2523 * Set dirty bit for removable devices if not ready -
2524 * sometimes drives will not report this properly.
2526 if (sdp->removable &&
2527 sense_valid && sshdr->sense_key == NOT_READY)
2528 set_media_not_present(sdkp);
2531 * We used to set media_present to 0 here to indicate no media
2532 * in the drive, but some drives fail read capacity even with
2533 * media present, so we can't do that.
2535 sdkp->capacity = 0; /* unknown mapped to zero - as usual */
2539 #if RC16_LEN > SD_BUF_SIZE
2540 #error RC16_LEN must not be more than SD_BUF_SIZE
2543 #define READ_CAPACITY_RETRIES_ON_RESET 10
2545 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
2546 struct queue_limits *lim, unsigned char *buffer)
2548 unsigned char cmd[16];
2549 struct scsi_sense_hdr sshdr;
2550 const struct scsi_exec_args exec_args = {
2553 int sense_valid = 0;
2555 int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2556 unsigned int alignment;
2557 unsigned long long lba;
2558 unsigned sector_size;
2560 if (sdp->no_read_capacity_16)
2565 cmd[0] = SERVICE_ACTION_IN_16;
2566 cmd[1] = SAI_READ_CAPACITY_16;
2568 memset(buffer, 0, RC16_LEN);
2570 the_result = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN,
2571 buffer, RC16_LEN, SD_TIMEOUT,
2572 sdkp->max_retries, &exec_args);
2573 if (the_result > 0) {
2574 if (media_not_present(sdkp, &sshdr))
2577 sense_valid = scsi_sense_valid(&sshdr);
2579 sshdr.sense_key == ILLEGAL_REQUEST &&
2580 (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
2582 /* Invalid Command Operation Code or
2583 * Invalid Field in CDB, just retry
2584 * silently with RC10 */
2587 sshdr.sense_key == UNIT_ATTENTION &&
2588 sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2589 /* Device reset might occur several times,
2590 * give it one more chance */
2591 if (--reset_retries > 0)
2596 } while (the_result && retries);
2599 sd_print_result(sdkp, "Read Capacity(16) failed", the_result);
2600 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2604 sector_size = get_unaligned_be32(&buffer[8]);
2605 lba = get_unaligned_be64(&buffer[0]);
2607 if (sd_read_protection_type(sdkp, buffer) < 0) {
2612 /* Logical blocks per physical block exponent */
2613 sdkp->physical_block_size = (1 << (buffer[13] & 0xf)) * sector_size;
2616 sdkp->rc_basis = (buffer[12] >> 4) & 0x3;
2618 /* Lowest aligned logical block */
2619 alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
2620 lim->alignment_offset = alignment;
2621 if (alignment && sdkp->first_scan)
2622 sd_printk(KERN_NOTICE, sdkp,
2623 "physical block alignment offset: %u\n", alignment);
2625 if (buffer[14] & 0x80) { /* LBPME */
2628 if (buffer[14] & 0x40) /* LBPRZ */
2631 sd_config_discard(sdkp, lim, SD_LBP_WS16);
2634 sdkp->capacity = lba + 1;
2638 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
2639 unsigned char *buffer)
2641 static const u8 cmd[10] = { READ_CAPACITY };
2642 struct scsi_sense_hdr sshdr;
2643 struct scsi_failure failure_defs[] = {
2644 /* Do not retry Medium Not Present */
2646 .sense = UNIT_ATTENTION,
2648 .result = SAM_STAT_CHECK_CONDITION,
2653 .result = SAM_STAT_CHECK_CONDITION,
2655 /* Device reset might occur several times so retry a lot */
2657 .sense = UNIT_ATTENTION,
2659 .allowed = READ_CAPACITY_RETRIES_ON_RESET,
2660 .result = SAM_STAT_CHECK_CONDITION,
2662 /* Any other error not listed above retry 3 times */
2664 .result = SCMD_FAILURE_RESULT_ANY,
2669 struct scsi_failures failures = {
2670 .failure_definitions = failure_defs,
2672 const struct scsi_exec_args exec_args = {
2674 .failures = &failures,
2676 int sense_valid = 0;
2679 unsigned sector_size;
2681 memset(buffer, 0, 8);
2683 the_result = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, buffer,
2684 8, SD_TIMEOUT, sdkp->max_retries,
2687 if (the_result > 0) {
2688 sense_valid = scsi_sense_valid(&sshdr);
2690 if (media_not_present(sdkp, &sshdr))
2695 sd_print_result(sdkp, "Read Capacity(10) failed", the_result);
2696 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2700 sector_size = get_unaligned_be32(&buffer[4]);
2701 lba = get_unaligned_be32(&buffer[0]);
2703 if (sdp->no_read_capacity_16 && (lba == 0xffffffff)) {
2704 /* Some buggy (usb cardreader) devices return an lba of
2705 0xffffffff when the want to report a size of 0 (with
2706 which they really mean no media is present) */
2708 sdkp->physical_block_size = sector_size;
2712 sdkp->capacity = lba + 1;
2713 sdkp->physical_block_size = sector_size;
2717 static int sd_try_rc16_first(struct scsi_device *sdp)
2719 if (sdp->host->max_cmd_len < 16)
2721 if (sdp->try_rc_10_first)
2723 if (sdp->scsi_level > SCSI_SPC_2)
2725 if (scsi_device_protection(sdp))
2731 * read disk capacity
2734 sd_read_capacity(struct scsi_disk *sdkp, struct queue_limits *lim,
2735 unsigned char *buffer)
2738 struct scsi_device *sdp = sdkp->device;
2740 if (sd_try_rc16_first(sdp)) {
2741 sector_size = read_capacity_16(sdkp, sdp, lim, buffer);
2742 if (sector_size == -EOVERFLOW)
2744 if (sector_size == -ENODEV)
2746 if (sector_size < 0)
2747 sector_size = read_capacity_10(sdkp, sdp, buffer);
2748 if (sector_size < 0)
2751 sector_size = read_capacity_10(sdkp, sdp, buffer);
2752 if (sector_size == -EOVERFLOW)
2754 if (sector_size < 0)
2756 if ((sizeof(sdkp->capacity) > 4) &&
2757 (sdkp->capacity > 0xffffffffULL)) {
2758 int old_sector_size = sector_size;
2759 sd_printk(KERN_NOTICE, sdkp, "Very big device. "
2760 "Trying to use READ CAPACITY(16).\n");
2761 sector_size = read_capacity_16(sdkp, sdp, lim, buffer);
2762 if (sector_size < 0) {
2763 sd_printk(KERN_NOTICE, sdkp,
2764 "Using 0xffffffff as device size\n");
2765 sdkp->capacity = 1 + (sector_t) 0xffffffff;
2766 sector_size = old_sector_size;
2769 /* Remember that READ CAPACITY(16) succeeded */
2770 sdp->try_rc_10_first = 0;
2774 /* Some devices are known to return the total number of blocks,
2775 * not the highest block number. Some devices have versions
2776 * which do this and others which do not. Some devices we might
2777 * suspect of doing this but we don't know for certain.
2779 * If we know the reported capacity is wrong, decrement it. If
2780 * we can only guess, then assume the number of blocks is even
2781 * (usually true but not always) and err on the side of lowering
2784 if (sdp->fix_capacity ||
2785 (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
2786 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
2787 "from its reported value: %llu\n",
2788 (unsigned long long) sdkp->capacity);
2793 if (sector_size == 0) {
2795 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
2799 if (sector_size != 512 &&
2800 sector_size != 1024 &&
2801 sector_size != 2048 &&
2802 sector_size != 4096) {
2803 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
2806 * The user might want to re-format the drive with
2807 * a supported sectorsize. Once this happens, it
2808 * would be relatively trivial to set the thing up.
2809 * For this reason, we leave the thing in the table.
2813 * set a bogus sector size so the normal read/write
2814 * logic in the block layer will eventually refuse any
2815 * request on this device without tripping over power
2816 * of two sector size assumptions
2820 lim->logical_block_size = sector_size;
2821 lim->physical_block_size = sdkp->physical_block_size;
2822 sdkp->device->sector_size = sector_size;
2824 if (sdkp->capacity > 0xffffffff)
2825 sdp->use_16_for_rw = 1;
2830 * Print disk capacity
2833 sd_print_capacity(struct scsi_disk *sdkp,
2834 sector_t old_capacity)
2836 int sector_size = sdkp->device->sector_size;
2837 char cap_str_2[10], cap_str_10[10];
2839 if (!sdkp->first_scan && old_capacity == sdkp->capacity)
2842 string_get_size(sdkp->capacity, sector_size,
2843 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
2844 string_get_size(sdkp->capacity, sector_size,
2845 STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
2847 sd_printk(KERN_NOTICE, sdkp,
2848 "%llu %d-byte logical blocks: (%s/%s)\n",
2849 (unsigned long long)sdkp->capacity,
2850 sector_size, cap_str_10, cap_str_2);
2852 if (sdkp->physical_block_size != sector_size)
2853 sd_printk(KERN_NOTICE, sdkp,
2854 "%u-byte physical blocks\n",
2855 sdkp->physical_block_size);
2858 /* called with buffer of length 512 */
2860 sd_do_mode_sense(struct scsi_disk *sdkp, int dbd, int modepage,
2861 unsigned char *buffer, int len, struct scsi_mode_data *data,
2862 struct scsi_sense_hdr *sshdr)
2865 * If we must use MODE SENSE(10), make sure that the buffer length
2866 * is at least 8 bytes so that the mode sense header fits.
2868 if (sdkp->device->use_10_for_ms && len < 8)
2871 return scsi_mode_sense(sdkp->device, dbd, modepage, 0, buffer, len,
2872 SD_TIMEOUT, sdkp->max_retries, data, sshdr);
2876 * read write protect setting, if possible - called only in sd_revalidate_disk()
2877 * called with buffer of length SD_BUF_SIZE
2880 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
2883 struct scsi_device *sdp = sdkp->device;
2884 struct scsi_mode_data data;
2885 int old_wp = sdkp->write_prot;
2887 set_disk_ro(sdkp->disk, 0);
2888 if (sdp->skip_ms_page_3f) {
2889 sd_first_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
2893 if (sdp->use_192_bytes_for_3f) {
2894 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 192, &data, NULL);
2897 * First attempt: ask for all pages (0x3F), but only 4 bytes.
2898 * We have to start carefully: some devices hang if we ask
2899 * for more than is available.
2901 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 4, &data, NULL);
2904 * Second attempt: ask for page 0 When only page 0 is
2905 * implemented, a request for page 3F may return Sense Key
2906 * 5: Illegal Request, Sense Code 24: Invalid field in
2910 res = sd_do_mode_sense(sdkp, 0, 0, buffer, 4, &data, NULL);
2913 * Third attempt: ask 255 bytes, as we did earlier.
2916 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 255,
2921 sd_first_printk(KERN_WARNING, sdkp,
2922 "Test WP failed, assume Write Enabled\n");
2924 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
2925 set_disk_ro(sdkp->disk, sdkp->write_prot);
2926 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
2927 sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
2928 sdkp->write_prot ? "on" : "off");
2929 sd_printk(KERN_DEBUG, sdkp, "Mode Sense: %4ph\n", buffer);
2935 * sd_read_cache_type - called only from sd_revalidate_disk()
2936 * called with buffer of length SD_BUF_SIZE
2939 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
2942 struct scsi_device *sdp = sdkp->device;
2947 struct scsi_mode_data data;
2948 struct scsi_sense_hdr sshdr;
2949 int old_wce = sdkp->WCE;
2950 int old_rcd = sdkp->RCD;
2951 int old_dpofua = sdkp->DPOFUA;
2954 if (sdkp->cache_override)
2958 if (sdp->skip_ms_page_8) {
2959 if (sdp->type == TYPE_RBC)
2962 if (sdp->skip_ms_page_3f)
2965 if (sdp->use_192_bytes_for_3f)
2969 } else if (sdp->type == TYPE_RBC) {
2977 /* cautiously ask */
2978 res = sd_do_mode_sense(sdkp, dbd, modepage, buffer, first_len,
2984 if (!data.header_length) {
2987 sd_first_printk(KERN_ERR, sdkp,
2988 "Missing header in MODE_SENSE response\n");
2991 /* that went OK, now ask for the proper length */
2995 * We're only interested in the first three bytes, actually.
2996 * But the data cache page is defined for the first 20.
3000 else if (len > SD_BUF_SIZE) {
3001 sd_first_printk(KERN_NOTICE, sdkp, "Truncating mode parameter "
3002 "data from %d to %d bytes\n", len, SD_BUF_SIZE);
3005 if (modepage == 0x3F && sdp->use_192_bytes_for_3f)
3009 if (len > first_len)
3010 res = sd_do_mode_sense(sdkp, dbd, modepage, buffer, len,
3014 int offset = data.header_length + data.block_descriptor_length;
3016 while (offset < len) {
3017 u8 page_code = buffer[offset] & 0x3F;
3018 u8 spf = buffer[offset] & 0x40;
3020 if (page_code == 8 || page_code == 6) {
3021 /* We're interested only in the first 3 bytes.
3023 if (len - offset <= 2) {
3024 sd_first_printk(KERN_ERR, sdkp,
3025 "Incomplete mode parameter "
3029 modepage = page_code;
3033 /* Go to the next page */
3034 if (spf && len - offset > 3)
3035 offset += 4 + (buffer[offset+2] << 8) +
3037 else if (!spf && len - offset > 1)
3038 offset += 2 + buffer[offset+1];
3040 sd_first_printk(KERN_ERR, sdkp,
3042 "parameter data\n");
3048 sd_first_printk(KERN_WARNING, sdkp,
3049 "No Caching mode page found\n");
3053 if (modepage == 8) {
3054 sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
3055 sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
3057 sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
3061 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
3062 if (sdp->broken_fua) {
3063 sd_first_printk(KERN_NOTICE, sdkp, "Disabling FUA\n");
3065 } else if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw &&
3066 !sdkp->device->use_16_for_rw) {
3067 sd_first_printk(KERN_NOTICE, sdkp,
3068 "Uses READ/WRITE(6), disabling FUA\n");
3072 /* No cache flush allowed for write protected devices */
3073 if (sdkp->WCE && sdkp->write_prot)
3076 if (sdkp->first_scan || old_wce != sdkp->WCE ||
3077 old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
3078 sd_printk(KERN_NOTICE, sdkp,
3079 "Write cache: %s, read cache: %s, %s\n",
3080 sdkp->WCE ? "enabled" : "disabled",
3081 sdkp->RCD ? "disabled" : "enabled",
3082 sdkp->DPOFUA ? "supports DPO and FUA"
3083 : "doesn't support DPO or FUA");
3089 if (res == -EIO && scsi_sense_valid(&sshdr) &&
3090 sshdr.sense_key == ILLEGAL_REQUEST &&
3091 sshdr.asc == 0x24 && sshdr.ascq == 0x0)
3092 /* Invalid field in CDB */
3093 sd_first_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
3095 sd_first_printk(KERN_ERR, sdkp,
3096 "Asking for cache data failed\n");
3099 if (sdp->wce_default_on) {
3100 sd_first_printk(KERN_NOTICE, sdkp,
3101 "Assuming drive cache: write back\n");
3104 sd_first_printk(KERN_WARNING, sdkp,
3105 "Assuming drive cache: write through\n");
3112 static bool sd_is_perm_stream(struct scsi_disk *sdkp, unsigned int stream_id)
3114 u8 cdb[16] = { SERVICE_ACTION_IN_16, SAI_GET_STREAM_STATUS };
3116 struct scsi_stream_status_header h;
3117 struct scsi_stream_status s;
3119 struct scsi_device *sdev = sdkp->device;
3120 struct scsi_sense_hdr sshdr;
3121 const struct scsi_exec_args exec_args = {
3126 put_unaligned_be16(stream_id, &cdb[4]);
3127 put_unaligned_be32(sizeof(buf), &cdb[10]);
3129 res = scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, &buf, sizeof(buf),
3130 SD_TIMEOUT, sdkp->max_retries, &exec_args);
3133 if (scsi_status_is_check_condition(res) && scsi_sense_valid(&sshdr))
3134 sd_print_sense_hdr(sdkp, &sshdr);
3137 if (get_unaligned_be32(&buf.h.len) < sizeof(struct scsi_stream_status))
3139 return buf.h.stream_status[0].perm;
3142 static void sd_read_io_hints(struct scsi_disk *sdkp, unsigned char *buffer)
3144 struct scsi_device *sdp = sdkp->device;
3145 const struct scsi_io_group_descriptor *desc, *start, *end;
3146 u16 permanent_stream_count_old;
3147 struct scsi_sense_hdr sshdr;
3148 struct scsi_mode_data data;
3151 res = scsi_mode_sense(sdp, /*dbd=*/0x8, /*modepage=*/0x0a,
3152 /*subpage=*/0x05, buffer, SD_BUF_SIZE, SD_TIMEOUT,
3153 sdkp->max_retries, &data, &sshdr);
3156 start = (void *)buffer + data.header_length + 16;
3157 end = (void *)buffer + ALIGN_DOWN(data.header_length + data.length,
3160 * From "SBC-5 Constrained Streams with Data Lifetimes": Device severs
3161 * should assign the lowest numbered stream identifiers to permanent
3164 for (desc = start; desc < end; desc++)
3165 if (!desc->st_enble || !sd_is_perm_stream(sdkp, desc - start))
3167 permanent_stream_count_old = sdkp->permanent_stream_count;
3168 sdkp->permanent_stream_count = desc - start;
3169 if (sdkp->rscs && sdkp->permanent_stream_count < 2)
3170 sd_printk(KERN_INFO, sdkp,
3171 "Unexpected: RSCS has been set and the permanent stream count is %u\n",
3172 sdkp->permanent_stream_count);
3173 else if (sdkp->permanent_stream_count != permanent_stream_count_old)
3174 sd_printk(KERN_INFO, sdkp, "permanent stream count = %d\n",
3175 sdkp->permanent_stream_count);
3179 * The ATO bit indicates whether the DIF application tag is available
3180 * for use by the operating system.
3182 static void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
3185 struct scsi_device *sdp = sdkp->device;
3186 struct scsi_mode_data data;
3187 struct scsi_sense_hdr sshdr;
3189 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
3192 if (sdkp->protection_type == 0)
3195 res = scsi_mode_sense(sdp, 1, 0x0a, 0, buffer, 36, SD_TIMEOUT,
3196 sdkp->max_retries, &data, &sshdr);
3198 if (res < 0 || !data.header_length ||
3200 sd_first_printk(KERN_WARNING, sdkp,
3201 "getting Control mode page failed, assume no ATO\n");
3203 if (res == -EIO && scsi_sense_valid(&sshdr))
3204 sd_print_sense_hdr(sdkp, &sshdr);
3209 offset = data.header_length + data.block_descriptor_length;
3211 if ((buffer[offset] & 0x3f) != 0x0a) {
3212 sd_first_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
3216 if ((buffer[offset + 5] & 0x80) == 0)
3224 static unsigned int sd_discard_mode(struct scsi_disk *sdkp)
3226 if (!sdkp->lbpvpd) {
3227 /* LBP VPD page not provided */
3228 if (sdkp->max_unmap_blocks)
3229 return SD_LBP_UNMAP;
3233 /* LBP VPD page tells us what to use */
3234 if (sdkp->lbpu && sdkp->max_unmap_blocks)
3235 return SD_LBP_UNMAP;
3240 return SD_LBP_DISABLE;
3244 * Query disk device for preferred I/O sizes.
3246 static void sd_read_block_limits(struct scsi_disk *sdkp,
3247 struct queue_limits *lim)
3249 struct scsi_vpd *vpd;
3253 vpd = rcu_dereference(sdkp->device->vpd_pgb0);
3254 if (!vpd || vpd->len < 16)
3257 sdkp->min_xfer_blocks = get_unaligned_be16(&vpd->data[6]);
3258 sdkp->max_xfer_blocks = get_unaligned_be32(&vpd->data[8]);
3259 sdkp->opt_xfer_blocks = get_unaligned_be32(&vpd->data[12]);
3261 if (vpd->len >= 64) {
3262 unsigned int lba_count, desc_count;
3264 sdkp->max_ws_blocks = (u32)get_unaligned_be64(&vpd->data[36]);
3269 lba_count = get_unaligned_be32(&vpd->data[20]);
3270 desc_count = get_unaligned_be32(&vpd->data[24]);
3272 if (lba_count && desc_count)
3273 sdkp->max_unmap_blocks = lba_count;
3275 sdkp->unmap_granularity = get_unaligned_be32(&vpd->data[28]);
3277 if (vpd->data[32] & 0x80)
3278 sdkp->unmap_alignment =
3279 get_unaligned_be32(&vpd->data[32]) & ~(1 << 31);
3281 sd_config_discard(sdkp, lim, sd_discard_mode(sdkp));
3288 /* Parse the Block Limits Extension VPD page (0xb7) */
3289 static void sd_read_block_limits_ext(struct scsi_disk *sdkp)
3291 struct scsi_vpd *vpd;
3294 vpd = rcu_dereference(sdkp->device->vpd_pgb7);
3295 if (vpd && vpd->len >= 2)
3296 sdkp->rscs = vpd->data[5] & 1;
3300 /* Query block device characteristics */
3301 static void sd_read_block_characteristics(struct scsi_disk *sdkp,
3302 struct queue_limits *lim)
3304 struct scsi_vpd *vpd;
3308 vpd = rcu_dereference(sdkp->device->vpd_pgb1);
3310 if (!vpd || vpd->len < 8) {
3315 rot = get_unaligned_be16(&vpd->data[4]);
3316 sdkp->zoned = (vpd->data[8] >> 4) & 3;
3320 lim->features &= ~(BLK_FEAT_ROTATIONAL | BLK_FEAT_ADD_RANDOM);
3322 if (!sdkp->first_scan)
3325 if (sdkp->device->type == TYPE_ZBC)
3326 sd_printk(KERN_NOTICE, sdkp, "Host-managed zoned block device\n");
3327 else if (sdkp->zoned == 1)
3328 sd_printk(KERN_NOTICE, sdkp, "Host-aware SMR disk used as regular disk\n");
3329 else if (sdkp->zoned == 2)
3330 sd_printk(KERN_NOTICE, sdkp, "Drive-managed SMR disk\n");
3334 * sd_read_block_provisioning - Query provisioning VPD page
3335 * @sdkp: disk to query
3337 static void sd_read_block_provisioning(struct scsi_disk *sdkp)
3339 struct scsi_vpd *vpd;
3341 if (sdkp->lbpme == 0)
3345 vpd = rcu_dereference(sdkp->device->vpd_pgb2);
3347 if (!vpd || vpd->len < 8) {
3353 sdkp->lbpu = (vpd->data[5] >> 7) & 1; /* UNMAP */
3354 sdkp->lbpws = (vpd->data[5] >> 6) & 1; /* WRITE SAME(16) w/ UNMAP */
3355 sdkp->lbpws10 = (vpd->data[5] >> 5) & 1; /* WRITE SAME(10) w/ UNMAP */
3359 static void sd_read_write_same(struct scsi_disk *sdkp, unsigned char *buffer)
3361 struct scsi_device *sdev = sdkp->device;
3363 if (sdev->host->no_write_same) {
3364 sdev->no_write_same = 1;
3369 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, INQUIRY, 0) < 0) {
3370 struct scsi_vpd *vpd;
3372 sdev->no_report_opcodes = 1;
3374 /* Disable WRITE SAME if REPORT SUPPORTED OPERATION
3375 * CODES is unsupported and the device has an ATA
3376 * Information VPD page (SAT).
3379 vpd = rcu_dereference(sdev->vpd_pg89);
3381 sdev->no_write_same = 1;
3385 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME_16, 0) == 1)
3388 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME, 0) == 1)
3392 static void sd_read_security(struct scsi_disk *sdkp, unsigned char *buffer)
3394 struct scsi_device *sdev = sdkp->device;
3396 if (!sdev->security_supported)
3399 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3400 SECURITY_PROTOCOL_IN, 0) == 1 &&
3401 scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3402 SECURITY_PROTOCOL_OUT, 0) == 1)
3406 static inline sector_t sd64_to_sectors(struct scsi_disk *sdkp, u8 *buf)
3408 return logical_to_sectors(sdkp->device, get_unaligned_be64(buf));
3412 * sd_read_cpr - Query concurrent positioning ranges
3413 * @sdkp: disk to query
3415 static void sd_read_cpr(struct scsi_disk *sdkp)
3417 struct blk_independent_access_ranges *iars = NULL;
3418 unsigned char *buffer = NULL;
3419 unsigned int nr_cpr = 0;
3420 int i, vpd_len, buf_len = SD_BUF_SIZE;
3424 * We need to have the capacity set first for the block layer to be
3425 * able to check the ranges.
3427 if (sdkp->first_scan)
3430 if (!sdkp->capacity)
3434 * Concurrent Positioning Ranges VPD: there can be at most 256 ranges,
3435 * leading to a maximum page size of 64 + 256*32 bytes.
3437 buf_len = 64 + 256*32;
3438 buffer = kmalloc(buf_len, GFP_KERNEL);
3439 if (!buffer || scsi_get_vpd_page(sdkp->device, 0xb9, buffer, buf_len))
3442 /* We must have at least a 64B header and one 32B range descriptor */
3443 vpd_len = get_unaligned_be16(&buffer[2]) + 4;
3444 if (vpd_len > buf_len || vpd_len < 64 + 32 || (vpd_len & 31)) {
3445 sd_printk(KERN_ERR, sdkp,
3446 "Invalid Concurrent Positioning Ranges VPD page\n");
3450 nr_cpr = (vpd_len - 64) / 32;
3456 iars = disk_alloc_independent_access_ranges(sdkp->disk, nr_cpr);
3463 for (i = 0; i < nr_cpr; i++, desc += 32) {
3465 sd_printk(KERN_ERR, sdkp,
3466 "Invalid Concurrent Positioning Range number\n");
3471 iars->ia_range[i].sector = sd64_to_sectors(sdkp, desc + 8);
3472 iars->ia_range[i].nr_sectors = sd64_to_sectors(sdkp, desc + 16);
3476 disk_set_independent_access_ranges(sdkp->disk, iars);
3477 if (nr_cpr && sdkp->nr_actuators != nr_cpr) {
3478 sd_printk(KERN_NOTICE, sdkp,
3479 "%u concurrent positioning ranges\n", nr_cpr);
3480 sdkp->nr_actuators = nr_cpr;
3486 static bool sd_validate_min_xfer_size(struct scsi_disk *sdkp)
3488 struct scsi_device *sdp = sdkp->device;
3489 unsigned int min_xfer_bytes =
3490 logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3492 if (sdkp->min_xfer_blocks == 0)
3495 if (min_xfer_bytes & (sdkp->physical_block_size - 1)) {
3496 sd_first_printk(KERN_WARNING, sdkp,
3497 "Preferred minimum I/O size %u bytes not a " \
3498 "multiple of physical block size (%u bytes)\n",
3499 min_xfer_bytes, sdkp->physical_block_size);
3500 sdkp->min_xfer_blocks = 0;
3504 sd_first_printk(KERN_INFO, sdkp, "Preferred minimum I/O size %u bytes\n",
3510 * Determine the device's preferred I/O size for reads and writes
3511 * unless the reported value is unreasonably small, large, not a
3512 * multiple of the physical block size, or simply garbage.
3514 static bool sd_validate_opt_xfer_size(struct scsi_disk *sdkp,
3515 unsigned int dev_max)
3517 struct scsi_device *sdp = sdkp->device;
3518 unsigned int opt_xfer_bytes =
3519 logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
3520 unsigned int min_xfer_bytes =
3521 logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3523 if (sdkp->opt_xfer_blocks == 0)
3526 if (sdkp->opt_xfer_blocks > dev_max) {
3527 sd_first_printk(KERN_WARNING, sdkp,
3528 "Optimal transfer size %u logical blocks " \
3529 "> dev_max (%u logical blocks)\n",
3530 sdkp->opt_xfer_blocks, dev_max);
3534 if (sdkp->opt_xfer_blocks > SD_DEF_XFER_BLOCKS) {
3535 sd_first_printk(KERN_WARNING, sdkp,
3536 "Optimal transfer size %u logical blocks " \
3537 "> sd driver limit (%u logical blocks)\n",
3538 sdkp->opt_xfer_blocks, SD_DEF_XFER_BLOCKS);
3542 if (opt_xfer_bytes < PAGE_SIZE) {
3543 sd_first_printk(KERN_WARNING, sdkp,
3544 "Optimal transfer size %u bytes < " \
3545 "PAGE_SIZE (%u bytes)\n",
3546 opt_xfer_bytes, (unsigned int)PAGE_SIZE);
3550 if (min_xfer_bytes && opt_xfer_bytes % min_xfer_bytes) {
3551 sd_first_printk(KERN_WARNING, sdkp,
3552 "Optimal transfer size %u bytes not a " \
3553 "multiple of preferred minimum block " \
3554 "size (%u bytes)\n",
3555 opt_xfer_bytes, min_xfer_bytes);
3559 if (opt_xfer_bytes & (sdkp->physical_block_size - 1)) {
3560 sd_first_printk(KERN_WARNING, sdkp,
3561 "Optimal transfer size %u bytes not a " \
3562 "multiple of physical block size (%u bytes)\n",
3563 opt_xfer_bytes, sdkp->physical_block_size);
3567 sd_first_printk(KERN_INFO, sdkp, "Optimal transfer size %u bytes\n",
3572 static void sd_read_block_zero(struct scsi_disk *sdkp)
3574 unsigned int buf_len = sdkp->device->sector_size;
3575 char *buffer, cmd[10] = { };
3577 buffer = kmalloc(buf_len, GFP_KERNEL);
3582 put_unaligned_be32(0, &cmd[2]); /* Logical block address 0 */
3583 put_unaligned_be16(1, &cmd[7]); /* Transfer 1 logical block */
3585 scsi_execute_cmd(sdkp->device, cmd, REQ_OP_DRV_IN, buffer, buf_len,
3586 SD_TIMEOUT, sdkp->max_retries, NULL);
3591 * sd_revalidate_disk - called the first time a new disk is seen,
3592 * performs disk spin up, read_capacity, etc.
3593 * @disk: struct gendisk we care about
3595 static int sd_revalidate_disk(struct gendisk *disk)
3597 struct scsi_disk *sdkp = scsi_disk(disk);
3598 struct scsi_device *sdp = sdkp->device;
3599 sector_t old_capacity = sdkp->capacity;
3600 struct queue_limits lim;
3601 unsigned char *buffer;
3602 unsigned int dev_max;
3605 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
3606 "sd_revalidate_disk\n"));
3609 * If the device is offline, don't try and read capacity or any
3610 * of the other niceties.
3612 if (!scsi_device_online(sdp))
3615 buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
3617 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
3618 "allocation failure.\n");
3622 sd_spinup_disk(sdkp);
3624 lim = queue_limits_start_update(sdkp->disk->queue);
3627 * Without media there is no reason to ask; moreover, some devices
3628 * react badly if we do.
3630 if (sdkp->media_present) {
3631 sd_read_capacity(sdkp, &lim, buffer);
3633 * Some USB/UAS devices return generic values for mode pages
3634 * until the media has been accessed. Trigger a READ operation
3635 * to force the device to populate mode pages.
3637 if (sdp->read_before_ms)
3638 sd_read_block_zero(sdkp);
3640 * set the default to rotational. All non-rotational devices
3641 * support the block characteristics VPD page, which will
3642 * cause this to be updated correctly and any device which
3643 * doesn't support it should be treated as rotational.
3645 lim.features |= (BLK_FEAT_ROTATIONAL | BLK_FEAT_ADD_RANDOM);
3647 if (scsi_device_supports_vpd(sdp)) {
3648 sd_read_block_provisioning(sdkp);
3649 sd_read_block_limits(sdkp, &lim);
3650 sd_read_block_limits_ext(sdkp);
3651 sd_read_block_characteristics(sdkp, &lim);
3652 sd_zbc_read_zones(sdkp, &lim, buffer);
3656 sd_print_capacity(sdkp, old_capacity);
3658 sd_read_write_protect_flag(sdkp, buffer);
3659 sd_read_cache_type(sdkp, buffer);
3660 sd_read_io_hints(sdkp, buffer);
3661 sd_read_app_tag_own(sdkp, buffer);
3662 sd_read_write_same(sdkp, buffer);
3663 sd_read_security(sdkp, buffer);
3664 sd_config_protection(sdkp, &lim);
3668 * We now have all cache related info, determine how we deal
3669 * with flush requests.
3671 sd_set_flush_flag(sdkp, &lim);
3673 /* Initial block count limit based on CDB TRANSFER LENGTH field size. */
3674 dev_max = sdp->use_16_for_rw ? SD_MAX_XFER_BLOCKS : SD_DEF_XFER_BLOCKS;
3676 /* Some devices report a maximum block count for READ/WRITE requests. */
3677 dev_max = min_not_zero(dev_max, sdkp->max_xfer_blocks);
3678 lim.max_dev_sectors = logical_to_sectors(sdp, dev_max);
3680 if (sd_validate_min_xfer_size(sdkp))
3681 lim.io_min = logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3686 * Limit default to SCSI host optimal sector limit if set. There may be
3687 * an impact on performance for when the size of a request exceeds this
3690 lim.io_opt = sdp->host->opt_sectors << SECTOR_SHIFT;
3691 if (sd_validate_opt_xfer_size(sdkp, dev_max)) {
3692 lim.io_opt = min_not_zero(lim.io_opt,
3693 logical_to_bytes(sdp, sdkp->opt_xfer_blocks));
3696 sdkp->first_scan = 0;
3698 set_capacity_and_notify(disk, logical_to_sectors(sdp, sdkp->capacity));
3699 sd_config_write_same(sdkp, &lim);
3702 blk_mq_freeze_queue(sdkp->disk->queue);
3703 err = queue_limits_commit_update(sdkp->disk->queue, &lim);
3704 blk_mq_unfreeze_queue(sdkp->disk->queue);
3709 * For a zoned drive, revalidating the zones can be done only once
3710 * the gendisk capacity is set. So if this fails, set back the gendisk
3713 if (sd_zbc_revalidate_zones(sdkp))
3714 set_capacity_and_notify(disk, 0);
3721 * sd_unlock_native_capacity - unlock native capacity
3722 * @disk: struct gendisk to set capacity for
3724 * Block layer calls this function if it detects that partitions
3725 * on @disk reach beyond the end of the device. If the SCSI host
3726 * implements ->unlock_native_capacity() method, it's invoked to
3727 * give it a chance to adjust the device capacity.
3730 * Defined by block layer. Might sleep.
3732 static void sd_unlock_native_capacity(struct gendisk *disk)
3734 struct scsi_device *sdev = scsi_disk(disk)->device;
3736 if (sdev->host->hostt->unlock_native_capacity)
3737 sdev->host->hostt->unlock_native_capacity(sdev);
3741 * sd_format_disk_name - format disk name
3742 * @prefix: name prefix - ie. "sd" for SCSI disks
3743 * @index: index of the disk to format name for
3744 * @buf: output buffer
3745 * @buflen: length of the output buffer
3747 * SCSI disk names starts at sda. The 26th device is sdz and the
3748 * 27th is sdaa. The last one for two lettered suffix is sdzz
3749 * which is followed by sdaaa.
3751 * This is basically 26 base counting with one extra 'nil' entry
3752 * at the beginning from the second digit on and can be
3753 * determined using similar method as 26 base conversion with the
3754 * index shifted -1 after each digit is computed.
3760 * 0 on success, -errno on failure.
3762 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
3764 const int base = 'z' - 'a' + 1;
3765 char *begin = buf + strlen(prefix);
3766 char *end = buf + buflen;
3776 *--p = 'a' + (index % unit);
3777 index = (index / unit) - 1;
3778 } while (index >= 0);
3780 memmove(begin, p, end - p);
3781 memcpy(buf, prefix, strlen(prefix));
3787 * sd_probe - called during driver initialization and whenever a
3788 * new scsi device is attached to the system. It is called once
3789 * for each scsi device (not just disks) present.
3790 * @dev: pointer to device object
3792 * Returns 0 if successful (or not interested in this scsi device
3793 * (e.g. scanner)); 1 when there is an error.
3795 * Note: this function is invoked from the scsi mid-level.
3796 * This function sets up the mapping between a given
3797 * <host,channel,id,lun> (found in sdp) and new device name
3798 * (e.g. /dev/sda). More precisely it is the block device major
3799 * and minor number that is chosen here.
3801 * Assume sd_probe is not re-entrant (for time being)
3802 * Also think about sd_probe() and sd_remove() running coincidentally.
3804 static int sd_probe(struct device *dev)
3806 struct scsi_device *sdp = to_scsi_device(dev);
3807 struct scsi_disk *sdkp;
3812 scsi_autopm_get_device(sdp);
3814 if (sdp->type != TYPE_DISK &&
3815 sdp->type != TYPE_ZBC &&
3816 sdp->type != TYPE_MOD &&
3817 sdp->type != TYPE_RBC)
3820 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) && sdp->type == TYPE_ZBC) {
3821 sdev_printk(KERN_WARNING, sdp,
3822 "Unsupported ZBC host-managed device.\n");
3826 SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
3830 sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
3834 gd = blk_mq_alloc_disk_for_queue(sdp->request_queue,
3835 &sd_bio_compl_lkclass);
3839 index = ida_alloc(&sd_index_ida, GFP_KERNEL);
3841 sdev_printk(KERN_WARNING, sdp, "sd_probe: memory exhausted.\n");
3845 error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
3847 sdev_printk(KERN_WARNING, sdp, "SCSI disk (sd) name length exceeded.\n");
3848 goto out_free_index;
3853 sdkp->index = index;
3854 sdkp->max_retries = SD_MAX_RETRIES;
3855 atomic_set(&sdkp->openers, 0);
3856 atomic_set(&sdkp->device->ioerr_cnt, 0);
3858 if (!sdp->request_queue->rq_timeout) {
3859 if (sdp->type != TYPE_MOD)
3860 blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
3862 blk_queue_rq_timeout(sdp->request_queue,
3866 device_initialize(&sdkp->disk_dev);
3867 sdkp->disk_dev.parent = get_device(dev);
3868 sdkp->disk_dev.class = &sd_disk_class;
3869 dev_set_name(&sdkp->disk_dev, "%s", dev_name(dev));
3871 error = device_add(&sdkp->disk_dev);
3873 put_device(&sdkp->disk_dev);
3877 dev_set_drvdata(dev, sdkp);
3879 gd->major = sd_major((index & 0xf0) >> 4);
3880 gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
3881 gd->minors = SD_MINORS;
3883 gd->fops = &sd_fops;
3884 gd->private_data = sdkp;
3886 /* defaults, until the device tells us otherwise */
3887 sdp->sector_size = 512;
3889 sdkp->media_present = 1;
3890 sdkp->write_prot = 0;
3891 sdkp->cache_override = 0;
3895 sdkp->first_scan = 1;
3896 sdkp->max_medium_access_timeouts = SD_MAX_MEDIUM_TIMEOUTS;
3898 sd_revalidate_disk(gd);
3900 if (sdp->removable) {
3901 gd->flags |= GENHD_FL_REMOVABLE;
3902 gd->events |= DISK_EVENT_MEDIA_CHANGE;
3903 gd->event_flags = DISK_EVENT_FLAG_POLL | DISK_EVENT_FLAG_UEVENT;
3906 blk_pm_runtime_init(sdp->request_queue, dev);
3907 if (sdp->rpm_autosuspend) {
3908 pm_runtime_set_autosuspend_delay(dev,
3909 sdp->host->rpm_autosuspend_delay);
3912 error = device_add_disk(dev, gd, NULL);
3914 device_unregister(&sdkp->disk_dev);
3919 if (sdkp->security) {
3920 sdkp->opal_dev = init_opal_dev(sdkp, &sd_sec_submit);
3922 sd_printk(KERN_NOTICE, sdkp, "supports TCG Opal\n");
3925 sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
3926 sdp->removable ? "removable " : "");
3927 scsi_autopm_put_device(sdp);
3932 ida_free(&sd_index_ida, index);
3938 scsi_autopm_put_device(sdp);
3943 * sd_remove - called whenever a scsi disk (previously recognized by
3944 * sd_probe) is detached from the system. It is called (potentially
3945 * multiple times) during sd module unload.
3946 * @dev: pointer to device object
3948 * Note: this function is invoked from the scsi mid-level.
3949 * This function potentially frees up a device name (e.g. /dev/sdc)
3950 * that could be re-used by a subsequent sd_probe().
3951 * This function is not called when the built-in sd driver is "exit-ed".
3953 static int sd_remove(struct device *dev)
3955 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3957 scsi_autopm_get_device(sdkp->device);
3959 device_del(&sdkp->disk_dev);
3960 del_gendisk(sdkp->disk);
3961 if (!sdkp->suspended)
3964 put_disk(sdkp->disk);
3968 static void scsi_disk_release(struct device *dev)
3970 struct scsi_disk *sdkp = to_scsi_disk(dev);
3972 ida_free(&sd_index_ida, sdkp->index);
3973 put_device(&sdkp->device->sdev_gendev);
3974 free_opal_dev(sdkp->opal_dev);
3979 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
3981 unsigned char cmd[6] = { START_STOP }; /* START_VALID */
3982 struct scsi_sense_hdr sshdr;
3983 const struct scsi_exec_args exec_args = {
3985 .req_flags = BLK_MQ_REQ_PM,
3987 struct scsi_device *sdp = sdkp->device;
3991 cmd[4] |= 1; /* START */
3993 if (sdp->start_stop_pwr_cond)
3994 cmd[4] |= start ? 1 << 4 : 3 << 4; /* Active or Standby */
3996 if (!scsi_device_online(sdp))
3999 res = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, NULL, 0, SD_TIMEOUT,
4000 sdkp->max_retries, &exec_args);
4002 sd_print_result(sdkp, "Start/Stop Unit failed", res);
4003 if (res > 0 && scsi_sense_valid(&sshdr)) {
4004 sd_print_sense_hdr(sdkp, &sshdr);
4005 /* 0x3a is medium not present */
4006 if (sshdr.asc == 0x3a)
4011 /* SCSI error codes must not go to the generic layer */
4019 * Send a SYNCHRONIZE CACHE instruction down to the device through
4020 * the normal SCSI command structure. Wait for the command to
4023 static void sd_shutdown(struct device *dev)
4025 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4028 return; /* this can happen */
4030 if (pm_runtime_suspended(dev))
4033 if (sdkp->WCE && sdkp->media_present) {
4034 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
4035 sd_sync_cache(sdkp);
4038 if ((system_state != SYSTEM_RESTART &&
4039 sdkp->device->manage_system_start_stop) ||
4040 (system_state == SYSTEM_POWER_OFF &&
4041 sdkp->device->manage_shutdown)) {
4042 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
4043 sd_start_stop_device(sdkp, 0);
4047 static inline bool sd_do_start_stop(struct scsi_device *sdev, bool runtime)
4049 return (sdev->manage_system_start_stop && !runtime) ||
4050 (sdev->manage_runtime_start_stop && runtime);
4053 static int sd_suspend_common(struct device *dev, bool runtime)
4055 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4058 if (!sdkp) /* E.g.: runtime suspend following sd_remove() */
4061 if (sdkp->WCE && sdkp->media_present) {
4062 if (!sdkp->device->silence_suspend)
4063 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
4064 ret = sd_sync_cache(sdkp);
4065 /* ignore OFFLINE device */
4073 if (sd_do_start_stop(sdkp->device, runtime)) {
4074 if (!sdkp->device->silence_suspend)
4075 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
4076 /* an error is not worth aborting a system sleep */
4077 ret = sd_start_stop_device(sdkp, 0);
4083 sdkp->suspended = true;
4088 static int sd_suspend_system(struct device *dev)
4090 if (pm_runtime_suspended(dev))
4093 return sd_suspend_common(dev, false);
4096 static int sd_suspend_runtime(struct device *dev)
4098 return sd_suspend_common(dev, true);
4101 static int sd_resume(struct device *dev)
4103 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4105 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
4107 if (opal_unlock_from_suspend(sdkp->opal_dev)) {
4108 sd_printk(KERN_NOTICE, sdkp, "OPAL unlock failed\n");
4115 static int sd_resume_common(struct device *dev, bool runtime)
4117 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4120 if (!sdkp) /* E.g.: runtime resume at the start of sd_probe() */
4123 if (!sd_do_start_stop(sdkp->device, runtime)) {
4124 sdkp->suspended = false;
4128 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
4129 ret = sd_start_stop_device(sdkp, 1);
4132 sdkp->suspended = false;
4138 static int sd_resume_system(struct device *dev)
4140 if (pm_runtime_suspended(dev)) {
4141 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4142 struct scsi_device *sdp = sdkp ? sdkp->device : NULL;
4144 if (sdp && sdp->force_runtime_start_on_system_start)
4145 pm_request_resume(dev);
4150 return sd_resume_common(dev, false);
4153 static int sd_resume_runtime(struct device *dev)
4155 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4156 struct scsi_device *sdp;
4158 if (!sdkp) /* E.g.: runtime resume at the start of sd_probe() */
4163 if (sdp->ignore_media_change) {
4164 /* clear the device's sense data */
4165 static const u8 cmd[10] = { REQUEST_SENSE };
4166 const struct scsi_exec_args exec_args = {
4167 .req_flags = BLK_MQ_REQ_PM,
4170 if (scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, NULL, 0,
4171 sdp->request_queue->rq_timeout, 1,
4173 sd_printk(KERN_NOTICE, sdkp,
4174 "Failed to clear sense data\n");
4177 return sd_resume_common(dev, true);
4180 static const struct dev_pm_ops sd_pm_ops = {
4181 .suspend = sd_suspend_system,
4182 .resume = sd_resume_system,
4183 .poweroff = sd_suspend_system,
4184 .restore = sd_resume_system,
4185 .runtime_suspend = sd_suspend_runtime,
4186 .runtime_resume = sd_resume_runtime,
4189 static struct scsi_driver sd_template = {
4193 .probe_type = PROBE_PREFER_ASYNCHRONOUS,
4194 .remove = sd_remove,
4195 .shutdown = sd_shutdown,
4198 .rescan = sd_rescan,
4199 .resume = sd_resume,
4200 .init_command = sd_init_command,
4201 .uninit_command = sd_uninit_command,
4203 .eh_action = sd_eh_action,
4204 .eh_reset = sd_eh_reset,
4208 * init_sd - entry point for this driver (both when built in or when
4211 * Note: this function registers this driver with the scsi mid-level.
4213 static int __init init_sd(void)
4215 int majors = 0, i, err;
4217 SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
4219 for (i = 0; i < SD_MAJORS; i++) {
4220 if (__register_blkdev(sd_major(i), "sd", sd_default_probe))
4228 err = class_register(&sd_disk_class);
4232 sd_page_pool = mempool_create_page_pool(SD_MEMPOOL_SIZE, 0);
4233 if (!sd_page_pool) {
4234 printk(KERN_ERR "sd: can't init discard page pool\n");
4239 err = scsi_register_driver(&sd_template.gendrv);
4241 goto err_out_driver;
4246 mempool_destroy(sd_page_pool);
4248 class_unregister(&sd_disk_class);
4250 for (i = 0; i < SD_MAJORS; i++)
4251 unregister_blkdev(sd_major(i), "sd");
4256 * exit_sd - exit point for this driver (when it is a module).
4258 * Note: this function unregisters this driver from the scsi mid-level.
4260 static void __exit exit_sd(void)
4264 SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
4266 scsi_unregister_driver(&sd_template.gendrv);
4267 mempool_destroy(sd_page_pool);
4269 class_unregister(&sd_disk_class);
4271 for (i = 0; i < SD_MAJORS; i++)
4272 unregister_blkdev(sd_major(i), "sd");
4275 module_init(init_sd);
4276 module_exit(exit_sd);
4278 void sd_print_sense_hdr(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr)
4280 scsi_print_sense_hdr(sdkp->device,
4281 sdkp->disk ? sdkp->disk->disk_name : NULL, sshdr);
4284 void sd_print_result(const struct scsi_disk *sdkp, const char *msg, int result)
4286 const char *hb_string = scsi_hostbyte_string(result);
4289 sd_printk(KERN_INFO, sdkp,
4290 "%s: Result: hostbyte=%s driverbyte=%s\n", msg,
4291 hb_string ? hb_string : "invalid",
4294 sd_printk(KERN_INFO, sdkp,
4295 "%s: Result: hostbyte=0x%02x driverbyte=%s\n",
4296 msg, host_byte(result), "DRIVER_OK");