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/bio-integrity.h>
37 #include <linux/module.h>
39 #include <linux/kernel.h>
41 #include <linux/bio-integrity.h>
42 #include <linux/hdreg.h>
43 #include <linux/errno.h>
44 #include <linux/idr.h>
45 #include <linux/interrupt.h>
46 #include <linux/init.h>
47 #include <linux/blkdev.h>
48 #include <linux/blkpg.h>
49 #include <linux/blk-pm.h>
50 #include <linux/delay.h>
51 #include <linux/rw_hint.h>
52 #include <linux/major.h>
53 #include <linux/mutex.h>
54 #include <linux/string_helpers.h>
55 #include <linux/slab.h>
56 #include <linux/sed-opal.h>
57 #include <linux/pm_runtime.h>
59 #include <linux/t10-pi.h>
60 #include <linux/uaccess.h>
61 #include <asm/unaligned.h>
63 #include <scsi/scsi.h>
64 #include <scsi/scsi_cmnd.h>
65 #include <scsi/scsi_dbg.h>
66 #include <scsi/scsi_device.h>
67 #include <scsi/scsi_devinfo.h>
68 #include <scsi/scsi_driver.h>
69 #include <scsi/scsi_eh.h>
70 #include <scsi/scsi_host.h>
71 #include <scsi/scsi_ioctl.h>
72 #include <scsi/scsicam.h>
73 #include <scsi/scsi_common.h>
76 #include "scsi_priv.h"
77 #include "scsi_logging.h"
79 MODULE_AUTHOR("Eric Youngdale");
80 MODULE_DESCRIPTION("SCSI disk (sd) driver");
81 MODULE_LICENSE("GPL");
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
88 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
89 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
90 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
91 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
92 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
93 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
94 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
95 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
96 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
97 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
98 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
99 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
100 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
101 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
102 MODULE_ALIAS_SCSI_DEVICE(TYPE_ZBC);
106 static void sd_config_discard(struct scsi_disk *sdkp, struct queue_limits *lim,
108 static void sd_config_write_same(struct scsi_disk *sdkp,
109 struct queue_limits *lim);
110 static int sd_revalidate_disk(struct gendisk *);
111 static void sd_unlock_native_capacity(struct gendisk *disk);
112 static void sd_shutdown(struct device *);
113 static void scsi_disk_release(struct device *cdev);
115 static DEFINE_IDA(sd_index_ida);
117 static mempool_t *sd_page_pool;
118 static struct lock_class_key sd_bio_compl_lkclass;
120 static const char *sd_cache_types[] = {
121 "write through", "none", "write back",
122 "write back, no read (daft)"
125 static void sd_set_flush_flag(struct scsi_disk *sdkp,
126 struct queue_limits *lim)
129 lim->features |= BLK_FEAT_WRITE_CACHE;
131 lim->features |= BLK_FEAT_FUA;
133 lim->features &= ~BLK_FEAT_FUA;
135 lim->features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
140 cache_type_store(struct device *dev, struct device_attribute *attr,
141 const char *buf, size_t count)
143 int ct, rcd, wce, sp;
144 struct scsi_disk *sdkp = to_scsi_disk(dev);
145 struct scsi_device *sdp = sdkp->device;
148 struct scsi_mode_data data;
149 struct scsi_sense_hdr sshdr;
150 static const char temp[] = "temporary ";
153 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
154 /* no cache control on RBC devices; theoretically they
155 * can do it, but there's probably so many exceptions
156 * it's not worth the risk */
159 if (strncmp(buf, temp, sizeof(temp) - 1) == 0) {
160 buf += sizeof(temp) - 1;
161 sdkp->cache_override = 1;
163 sdkp->cache_override = 0;
166 ct = sysfs_match_string(sd_cache_types, buf);
170 rcd = ct & 0x01 ? 1 : 0;
171 wce = (ct & 0x02) && !sdkp->write_prot ? 1 : 0;
173 if (sdkp->cache_override) {
174 struct queue_limits lim;
179 lim = queue_limits_start_update(sdkp->disk->queue);
180 sd_set_flush_flag(sdkp, &lim);
181 blk_mq_freeze_queue(sdkp->disk->queue);
182 ret = queue_limits_commit_update(sdkp->disk->queue, &lim);
183 blk_mq_unfreeze_queue(sdkp->disk->queue);
189 if (scsi_mode_sense(sdp, 0x08, 8, 0, buffer, sizeof(buffer), SD_TIMEOUT,
190 sdkp->max_retries, &data, NULL))
192 len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
193 data.block_descriptor_length);
194 buffer_data = buffer + data.header_length +
195 data.block_descriptor_length;
196 buffer_data[2] &= ~0x05;
197 buffer_data[2] |= wce << 2 | rcd;
198 sp = buffer_data[0] & 0x80 ? 1 : 0;
199 buffer_data[0] &= ~0x80;
202 * Ensure WP, DPOFUA, and RESERVED fields are cleared in
203 * received mode parameter buffer before doing MODE SELECT.
205 data.device_specific = 0;
207 ret = scsi_mode_select(sdp, 1, sp, buffer_data, len, SD_TIMEOUT,
208 sdkp->max_retries, &data, &sshdr);
210 if (ret > 0 && scsi_sense_valid(&sshdr))
211 sd_print_sense_hdr(sdkp, &sshdr);
214 sd_revalidate_disk(sdkp->disk);
219 manage_start_stop_show(struct device *dev,
220 struct device_attribute *attr, char *buf)
222 struct scsi_disk *sdkp = to_scsi_disk(dev);
223 struct scsi_device *sdp = sdkp->device;
225 return sysfs_emit(buf, "%u\n",
226 sdp->manage_system_start_stop &&
227 sdp->manage_runtime_start_stop &&
228 sdp->manage_shutdown);
230 static DEVICE_ATTR_RO(manage_start_stop);
233 manage_system_start_stop_show(struct device *dev,
234 struct device_attribute *attr, char *buf)
236 struct scsi_disk *sdkp = to_scsi_disk(dev);
237 struct scsi_device *sdp = sdkp->device;
239 return sysfs_emit(buf, "%u\n", sdp->manage_system_start_stop);
243 manage_system_start_stop_store(struct device *dev,
244 struct device_attribute *attr,
245 const char *buf, size_t count)
247 struct scsi_disk *sdkp = to_scsi_disk(dev);
248 struct scsi_device *sdp = sdkp->device;
251 if (!capable(CAP_SYS_ADMIN))
254 if (kstrtobool(buf, &v))
257 sdp->manage_system_start_stop = v;
261 static DEVICE_ATTR_RW(manage_system_start_stop);
264 manage_runtime_start_stop_show(struct device *dev,
265 struct device_attribute *attr, char *buf)
267 struct scsi_disk *sdkp = to_scsi_disk(dev);
268 struct scsi_device *sdp = sdkp->device;
270 return sysfs_emit(buf, "%u\n", sdp->manage_runtime_start_stop);
274 manage_runtime_start_stop_store(struct device *dev,
275 struct device_attribute *attr,
276 const char *buf, size_t count)
278 struct scsi_disk *sdkp = to_scsi_disk(dev);
279 struct scsi_device *sdp = sdkp->device;
282 if (!capable(CAP_SYS_ADMIN))
285 if (kstrtobool(buf, &v))
288 sdp->manage_runtime_start_stop = v;
292 static DEVICE_ATTR_RW(manage_runtime_start_stop);
294 static ssize_t manage_shutdown_show(struct device *dev,
295 struct device_attribute *attr, char *buf)
297 struct scsi_disk *sdkp = to_scsi_disk(dev);
298 struct scsi_device *sdp = sdkp->device;
300 return sysfs_emit(buf, "%u\n", sdp->manage_shutdown);
303 static ssize_t manage_shutdown_store(struct device *dev,
304 struct device_attribute *attr,
305 const char *buf, size_t count)
307 struct scsi_disk *sdkp = to_scsi_disk(dev);
308 struct scsi_device *sdp = sdkp->device;
311 if (!capable(CAP_SYS_ADMIN))
314 if (kstrtobool(buf, &v))
317 sdp->manage_shutdown = v;
321 static DEVICE_ATTR_RW(manage_shutdown);
324 allow_restart_show(struct device *dev, struct device_attribute *attr, char *buf)
326 struct scsi_disk *sdkp = to_scsi_disk(dev);
328 return sprintf(buf, "%u\n", sdkp->device->allow_restart);
332 allow_restart_store(struct device *dev, struct device_attribute *attr,
333 const char *buf, size_t count)
336 struct scsi_disk *sdkp = to_scsi_disk(dev);
337 struct scsi_device *sdp = sdkp->device;
339 if (!capable(CAP_SYS_ADMIN))
342 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
345 if (kstrtobool(buf, &v))
348 sdp->allow_restart = v;
352 static DEVICE_ATTR_RW(allow_restart);
355 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
357 struct scsi_disk *sdkp = to_scsi_disk(dev);
358 int ct = sdkp->RCD + 2*sdkp->WCE;
360 return sprintf(buf, "%s\n", sd_cache_types[ct]);
362 static DEVICE_ATTR_RW(cache_type);
365 FUA_show(struct device *dev, struct device_attribute *attr, char *buf)
367 struct scsi_disk *sdkp = to_scsi_disk(dev);
369 return sprintf(buf, "%u\n", sdkp->DPOFUA);
371 static DEVICE_ATTR_RO(FUA);
374 protection_type_show(struct device *dev, struct device_attribute *attr,
377 struct scsi_disk *sdkp = to_scsi_disk(dev);
379 return sprintf(buf, "%u\n", sdkp->protection_type);
383 protection_type_store(struct device *dev, struct device_attribute *attr,
384 const char *buf, size_t count)
386 struct scsi_disk *sdkp = to_scsi_disk(dev);
390 if (!capable(CAP_SYS_ADMIN))
393 err = kstrtouint(buf, 10, &val);
398 if (val <= T10_PI_TYPE3_PROTECTION)
399 sdkp->protection_type = val;
403 static DEVICE_ATTR_RW(protection_type);
406 protection_mode_show(struct device *dev, struct device_attribute *attr,
409 struct scsi_disk *sdkp = to_scsi_disk(dev);
410 struct scsi_device *sdp = sdkp->device;
411 unsigned int dif, dix;
413 dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
414 dix = scsi_host_dix_capable(sdp->host, sdkp->protection_type);
416 if (!dix && scsi_host_dix_capable(sdp->host, T10_PI_TYPE0_PROTECTION)) {
422 return sprintf(buf, "none\n");
424 return sprintf(buf, "%s%u\n", dix ? "dix" : "dif", dif);
426 static DEVICE_ATTR_RO(protection_mode);
429 app_tag_own_show(struct device *dev, struct device_attribute *attr, char *buf)
431 struct scsi_disk *sdkp = to_scsi_disk(dev);
433 return sprintf(buf, "%u\n", sdkp->ATO);
435 static DEVICE_ATTR_RO(app_tag_own);
438 thin_provisioning_show(struct device *dev, struct device_attribute *attr,
441 struct scsi_disk *sdkp = to_scsi_disk(dev);
443 return sprintf(buf, "%u\n", sdkp->lbpme);
445 static DEVICE_ATTR_RO(thin_provisioning);
447 /* sysfs_match_string() requires dense arrays */
448 static const char *lbp_mode[] = {
449 [SD_LBP_FULL] = "full",
450 [SD_LBP_UNMAP] = "unmap",
451 [SD_LBP_WS16] = "writesame_16",
452 [SD_LBP_WS10] = "writesame_10",
453 [SD_LBP_ZERO] = "writesame_zero",
454 [SD_LBP_DISABLE] = "disabled",
458 provisioning_mode_show(struct device *dev, struct device_attribute *attr,
461 struct scsi_disk *sdkp = to_scsi_disk(dev);
463 return sprintf(buf, "%s\n", lbp_mode[sdkp->provisioning_mode]);
467 provisioning_mode_store(struct device *dev, struct device_attribute *attr,
468 const char *buf, size_t count)
470 struct scsi_disk *sdkp = to_scsi_disk(dev);
471 struct scsi_device *sdp = sdkp->device;
472 struct queue_limits lim;
475 if (!capable(CAP_SYS_ADMIN))
478 if (sdp->type != TYPE_DISK)
481 mode = sysfs_match_string(lbp_mode, buf);
485 lim = queue_limits_start_update(sdkp->disk->queue);
486 sd_config_discard(sdkp, &lim, mode);
487 blk_mq_freeze_queue(sdkp->disk->queue);
488 err = queue_limits_commit_update(sdkp->disk->queue, &lim);
489 blk_mq_unfreeze_queue(sdkp->disk->queue);
494 static DEVICE_ATTR_RW(provisioning_mode);
496 /* sysfs_match_string() requires dense arrays */
497 static const char *zeroing_mode[] = {
498 [SD_ZERO_WRITE] = "write",
499 [SD_ZERO_WS] = "writesame",
500 [SD_ZERO_WS16_UNMAP] = "writesame_16_unmap",
501 [SD_ZERO_WS10_UNMAP] = "writesame_10_unmap",
505 zeroing_mode_show(struct device *dev, struct device_attribute *attr,
508 struct scsi_disk *sdkp = to_scsi_disk(dev);
510 return sprintf(buf, "%s\n", zeroing_mode[sdkp->zeroing_mode]);
514 zeroing_mode_store(struct device *dev, struct device_attribute *attr,
515 const char *buf, size_t count)
517 struct scsi_disk *sdkp = to_scsi_disk(dev);
520 if (!capable(CAP_SYS_ADMIN))
523 mode = sysfs_match_string(zeroing_mode, buf);
527 sdkp->zeroing_mode = mode;
531 static DEVICE_ATTR_RW(zeroing_mode);
534 max_medium_access_timeouts_show(struct device *dev,
535 struct device_attribute *attr, char *buf)
537 struct scsi_disk *sdkp = to_scsi_disk(dev);
539 return sprintf(buf, "%u\n", sdkp->max_medium_access_timeouts);
543 max_medium_access_timeouts_store(struct device *dev,
544 struct device_attribute *attr, const char *buf,
547 struct scsi_disk *sdkp = to_scsi_disk(dev);
550 if (!capable(CAP_SYS_ADMIN))
553 err = kstrtouint(buf, 10, &sdkp->max_medium_access_timeouts);
555 return err ? err : count;
557 static DEVICE_ATTR_RW(max_medium_access_timeouts);
560 max_write_same_blocks_show(struct device *dev, struct device_attribute *attr,
563 struct scsi_disk *sdkp = to_scsi_disk(dev);
565 return sprintf(buf, "%u\n", sdkp->max_ws_blocks);
569 max_write_same_blocks_store(struct device *dev, struct device_attribute *attr,
570 const char *buf, size_t count)
572 struct scsi_disk *sdkp = to_scsi_disk(dev);
573 struct scsi_device *sdp = sdkp->device;
574 struct queue_limits lim;
578 if (!capable(CAP_SYS_ADMIN))
581 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
584 err = kstrtoul(buf, 10, &max);
590 sdp->no_write_same = 1;
591 else if (max <= SD_MAX_WS16_BLOCKS) {
592 sdp->no_write_same = 0;
593 sdkp->max_ws_blocks = max;
596 lim = queue_limits_start_update(sdkp->disk->queue);
597 sd_config_write_same(sdkp, &lim);
598 blk_mq_freeze_queue(sdkp->disk->queue);
599 err = queue_limits_commit_update(sdkp->disk->queue, &lim);
600 blk_mq_unfreeze_queue(sdkp->disk->queue);
605 static DEVICE_ATTR_RW(max_write_same_blocks);
608 zoned_cap_show(struct device *dev, struct device_attribute *attr, char *buf)
610 struct scsi_disk *sdkp = to_scsi_disk(dev);
612 if (sdkp->device->type == TYPE_ZBC)
613 return sprintf(buf, "host-managed\n");
614 if (sdkp->zoned == 1)
615 return sprintf(buf, "host-aware\n");
616 if (sdkp->zoned == 2)
617 return sprintf(buf, "drive-managed\n");
618 return sprintf(buf, "none\n");
620 static DEVICE_ATTR_RO(zoned_cap);
623 max_retries_store(struct device *dev, struct device_attribute *attr,
624 const char *buf, size_t count)
626 struct scsi_disk *sdkp = to_scsi_disk(dev);
627 struct scsi_device *sdev = sdkp->device;
630 err = kstrtoint(buf, 10, &retries);
634 if (retries == SCSI_CMD_RETRIES_NO_LIMIT || retries <= SD_MAX_RETRIES) {
635 sdkp->max_retries = retries;
639 sdev_printk(KERN_ERR, sdev, "max_retries must be between -1 and %d\n",
645 max_retries_show(struct device *dev, struct device_attribute *attr,
648 struct scsi_disk *sdkp = to_scsi_disk(dev);
650 return sprintf(buf, "%d\n", sdkp->max_retries);
653 static DEVICE_ATTR_RW(max_retries);
655 static struct attribute *sd_disk_attrs[] = {
656 &dev_attr_cache_type.attr,
658 &dev_attr_allow_restart.attr,
659 &dev_attr_manage_start_stop.attr,
660 &dev_attr_manage_system_start_stop.attr,
661 &dev_attr_manage_runtime_start_stop.attr,
662 &dev_attr_manage_shutdown.attr,
663 &dev_attr_protection_type.attr,
664 &dev_attr_protection_mode.attr,
665 &dev_attr_app_tag_own.attr,
666 &dev_attr_thin_provisioning.attr,
667 &dev_attr_provisioning_mode.attr,
668 &dev_attr_zeroing_mode.attr,
669 &dev_attr_max_write_same_blocks.attr,
670 &dev_attr_max_medium_access_timeouts.attr,
671 &dev_attr_zoned_cap.attr,
672 &dev_attr_max_retries.attr,
675 ATTRIBUTE_GROUPS(sd_disk);
677 static struct class sd_disk_class = {
679 .dev_release = scsi_disk_release,
680 .dev_groups = sd_disk_groups,
684 * Don't request a new module, as that could deadlock in multipath
687 static void sd_default_probe(dev_t devt)
692 * Device no to disk mapping:
694 * major disc2 disc p1
695 * |............|.............|....|....| <- dev_t
698 * Inside a major, we have 16k disks, however mapped non-
699 * contiguously. The first 16 disks are for major0, the next
700 * ones with major1, ... Disk 256 is for major0 again, disk 272
702 * As we stay compatible with our numbering scheme, we can reuse
703 * the well-know SCSI majors 8, 65--71, 136--143.
705 static int sd_major(int major_idx)
709 return SCSI_DISK0_MAJOR;
711 return SCSI_DISK1_MAJOR + major_idx - 1;
713 return SCSI_DISK8_MAJOR + major_idx - 8;
716 return 0; /* shut up gcc */
720 #ifdef CONFIG_BLK_SED_OPAL
721 static int sd_sec_submit(void *data, u16 spsp, u8 secp, void *buffer,
722 size_t len, bool send)
724 struct scsi_disk *sdkp = data;
725 struct scsi_device *sdev = sdkp->device;
727 const struct scsi_exec_args exec_args = {
728 .req_flags = BLK_MQ_REQ_PM,
732 cdb[0] = send ? SECURITY_PROTOCOL_OUT : SECURITY_PROTOCOL_IN;
734 put_unaligned_be16(spsp, &cdb[2]);
735 put_unaligned_be32(len, &cdb[6]);
737 ret = scsi_execute_cmd(sdev, cdb, send ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN,
738 buffer, len, SD_TIMEOUT, sdkp->max_retries,
740 return ret <= 0 ? ret : -EIO;
742 #endif /* CONFIG_BLK_SED_OPAL */
745 * Look up the DIX operation based on whether the command is read or
746 * write and whether dix and dif are enabled.
748 static unsigned int sd_prot_op(bool write, bool dix, bool dif)
750 /* Lookup table: bit 2 (write), bit 1 (dix), bit 0 (dif) */
751 static const unsigned int ops[] = { /* wrt dix dif */
752 SCSI_PROT_NORMAL, /* 0 0 0 */
753 SCSI_PROT_READ_STRIP, /* 0 0 1 */
754 SCSI_PROT_READ_INSERT, /* 0 1 0 */
755 SCSI_PROT_READ_PASS, /* 0 1 1 */
756 SCSI_PROT_NORMAL, /* 1 0 0 */
757 SCSI_PROT_WRITE_INSERT, /* 1 0 1 */
758 SCSI_PROT_WRITE_STRIP, /* 1 1 0 */
759 SCSI_PROT_WRITE_PASS, /* 1 1 1 */
762 return ops[write << 2 | dix << 1 | dif];
766 * Returns a mask of the protection flags that are valid for a given DIX
769 static unsigned int sd_prot_flag_mask(unsigned int prot_op)
771 static const unsigned int flag_mask[] = {
772 [SCSI_PROT_NORMAL] = 0,
774 [SCSI_PROT_READ_STRIP] = SCSI_PROT_TRANSFER_PI |
775 SCSI_PROT_GUARD_CHECK |
776 SCSI_PROT_REF_CHECK |
777 SCSI_PROT_REF_INCREMENT,
779 [SCSI_PROT_READ_INSERT] = SCSI_PROT_REF_INCREMENT |
780 SCSI_PROT_IP_CHECKSUM,
782 [SCSI_PROT_READ_PASS] = SCSI_PROT_TRANSFER_PI |
783 SCSI_PROT_GUARD_CHECK |
784 SCSI_PROT_REF_CHECK |
785 SCSI_PROT_REF_INCREMENT |
786 SCSI_PROT_IP_CHECKSUM,
788 [SCSI_PROT_WRITE_INSERT] = SCSI_PROT_TRANSFER_PI |
789 SCSI_PROT_REF_INCREMENT,
791 [SCSI_PROT_WRITE_STRIP] = SCSI_PROT_GUARD_CHECK |
792 SCSI_PROT_REF_CHECK |
793 SCSI_PROT_REF_INCREMENT |
794 SCSI_PROT_IP_CHECKSUM,
796 [SCSI_PROT_WRITE_PASS] = SCSI_PROT_TRANSFER_PI |
797 SCSI_PROT_GUARD_CHECK |
798 SCSI_PROT_REF_CHECK |
799 SCSI_PROT_REF_INCREMENT |
800 SCSI_PROT_IP_CHECKSUM,
803 return flag_mask[prot_op];
806 static unsigned char sd_setup_protect_cmnd(struct scsi_cmnd *scmd,
807 unsigned int dix, unsigned int dif)
809 struct request *rq = scsi_cmd_to_rq(scmd);
810 struct bio *bio = rq->bio;
811 unsigned int prot_op = sd_prot_op(rq_data_dir(rq), dix, dif);
812 unsigned int protect = 0;
814 if (dix) { /* DIX Type 0, 1, 2, 3 */
815 if (bio_integrity_flagged(bio, BIP_IP_CHECKSUM))
816 scmd->prot_flags |= SCSI_PROT_IP_CHECKSUM;
818 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
819 scmd->prot_flags |= SCSI_PROT_GUARD_CHECK;
822 if (dif != T10_PI_TYPE3_PROTECTION) { /* DIX/DIF Type 0, 1, 2 */
823 scmd->prot_flags |= SCSI_PROT_REF_INCREMENT;
825 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
826 scmd->prot_flags |= SCSI_PROT_REF_CHECK;
829 if (dif) { /* DIX/DIF Type 1, 2, 3 */
830 scmd->prot_flags |= SCSI_PROT_TRANSFER_PI;
832 if (bio_integrity_flagged(bio, BIP_DISK_NOCHECK))
833 protect = 3 << 5; /* Disable target PI checking */
835 protect = 1 << 5; /* Enable target PI checking */
838 scsi_set_prot_op(scmd, prot_op);
839 scsi_set_prot_type(scmd, dif);
840 scmd->prot_flags &= sd_prot_flag_mask(prot_op);
845 static void sd_disable_discard(struct scsi_disk *sdkp)
847 sdkp->provisioning_mode = SD_LBP_DISABLE;
848 blk_queue_disable_discard(sdkp->disk->queue);
851 static void sd_config_discard(struct scsi_disk *sdkp, struct queue_limits *lim,
854 unsigned int logical_block_size = sdkp->device->sector_size;
855 unsigned int max_blocks = 0;
857 lim->discard_alignment = sdkp->unmap_alignment * logical_block_size;
858 lim->discard_granularity = max(sdkp->physical_block_size,
859 sdkp->unmap_granularity * logical_block_size);
860 sdkp->provisioning_mode = mode;
869 max_blocks = min_not_zero(sdkp->max_unmap_blocks,
870 (u32)SD_MAX_WS16_BLOCKS);
874 if (sdkp->device->unmap_limit_for_ws)
875 max_blocks = sdkp->max_unmap_blocks;
877 max_blocks = sdkp->max_ws_blocks;
879 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS16_BLOCKS);
883 if (sdkp->device->unmap_limit_for_ws)
884 max_blocks = sdkp->max_unmap_blocks;
886 max_blocks = sdkp->max_ws_blocks;
888 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS10_BLOCKS);
892 max_blocks = min_not_zero(sdkp->max_ws_blocks,
893 (u32)SD_MAX_WS10_BLOCKS);
897 lim->max_hw_discard_sectors = max_blocks *
898 (logical_block_size >> SECTOR_SHIFT);
901 static void *sd_set_special_bvec(struct request *rq, unsigned int data_len)
905 page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
908 clear_highpage(page);
909 bvec_set_page(&rq->special_vec, page, data_len, 0);
910 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
911 return bvec_virt(&rq->special_vec);
914 static blk_status_t sd_setup_unmap_cmnd(struct scsi_cmnd *cmd)
916 struct scsi_device *sdp = cmd->device;
917 struct request *rq = scsi_cmd_to_rq(cmd);
918 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
919 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
920 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
921 unsigned int data_len = 24;
924 buf = sd_set_special_bvec(rq, data_len);
926 return BLK_STS_RESOURCE;
929 cmd->cmnd[0] = UNMAP;
932 put_unaligned_be16(6 + 16, &buf[0]);
933 put_unaligned_be16(16, &buf[2]);
934 put_unaligned_be64(lba, &buf[8]);
935 put_unaligned_be32(nr_blocks, &buf[16]);
937 cmd->allowed = sdkp->max_retries;
938 cmd->transfersize = data_len;
939 rq->timeout = SD_TIMEOUT;
941 return scsi_alloc_sgtables(cmd);
944 static void sd_config_atomic(struct scsi_disk *sdkp, struct queue_limits *lim)
946 unsigned int logical_block_size = sdkp->device->sector_size,
947 physical_block_size_sectors, max_atomic, unit_min, unit_max;
949 if ((!sdkp->max_atomic && !sdkp->max_atomic_with_boundary) ||
950 sdkp->protection_type == T10_PI_TYPE2_PROTECTION)
953 physical_block_size_sectors = sdkp->physical_block_size /
954 sdkp->device->sector_size;
956 unit_min = rounddown_pow_of_two(sdkp->atomic_granularity ?
957 sdkp->atomic_granularity :
958 physical_block_size_sectors);
961 * Only use atomic boundary when we have the odd scenario of
962 * sdkp->max_atomic == 0, which the spec does permit.
964 if (sdkp->max_atomic) {
965 max_atomic = sdkp->max_atomic;
966 unit_max = rounddown_pow_of_two(sdkp->max_atomic);
967 sdkp->use_atomic_write_boundary = 0;
969 max_atomic = sdkp->max_atomic_with_boundary;
970 unit_max = rounddown_pow_of_two(sdkp->max_atomic_boundary);
971 sdkp->use_atomic_write_boundary = 1;
975 * Ensure compliance with granularity and alignment. For now, keep it
976 * simple and just don't support atomic writes for values mismatched
977 * with max_{boundary}atomic, physical block size, and
978 * atomic_granularity itself.
980 * We're really being distrustful by checking unit_max also...
982 if (sdkp->atomic_granularity > 1) {
983 if (unit_min > 1 && unit_min % sdkp->atomic_granularity)
985 if (unit_max > 1 && unit_max % sdkp->atomic_granularity)
989 if (sdkp->atomic_alignment > 1) {
990 if (unit_min > 1 && unit_min % sdkp->atomic_alignment)
992 if (unit_max > 1 && unit_max % sdkp->atomic_alignment)
996 lim->atomic_write_hw_max = max_atomic * logical_block_size;
997 lim->atomic_write_hw_boundary = 0;
998 lim->atomic_write_hw_unit_min = unit_min * logical_block_size;
999 lim->atomic_write_hw_unit_max = unit_max * logical_block_size;
1002 static blk_status_t sd_setup_write_same16_cmnd(struct scsi_cmnd *cmd,
1005 struct scsi_device *sdp = cmd->device;
1006 struct request *rq = scsi_cmd_to_rq(cmd);
1007 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1008 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1009 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1010 u32 data_len = sdp->sector_size;
1012 if (!sd_set_special_bvec(rq, data_len))
1013 return BLK_STS_RESOURCE;
1016 cmd->cmnd[0] = WRITE_SAME_16;
1018 cmd->cmnd[1] = 0x8; /* UNMAP */
1019 put_unaligned_be64(lba, &cmd->cmnd[2]);
1020 put_unaligned_be32(nr_blocks, &cmd->cmnd[10]);
1022 cmd->allowed = sdkp->max_retries;
1023 cmd->transfersize = data_len;
1024 rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
1026 return scsi_alloc_sgtables(cmd);
1029 static blk_status_t sd_setup_write_same10_cmnd(struct scsi_cmnd *cmd,
1032 struct scsi_device *sdp = cmd->device;
1033 struct request *rq = scsi_cmd_to_rq(cmd);
1034 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1035 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1036 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1037 u32 data_len = sdp->sector_size;
1039 if (!sd_set_special_bvec(rq, data_len))
1040 return BLK_STS_RESOURCE;
1043 cmd->cmnd[0] = WRITE_SAME;
1045 cmd->cmnd[1] = 0x8; /* UNMAP */
1046 put_unaligned_be32(lba, &cmd->cmnd[2]);
1047 put_unaligned_be16(nr_blocks, &cmd->cmnd[7]);
1049 cmd->allowed = sdkp->max_retries;
1050 cmd->transfersize = data_len;
1051 rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
1053 return scsi_alloc_sgtables(cmd);
1056 static blk_status_t sd_setup_write_zeroes_cmnd(struct scsi_cmnd *cmd)
1058 struct request *rq = scsi_cmd_to_rq(cmd);
1059 struct scsi_device *sdp = cmd->device;
1060 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1061 u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1062 u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1064 if (!(rq->cmd_flags & REQ_NOUNMAP)) {
1065 switch (sdkp->zeroing_mode) {
1066 case SD_ZERO_WS16_UNMAP:
1067 return sd_setup_write_same16_cmnd(cmd, true);
1068 case SD_ZERO_WS10_UNMAP:
1069 return sd_setup_write_same10_cmnd(cmd, true);
1073 if (sdp->no_write_same) {
1074 rq->rq_flags |= RQF_QUIET;
1075 return BLK_STS_TARGET;
1078 if (sdkp->ws16 || lba > 0xffffffff || nr_blocks > 0xffff)
1079 return sd_setup_write_same16_cmnd(cmd, false);
1081 return sd_setup_write_same10_cmnd(cmd, false);
1084 static void sd_disable_write_same(struct scsi_disk *sdkp)
1086 sdkp->device->no_write_same = 1;
1087 sdkp->max_ws_blocks = 0;
1088 blk_queue_disable_write_zeroes(sdkp->disk->queue);
1091 static void sd_config_write_same(struct scsi_disk *sdkp,
1092 struct queue_limits *lim)
1094 unsigned int logical_block_size = sdkp->device->sector_size;
1096 if (sdkp->device->no_write_same) {
1097 sdkp->max_ws_blocks = 0;
1101 /* Some devices can not handle block counts above 0xffff despite
1102 * supporting WRITE SAME(16). Consequently we default to 64k
1103 * blocks per I/O unless the device explicitly advertises a
1106 if (sdkp->max_ws_blocks > SD_MAX_WS10_BLOCKS)
1107 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
1108 (u32)SD_MAX_WS16_BLOCKS);
1109 else if (sdkp->ws16 || sdkp->ws10 || sdkp->device->no_report_opcodes)
1110 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
1111 (u32)SD_MAX_WS10_BLOCKS);
1113 sdkp->device->no_write_same = 1;
1114 sdkp->max_ws_blocks = 0;
1117 if (sdkp->lbprz && sdkp->lbpws)
1118 sdkp->zeroing_mode = SD_ZERO_WS16_UNMAP;
1119 else if (sdkp->lbprz && sdkp->lbpws10)
1120 sdkp->zeroing_mode = SD_ZERO_WS10_UNMAP;
1121 else if (sdkp->max_ws_blocks)
1122 sdkp->zeroing_mode = SD_ZERO_WS;
1124 sdkp->zeroing_mode = SD_ZERO_WRITE;
1126 if (sdkp->max_ws_blocks &&
1127 sdkp->physical_block_size > logical_block_size) {
1129 * Reporting a maximum number of blocks that is not aligned
1130 * on the device physical size would cause a large write same
1131 * request to be split into physically unaligned chunks by
1132 * __blkdev_issue_write_zeroes() even if the caller of this
1133 * functions took care to align the large request. So make sure
1134 * the maximum reported is aligned to the device physical block
1135 * size. This is only an optional optimization for regular
1136 * disks, but this is mandatory to avoid failure of large write
1137 * same requests directed at sequential write required zones of
1138 * host-managed ZBC disks.
1140 sdkp->max_ws_blocks =
1141 round_down(sdkp->max_ws_blocks,
1142 bytes_to_logical(sdkp->device,
1143 sdkp->physical_block_size));
1147 lim->max_write_zeroes_sectors =
1148 sdkp->max_ws_blocks * (logical_block_size >> SECTOR_SHIFT);
1151 static blk_status_t sd_setup_flush_cmnd(struct scsi_cmnd *cmd)
1153 struct request *rq = scsi_cmd_to_rq(cmd);
1154 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1156 /* flush requests don't perform I/O, zero the S/G table */
1157 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1159 if (cmd->device->use_16_for_sync) {
1160 cmd->cmnd[0] = SYNCHRONIZE_CACHE_16;
1163 cmd->cmnd[0] = SYNCHRONIZE_CACHE;
1166 cmd->transfersize = 0;
1167 cmd->allowed = sdkp->max_retries;
1169 rq->timeout = rq->q->rq_timeout * SD_FLUSH_TIMEOUT_MULTIPLIER;
1174 * sd_group_number() - Compute the GROUP NUMBER field
1175 * @cmd: SCSI command for which to compute the value of the six-bit GROUP NUMBER
1178 * From SBC-5 r05 (https://www.t10.org/cgi-bin/ac.pl?t=f&f=sbc5r05.pdf):
1179 * 0: no relative lifetime.
1180 * 1: shortest relative lifetime.
1181 * 2: second shortest relative lifetime.
1182 * 3 - 0x3d: intermediate relative lifetimes.
1183 * 0x3e: second longest relative lifetime.
1184 * 0x3f: longest relative lifetime.
1186 static u8 sd_group_number(struct scsi_cmnd *cmd)
1188 const struct request *rq = scsi_cmd_to_rq(cmd);
1189 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1194 return min3((u32)rq->write_hint, (u32)sdkp->permanent_stream_count,
1198 static blk_status_t sd_setup_rw32_cmnd(struct scsi_cmnd *cmd, bool write,
1199 sector_t lba, unsigned int nr_blocks,
1200 unsigned char flags, unsigned int dld)
1202 cmd->cmd_len = SD_EXT_CDB_SIZE;
1203 cmd->cmnd[0] = VARIABLE_LENGTH_CMD;
1204 cmd->cmnd[6] = sd_group_number(cmd);
1205 cmd->cmnd[7] = 0x18; /* Additional CDB len */
1206 cmd->cmnd[9] = write ? WRITE_32 : READ_32;
1207 cmd->cmnd[10] = flags;
1208 cmd->cmnd[11] = dld & 0x07;
1209 put_unaligned_be64(lba, &cmd->cmnd[12]);
1210 put_unaligned_be32(lba, &cmd->cmnd[20]); /* Expected Indirect LBA */
1211 put_unaligned_be32(nr_blocks, &cmd->cmnd[28]);
1216 static blk_status_t sd_setup_rw16_cmnd(struct scsi_cmnd *cmd, bool write,
1217 sector_t lba, unsigned int nr_blocks,
1218 unsigned char flags, unsigned int dld)
1221 cmd->cmnd[0] = write ? WRITE_16 : READ_16;
1222 cmd->cmnd[1] = flags | ((dld >> 2) & 0x01);
1223 cmd->cmnd[14] = ((dld & 0x03) << 6) | sd_group_number(cmd);
1225 put_unaligned_be64(lba, &cmd->cmnd[2]);
1226 put_unaligned_be32(nr_blocks, &cmd->cmnd[10]);
1231 static blk_status_t sd_setup_rw10_cmnd(struct scsi_cmnd *cmd, bool write,
1232 sector_t lba, unsigned int nr_blocks,
1233 unsigned char flags)
1236 cmd->cmnd[0] = write ? WRITE_10 : READ_10;
1237 cmd->cmnd[1] = flags;
1238 cmd->cmnd[6] = sd_group_number(cmd);
1240 put_unaligned_be32(lba, &cmd->cmnd[2]);
1241 put_unaligned_be16(nr_blocks, &cmd->cmnd[7]);
1246 static blk_status_t sd_setup_rw6_cmnd(struct scsi_cmnd *cmd, bool write,
1247 sector_t lba, unsigned int nr_blocks,
1248 unsigned char flags)
1250 /* Avoid that 0 blocks gets translated into 256 blocks. */
1251 if (WARN_ON_ONCE(nr_blocks == 0))
1252 return BLK_STS_IOERR;
1254 if (unlikely(flags & 0x8)) {
1256 * This happens only if this drive failed 10byte rw
1257 * command with ILLEGAL_REQUEST during operation and
1258 * thus turned off use_10_for_rw.
1260 scmd_printk(KERN_ERR, cmd, "FUA write on READ/WRITE(6) drive\n");
1261 return BLK_STS_IOERR;
1265 cmd->cmnd[0] = write ? WRITE_6 : READ_6;
1266 cmd->cmnd[1] = (lba >> 16) & 0x1f;
1267 cmd->cmnd[2] = (lba >> 8) & 0xff;
1268 cmd->cmnd[3] = lba & 0xff;
1269 cmd->cmnd[4] = nr_blocks;
1276 * Check if a command has a duration limit set. If it does, and the target
1277 * device supports CDL and the feature is enabled, return the limit
1278 * descriptor index to use. Return 0 (no limit) otherwise.
1280 static int sd_cdl_dld(struct scsi_disk *sdkp, struct scsi_cmnd *scmd)
1282 struct scsi_device *sdp = sdkp->device;
1285 if (!sdp->cdl_supported || !sdp->cdl_enable)
1289 * Use "no limit" if the request ioprio does not specify a duration
1292 hint = IOPRIO_PRIO_HINT(req_get_ioprio(scsi_cmd_to_rq(scmd)));
1293 if (hint < IOPRIO_HINT_DEV_DURATION_LIMIT_1 ||
1294 hint > IOPRIO_HINT_DEV_DURATION_LIMIT_7)
1297 return (hint - IOPRIO_HINT_DEV_DURATION_LIMIT_1) + 1;
1300 static blk_status_t sd_setup_atomic_cmnd(struct scsi_cmnd *cmd,
1301 sector_t lba, unsigned int nr_blocks,
1302 bool boundary, unsigned char flags)
1305 cmd->cmnd[0] = WRITE_ATOMIC_16;
1306 cmd->cmnd[1] = flags;
1307 put_unaligned_be64(lba, &cmd->cmnd[2]);
1308 put_unaligned_be16(nr_blocks, &cmd->cmnd[12]);
1310 put_unaligned_be16(nr_blocks, &cmd->cmnd[10]);
1312 put_unaligned_be16(0, &cmd->cmnd[10]);
1313 put_unaligned_be16(nr_blocks, &cmd->cmnd[12]);
1320 static blk_status_t sd_setup_read_write_cmnd(struct scsi_cmnd *cmd)
1322 struct request *rq = scsi_cmd_to_rq(cmd);
1323 struct scsi_device *sdp = cmd->device;
1324 struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1325 sector_t lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1327 unsigned int nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1328 unsigned int mask = logical_to_sectors(sdp, 1) - 1;
1329 bool write = rq_data_dir(rq) == WRITE;
1330 unsigned char protect, fua;
1336 ret = scsi_alloc_sgtables(cmd);
1337 if (ret != BLK_STS_OK)
1340 ret = BLK_STS_IOERR;
1341 if (!scsi_device_online(sdp) || sdp->changed) {
1342 scmd_printk(KERN_ERR, cmd, "device offline or changed\n");
1346 if (blk_rq_pos(rq) + blk_rq_sectors(rq) > get_capacity(rq->q->disk)) {
1347 scmd_printk(KERN_ERR, cmd, "access beyond end of device\n");
1351 if ((blk_rq_pos(rq) & mask) || (blk_rq_sectors(rq) & mask)) {
1352 scmd_printk(KERN_ERR, cmd, "request not aligned to the logical block size\n");
1357 * Some SD card readers can't handle accesses which touch the
1358 * last one or two logical blocks. Split accesses as needed.
1360 threshold = sdkp->capacity - SD_LAST_BUGGY_SECTORS;
1362 if (unlikely(sdp->last_sector_bug && lba + nr_blocks > threshold)) {
1363 if (lba < threshold) {
1364 /* Access up to the threshold but not beyond */
1365 nr_blocks = threshold - lba;
1367 /* Access only a single logical block */
1372 fua = rq->cmd_flags & REQ_FUA ? 0x8 : 0;
1373 dix = scsi_prot_sg_count(cmd);
1374 dif = scsi_host_dif_capable(cmd->device->host, sdkp->protection_type);
1375 dld = sd_cdl_dld(sdkp, cmd);
1378 protect = sd_setup_protect_cmnd(cmd, dix, dif);
1382 if (protect && sdkp->protection_type == T10_PI_TYPE2_PROTECTION) {
1383 ret = sd_setup_rw32_cmnd(cmd, write, lba, nr_blocks,
1384 protect | fua, dld);
1385 } else if (rq->cmd_flags & REQ_ATOMIC && write) {
1386 ret = sd_setup_atomic_cmnd(cmd, lba, nr_blocks,
1387 sdkp->use_atomic_write_boundary,
1389 } else if (sdp->use_16_for_rw || (nr_blocks > 0xffff)) {
1390 ret = sd_setup_rw16_cmnd(cmd, write, lba, nr_blocks,
1391 protect | fua, dld);
1392 } else if ((nr_blocks > 0xff) || (lba > 0x1fffff) ||
1393 sdp->use_10_for_rw || protect || rq->write_hint) {
1394 ret = sd_setup_rw10_cmnd(cmd, write, lba, nr_blocks,
1397 ret = sd_setup_rw6_cmnd(cmd, write, lba, nr_blocks,
1401 if (unlikely(ret != BLK_STS_OK))
1405 * We shouldn't disconnect in the middle of a sector, so with a dumb
1406 * host adapter, it's safe to assume that we can at least transfer
1407 * this many bytes between each connect / disconnect.
1409 cmd->transfersize = sdp->sector_size;
1410 cmd->underflow = nr_blocks << 9;
1411 cmd->allowed = sdkp->max_retries;
1412 cmd->sdb.length = nr_blocks * sdp->sector_size;
1415 scmd_printk(KERN_INFO, cmd,
1416 "%s: block=%llu, count=%d\n", __func__,
1417 (unsigned long long)blk_rq_pos(rq),
1418 blk_rq_sectors(rq)));
1420 scmd_printk(KERN_INFO, cmd,
1421 "%s %d/%u 512 byte blocks.\n",
1422 write ? "writing" : "reading", nr_blocks,
1423 blk_rq_sectors(rq)));
1426 * This indicates that the command is ready from our end to be queued.
1430 scsi_free_sgtables(cmd);
1434 static blk_status_t sd_init_command(struct scsi_cmnd *cmd)
1436 struct request *rq = scsi_cmd_to_rq(cmd);
1438 switch (req_op(rq)) {
1439 case REQ_OP_DISCARD:
1440 switch (scsi_disk(rq->q->disk)->provisioning_mode) {
1442 return sd_setup_unmap_cmnd(cmd);
1444 return sd_setup_write_same16_cmnd(cmd, true);
1446 return sd_setup_write_same10_cmnd(cmd, true);
1448 return sd_setup_write_same10_cmnd(cmd, false);
1450 return BLK_STS_TARGET;
1452 case REQ_OP_WRITE_ZEROES:
1453 return sd_setup_write_zeroes_cmnd(cmd);
1455 return sd_setup_flush_cmnd(cmd);
1458 return sd_setup_read_write_cmnd(cmd);
1459 case REQ_OP_ZONE_RESET:
1460 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_RESET_WRITE_POINTER,
1462 case REQ_OP_ZONE_RESET_ALL:
1463 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_RESET_WRITE_POINTER,
1465 case REQ_OP_ZONE_OPEN:
1466 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_OPEN_ZONE, false);
1467 case REQ_OP_ZONE_CLOSE:
1468 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_CLOSE_ZONE, false);
1469 case REQ_OP_ZONE_FINISH:
1470 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_FINISH_ZONE, false);
1473 return BLK_STS_NOTSUPP;
1477 static void sd_uninit_command(struct scsi_cmnd *SCpnt)
1479 struct request *rq = scsi_cmd_to_rq(SCpnt);
1481 if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1482 mempool_free(rq->special_vec.bv_page, sd_page_pool);
1485 static bool sd_need_revalidate(struct gendisk *disk, struct scsi_disk *sdkp)
1487 if (sdkp->device->removable || sdkp->write_prot) {
1488 if (disk_check_media_change(disk))
1493 * Force a full rescan after ioctl(BLKRRPART). While the disk state has
1494 * nothing to do with partitions, BLKRRPART is used to force a full
1495 * revalidate after things like a format for historical reasons.
1497 return test_bit(GD_NEED_PART_SCAN, &disk->state);
1501 * sd_open - open a scsi disk device
1502 * @disk: disk to open
1505 * Returns 0 if successful. Returns a negated errno value in case
1508 * Note: This can be called from a user context (e.g. fsck(1) )
1509 * or from within the kernel (e.g. as a result of a mount(1) ).
1510 * In the latter case @inode and @filp carry an abridged amount
1511 * of information as noted above.
1513 * Locking: called with disk->open_mutex held.
1515 static int sd_open(struct gendisk *disk, blk_mode_t mode)
1517 struct scsi_disk *sdkp = scsi_disk(disk);
1518 struct scsi_device *sdev = sdkp->device;
1521 if (scsi_device_get(sdev))
1524 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
1527 * If the device is in error recovery, wait until it is done.
1528 * If the device is offline, then disallow any access to it.
1531 if (!scsi_block_when_processing_errors(sdev))
1534 if (sd_need_revalidate(disk, sdkp))
1535 sd_revalidate_disk(disk);
1538 * If the drive is empty, just let the open fail.
1540 retval = -ENOMEDIUM;
1541 if (sdev->removable && !sdkp->media_present &&
1542 !(mode & BLK_OPEN_NDELAY))
1546 * If the device has the write protect tab set, have the open fail
1547 * if the user expects to be able to write to the thing.
1550 if (sdkp->write_prot && (mode & BLK_OPEN_WRITE))
1554 * It is possible that the disk changing stuff resulted in
1555 * the device being taken offline. If this is the case,
1556 * report this to the user, and don't pretend that the
1557 * open actually succeeded.
1560 if (!scsi_device_online(sdev))
1563 if ((atomic_inc_return(&sdkp->openers) == 1) && sdev->removable) {
1564 if (scsi_block_when_processing_errors(sdev))
1565 scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
1571 scsi_device_put(sdev);
1576 * sd_release - invoked when the (last) close(2) is called on this
1578 * @disk: disk to release
1582 * Note: may block (uninterruptible) if error recovery is underway
1585 * Locking: called with disk->open_mutex held.
1587 static void sd_release(struct gendisk *disk)
1589 struct scsi_disk *sdkp = scsi_disk(disk);
1590 struct scsi_device *sdev = sdkp->device;
1592 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
1594 if (atomic_dec_return(&sdkp->openers) == 0 && sdev->removable) {
1595 if (scsi_block_when_processing_errors(sdev))
1596 scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
1599 scsi_device_put(sdev);
1602 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1604 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1605 struct scsi_device *sdp = sdkp->device;
1606 struct Scsi_Host *host = sdp->host;
1607 sector_t capacity = logical_to_sectors(sdp, sdkp->capacity);
1610 /* default to most commonly used values */
1611 diskinfo[0] = 0x40; /* 1 << 6 */
1612 diskinfo[1] = 0x20; /* 1 << 5 */
1613 diskinfo[2] = capacity >> 11;
1615 /* override with calculated, extended default, or driver values */
1616 if (host->hostt->bios_param)
1617 host->hostt->bios_param(sdp, bdev, capacity, diskinfo);
1619 scsicam_bios_param(bdev, capacity, diskinfo);
1621 geo->heads = diskinfo[0];
1622 geo->sectors = diskinfo[1];
1623 geo->cylinders = diskinfo[2];
1628 * sd_ioctl - process an ioctl
1629 * @bdev: target block device
1631 * @cmd: ioctl command number
1632 * @arg: this is third argument given to ioctl(2) system call.
1633 * Often contains a pointer.
1635 * Returns 0 if successful (some ioctls return positive numbers on
1636 * success as well). Returns a negated errno value in case of error.
1638 * Note: most ioctls are forward onto the block subsystem or further
1639 * down in the scsi subsystem.
1641 static int sd_ioctl(struct block_device *bdev, blk_mode_t mode,
1642 unsigned int cmd, unsigned long arg)
1644 struct gendisk *disk = bdev->bd_disk;
1645 struct scsi_disk *sdkp = scsi_disk(disk);
1646 struct scsi_device *sdp = sdkp->device;
1647 void __user *p = (void __user *)arg;
1650 SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, "
1651 "cmd=0x%x\n", disk->disk_name, cmd));
1653 if (bdev_is_partition(bdev) && !capable(CAP_SYS_RAWIO))
1654 return -ENOIOCTLCMD;
1657 * If we are in the middle of error recovery, don't let anyone
1658 * else try and use this device. Also, if error recovery fails, it
1659 * may try and take the device offline, in which case all further
1660 * access to the device is prohibited.
1662 error = scsi_ioctl_block_when_processing_errors(sdp, cmd,
1663 (mode & BLK_OPEN_NDELAY));
1667 if (is_sed_ioctl(cmd))
1668 return sed_ioctl(sdkp->opal_dev, cmd, p);
1669 return scsi_ioctl(sdp, mode & BLK_OPEN_WRITE, cmd, p);
1672 static void set_media_not_present(struct scsi_disk *sdkp)
1674 if (sdkp->media_present)
1675 sdkp->device->changed = 1;
1677 if (sdkp->device->removable) {
1678 sdkp->media_present = 0;
1683 static int media_not_present(struct scsi_disk *sdkp,
1684 struct scsi_sense_hdr *sshdr)
1686 if (!scsi_sense_valid(sshdr))
1689 /* not invoked for commands that could return deferred errors */
1690 switch (sshdr->sense_key) {
1691 case UNIT_ATTENTION:
1693 /* medium not present */
1694 if (sshdr->asc == 0x3A) {
1695 set_media_not_present(sdkp);
1703 * sd_check_events - check media events
1704 * @disk: kernel device descriptor
1705 * @clearing: disk events currently being cleared
1707 * Returns mask of DISK_EVENT_*.
1709 * Note: this function is invoked from the block subsystem.
1711 static unsigned int sd_check_events(struct gendisk *disk, unsigned int clearing)
1713 struct scsi_disk *sdkp = disk->private_data;
1714 struct scsi_device *sdp;
1722 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_check_events\n"));
1725 * If the device is offline, don't send any commands - just pretend as
1726 * if the command failed. If the device ever comes back online, we
1727 * can deal with it then. It is only because of unrecoverable errors
1728 * that we would ever take a device offline in the first place.
1730 if (!scsi_device_online(sdp)) {
1731 set_media_not_present(sdkp);
1736 * Using TEST_UNIT_READY enables differentiation between drive with
1737 * no cartridge loaded - NOT READY, drive with changed cartridge -
1738 * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
1740 * Drives that auto spin down. eg iomega jaz 1G, will be started
1741 * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
1742 * sd_revalidate() is called.
1744 if (scsi_block_when_processing_errors(sdp)) {
1745 struct scsi_sense_hdr sshdr = { 0, };
1747 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, sdkp->max_retries,
1750 /* failed to execute TUR, assume media not present */
1751 if (retval < 0 || host_byte(retval)) {
1752 set_media_not_present(sdkp);
1756 if (media_not_present(sdkp, &sshdr))
1761 * For removable scsi disk we have to recognise the presence
1762 * of a disk in the drive.
1764 if (!sdkp->media_present)
1766 sdkp->media_present = 1;
1769 * sdp->changed is set under the following conditions:
1771 * Medium present state has changed in either direction.
1772 * Device has indicated UNIT_ATTENTION.
1774 disk_changed = sdp->changed;
1776 return disk_changed ? DISK_EVENT_MEDIA_CHANGE : 0;
1779 static int sd_sync_cache(struct scsi_disk *sdkp)
1782 struct scsi_device *sdp = sdkp->device;
1783 const int timeout = sdp->request_queue->rq_timeout
1784 * SD_FLUSH_TIMEOUT_MULTIPLIER;
1785 /* Leave the rest of the command zero to indicate flush everything. */
1786 const unsigned char cmd[16] = { sdp->use_16_for_sync ?
1787 SYNCHRONIZE_CACHE_16 : SYNCHRONIZE_CACHE };
1788 struct scsi_sense_hdr sshdr;
1789 struct scsi_failure failure_defs[] = {
1792 .result = SCMD_FAILURE_RESULT_ANY,
1796 struct scsi_failures failures = {
1797 .failure_definitions = failure_defs,
1799 const struct scsi_exec_args exec_args = {
1800 .req_flags = BLK_MQ_REQ_PM,
1802 .failures = &failures,
1805 if (!scsi_device_online(sdp))
1808 res = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, NULL, 0, timeout,
1809 sdkp->max_retries, &exec_args);
1811 sd_print_result(sdkp, "Synchronize Cache(10) failed", res);
1816 if (scsi_status_is_check_condition(res) &&
1817 scsi_sense_valid(&sshdr)) {
1818 sd_print_sense_hdr(sdkp, &sshdr);
1820 /* we need to evaluate the error return */
1821 if (sshdr.asc == 0x3a || /* medium not present */
1822 sshdr.asc == 0x20 || /* invalid command */
1823 (sshdr.asc == 0x74 && sshdr.ascq == 0x71)) /* drive is password locked */
1824 /* this is no error here */
1827 * This drive doesn't support sync and there's not much
1828 * we can do because this is called during shutdown
1829 * or suspend so just return success so those operations
1832 if (sshdr.sense_key == ILLEGAL_REQUEST)
1836 switch (host_byte(res)) {
1837 /* ignore errors due to racing a disconnection */
1838 case DID_BAD_TARGET:
1839 case DID_NO_CONNECT:
1841 /* signal the upper layer it might try again */
1845 case DID_SOFT_ERROR:
1854 static void sd_rescan(struct device *dev)
1856 struct scsi_disk *sdkp = dev_get_drvdata(dev);
1858 sd_revalidate_disk(sdkp->disk);
1861 static int sd_get_unique_id(struct gendisk *disk, u8 id[16],
1862 enum blk_unique_id type)
1864 struct scsi_device *sdev = scsi_disk(disk)->device;
1865 const struct scsi_vpd *vpd;
1866 const unsigned char *d;
1867 int ret = -ENXIO, len;
1870 vpd = rcu_dereference(sdev->vpd_pg83);
1875 for (d = vpd->data + 4; d < vpd->data + vpd->len; d += d[3] + 4) {
1876 /* we only care about designators with LU association */
1877 if (((d[1] >> 4) & 0x3) != 0x00)
1879 if ((d[1] & 0xf) != type)
1883 * Only exit early if a 16-byte descriptor was found. Otherwise
1884 * keep looking as one with more entropy might still show up.
1887 if (len != 8 && len != 12 && len != 16)
1890 memcpy(id, d + 4, len);
1899 static int sd_scsi_to_pr_err(struct scsi_sense_hdr *sshdr, int result)
1901 switch (host_byte(result)) {
1902 case DID_TRANSPORT_MARGINAL:
1903 case DID_TRANSPORT_DISRUPTED:
1905 return PR_STS_RETRY_PATH_FAILURE;
1906 case DID_NO_CONNECT:
1907 return PR_STS_PATH_FAILED;
1908 case DID_TRANSPORT_FAILFAST:
1909 return PR_STS_PATH_FAST_FAILED;
1912 switch (status_byte(result)) {
1913 case SAM_STAT_RESERVATION_CONFLICT:
1914 return PR_STS_RESERVATION_CONFLICT;
1915 case SAM_STAT_CHECK_CONDITION:
1916 if (!scsi_sense_valid(sshdr))
1917 return PR_STS_IOERR;
1919 if (sshdr->sense_key == ILLEGAL_REQUEST &&
1920 (sshdr->asc == 0x26 || sshdr->asc == 0x24))
1925 return PR_STS_IOERR;
1929 static int sd_pr_in_command(struct block_device *bdev, u8 sa,
1930 unsigned char *data, int data_len)
1932 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1933 struct scsi_device *sdev = sdkp->device;
1934 struct scsi_sense_hdr sshdr;
1935 u8 cmd[10] = { PERSISTENT_RESERVE_IN, sa };
1936 struct scsi_failure failure_defs[] = {
1938 .sense = UNIT_ATTENTION,
1939 .asc = SCMD_FAILURE_ASC_ANY,
1940 .ascq = SCMD_FAILURE_ASCQ_ANY,
1942 .result = SAM_STAT_CHECK_CONDITION,
1946 struct scsi_failures failures = {
1947 .failure_definitions = failure_defs,
1949 const struct scsi_exec_args exec_args = {
1951 .failures = &failures,
1955 put_unaligned_be16(data_len, &cmd[7]);
1957 result = scsi_execute_cmd(sdev, cmd, REQ_OP_DRV_IN, data, data_len,
1958 SD_TIMEOUT, sdkp->max_retries, &exec_args);
1959 if (scsi_status_is_check_condition(result) &&
1960 scsi_sense_valid(&sshdr)) {
1961 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
1962 scsi_print_sense_hdr(sdev, NULL, &sshdr);
1968 return sd_scsi_to_pr_err(&sshdr, result);
1971 static int sd_pr_read_keys(struct block_device *bdev, struct pr_keys *keys_info)
1973 int result, i, data_offset, num_copy_keys;
1974 u32 num_keys = keys_info->num_keys;
1975 int data_len = num_keys * 8 + 8;
1978 data = kzalloc(data_len, GFP_KERNEL);
1982 result = sd_pr_in_command(bdev, READ_KEYS, data, data_len);
1986 keys_info->generation = get_unaligned_be32(&data[0]);
1987 keys_info->num_keys = get_unaligned_be32(&data[4]) / 8;
1990 num_copy_keys = min(num_keys, keys_info->num_keys);
1992 for (i = 0; i < num_copy_keys; i++) {
1993 keys_info->keys[i] = get_unaligned_be64(&data[data_offset]);
2002 static int sd_pr_read_reservation(struct block_device *bdev,
2003 struct pr_held_reservation *rsv)
2005 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
2006 struct scsi_device *sdev = sdkp->device;
2010 result = sd_pr_in_command(bdev, READ_RESERVATION, data, sizeof(data));
2014 len = get_unaligned_be32(&data[4]);
2018 /* Make sure we have at least the key and type */
2020 sdev_printk(KERN_INFO, sdev,
2021 "READ RESERVATION failed due to short return buffer of %d bytes\n",
2026 rsv->generation = get_unaligned_be32(&data[0]);
2027 rsv->key = get_unaligned_be64(&data[8]);
2028 rsv->type = scsi_pr_type_to_block(data[21] & 0x0f);
2032 static int sd_pr_out_command(struct block_device *bdev, u8 sa, u64 key,
2033 u64 sa_key, enum scsi_pr_type type, u8 flags)
2035 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
2036 struct scsi_device *sdev = sdkp->device;
2037 struct scsi_sense_hdr sshdr;
2038 struct scsi_failure failure_defs[] = {
2040 .sense = UNIT_ATTENTION,
2041 .asc = SCMD_FAILURE_ASC_ANY,
2042 .ascq = SCMD_FAILURE_ASCQ_ANY,
2044 .result = SAM_STAT_CHECK_CONDITION,
2048 struct scsi_failures failures = {
2049 .failure_definitions = failure_defs,
2051 const struct scsi_exec_args exec_args = {
2053 .failures = &failures,
2056 u8 cmd[16] = { 0, };
2057 u8 data[24] = { 0, };
2059 cmd[0] = PERSISTENT_RESERVE_OUT;
2062 put_unaligned_be32(sizeof(data), &cmd[5]);
2064 put_unaligned_be64(key, &data[0]);
2065 put_unaligned_be64(sa_key, &data[8]);
2068 result = scsi_execute_cmd(sdev, cmd, REQ_OP_DRV_OUT, &data,
2069 sizeof(data), SD_TIMEOUT, sdkp->max_retries,
2072 if (scsi_status_is_check_condition(result) &&
2073 scsi_sense_valid(&sshdr)) {
2074 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
2075 scsi_print_sense_hdr(sdev, NULL, &sshdr);
2081 return sd_scsi_to_pr_err(&sshdr, result);
2084 static int sd_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
2087 if (flags & ~PR_FL_IGNORE_KEY)
2089 return sd_pr_out_command(bdev, (flags & PR_FL_IGNORE_KEY) ? 0x06 : 0x00,
2090 old_key, new_key, 0,
2091 (1 << 0) /* APTPL */);
2094 static int sd_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
2099 return sd_pr_out_command(bdev, 0x01, key, 0,
2100 block_pr_type_to_scsi(type), 0);
2103 static int sd_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2105 return sd_pr_out_command(bdev, 0x02, key, 0,
2106 block_pr_type_to_scsi(type), 0);
2109 static int sd_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
2110 enum pr_type type, bool abort)
2112 return sd_pr_out_command(bdev, abort ? 0x05 : 0x04, old_key, new_key,
2113 block_pr_type_to_scsi(type), 0);
2116 static int sd_pr_clear(struct block_device *bdev, u64 key)
2118 return sd_pr_out_command(bdev, 0x03, key, 0, 0, 0);
2121 static const struct pr_ops sd_pr_ops = {
2122 .pr_register = sd_pr_register,
2123 .pr_reserve = sd_pr_reserve,
2124 .pr_release = sd_pr_release,
2125 .pr_preempt = sd_pr_preempt,
2126 .pr_clear = sd_pr_clear,
2127 .pr_read_keys = sd_pr_read_keys,
2128 .pr_read_reservation = sd_pr_read_reservation,
2131 static void scsi_disk_free_disk(struct gendisk *disk)
2133 struct scsi_disk *sdkp = scsi_disk(disk);
2135 put_device(&sdkp->disk_dev);
2138 static const struct block_device_operations sd_fops = {
2139 .owner = THIS_MODULE,
2141 .release = sd_release,
2143 .getgeo = sd_getgeo,
2144 .compat_ioctl = blkdev_compat_ptr_ioctl,
2145 .check_events = sd_check_events,
2146 .unlock_native_capacity = sd_unlock_native_capacity,
2147 .report_zones = sd_zbc_report_zones,
2148 .get_unique_id = sd_get_unique_id,
2149 .free_disk = scsi_disk_free_disk,
2150 .pr_ops = &sd_pr_ops,
2154 * sd_eh_reset - reset error handling callback
2155 * @scmd: sd-issued command that has failed
2157 * This function is called by the SCSI midlayer before starting
2158 * SCSI EH. When counting medium access failures we have to be
2159 * careful to register it only only once per device and SCSI EH run;
2160 * there might be several timed out commands which will cause the
2161 * 'max_medium_access_timeouts' counter to trigger after the first
2162 * SCSI EH run already and set the device to offline.
2163 * So this function resets the internal counter before starting SCSI EH.
2165 static void sd_eh_reset(struct scsi_cmnd *scmd)
2167 struct scsi_disk *sdkp = scsi_disk(scsi_cmd_to_rq(scmd)->q->disk);
2169 /* New SCSI EH run, reset gate variable */
2170 sdkp->ignore_medium_access_errors = false;
2174 * sd_eh_action - error handling callback
2175 * @scmd: sd-issued command that has failed
2176 * @eh_disp: The recovery disposition suggested by the midlayer
2178 * This function is called by the SCSI midlayer upon completion of an
2179 * error test command (currently TEST UNIT READY). The result of sending
2180 * the eh command is passed in eh_disp. We're looking for devices that
2181 * fail medium access commands but are OK with non access commands like
2182 * test unit ready (so wrongly see the device as having a successful
2185 static int sd_eh_action(struct scsi_cmnd *scmd, int eh_disp)
2187 struct scsi_disk *sdkp = scsi_disk(scsi_cmd_to_rq(scmd)->q->disk);
2188 struct scsi_device *sdev = scmd->device;
2190 if (!scsi_device_online(sdev) ||
2191 !scsi_medium_access_command(scmd) ||
2192 host_byte(scmd->result) != DID_TIME_OUT ||
2197 * The device has timed out executing a medium access command.
2198 * However, the TEST UNIT READY command sent during error
2199 * handling completed successfully. Either the device is in the
2200 * process of recovering or has it suffered an internal failure
2201 * that prevents access to the storage medium.
2203 if (!sdkp->ignore_medium_access_errors) {
2204 sdkp->medium_access_timed_out++;
2205 sdkp->ignore_medium_access_errors = true;
2209 * If the device keeps failing read/write commands but TEST UNIT
2210 * READY always completes successfully we assume that medium
2211 * access is no longer possible and take the device offline.
2213 if (sdkp->medium_access_timed_out >= sdkp->max_medium_access_timeouts) {
2214 scmd_printk(KERN_ERR, scmd,
2215 "Medium access timeout failure. Offlining disk!\n");
2216 mutex_lock(&sdev->state_mutex);
2217 scsi_device_set_state(sdev, SDEV_OFFLINE);
2218 mutex_unlock(&sdev->state_mutex);
2226 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
2228 struct request *req = scsi_cmd_to_rq(scmd);
2229 struct scsi_device *sdev = scmd->device;
2230 unsigned int transferred, good_bytes;
2231 u64 start_lba, end_lba, bad_lba;
2234 * Some commands have a payload smaller than the device logical
2235 * block size (e.g. INQUIRY on a 4K disk).
2237 if (scsi_bufflen(scmd) <= sdev->sector_size)
2240 /* Check if we have a 'bad_lba' information */
2241 if (!scsi_get_sense_info_fld(scmd->sense_buffer,
2242 SCSI_SENSE_BUFFERSIZE,
2247 * If the bad lba was reported incorrectly, we have no idea where
2250 start_lba = sectors_to_logical(sdev, blk_rq_pos(req));
2251 end_lba = start_lba + bytes_to_logical(sdev, scsi_bufflen(scmd));
2252 if (bad_lba < start_lba || bad_lba >= end_lba)
2256 * resid is optional but mostly filled in. When it's unused,
2257 * its value is zero, so we assume the whole buffer transferred
2259 transferred = scsi_bufflen(scmd) - scsi_get_resid(scmd);
2261 /* This computation should always be done in terms of the
2262 * resolution of the device's medium.
2264 good_bytes = logical_to_bytes(sdev, bad_lba - start_lba);
2266 return min(good_bytes, transferred);
2270 * sd_done - bottom half handler: called when the lower level
2271 * driver has completed (successfully or otherwise) a scsi command.
2272 * @SCpnt: mid-level's per command structure.
2274 * Note: potentially run from within an ISR. Must not block.
2276 static int sd_done(struct scsi_cmnd *SCpnt)
2278 int result = SCpnt->result;
2279 unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
2280 unsigned int sector_size = SCpnt->device->sector_size;
2282 struct scsi_sense_hdr sshdr;
2283 struct request *req = scsi_cmd_to_rq(SCpnt);
2284 struct scsi_disk *sdkp = scsi_disk(req->q->disk);
2285 int sense_valid = 0;
2286 int sense_deferred = 0;
2288 switch (req_op(req)) {
2289 case REQ_OP_DISCARD:
2290 case REQ_OP_WRITE_ZEROES:
2291 case REQ_OP_ZONE_RESET:
2292 case REQ_OP_ZONE_RESET_ALL:
2293 case REQ_OP_ZONE_OPEN:
2294 case REQ_OP_ZONE_CLOSE:
2295 case REQ_OP_ZONE_FINISH:
2297 good_bytes = blk_rq_bytes(req);
2298 scsi_set_resid(SCpnt, 0);
2301 scsi_set_resid(SCpnt, blk_rq_bytes(req));
2306 * In case of bogus fw or device, we could end up having
2307 * an unaligned partial completion. Check this here and force
2310 resid = scsi_get_resid(SCpnt);
2311 if (resid & (sector_size - 1)) {
2312 sd_printk(KERN_INFO, sdkp,
2313 "Unaligned partial completion (resid=%u, sector_sz=%u)\n",
2314 resid, sector_size);
2315 scsi_print_command(SCpnt);
2316 resid = min(scsi_bufflen(SCpnt),
2317 round_up(resid, sector_size));
2318 scsi_set_resid(SCpnt, resid);
2323 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
2325 sense_deferred = scsi_sense_is_deferred(&sshdr);
2327 sdkp->medium_access_timed_out = 0;
2329 if (!scsi_status_is_check_condition(result) &&
2330 (!sense_valid || sense_deferred))
2333 switch (sshdr.sense_key) {
2334 case HARDWARE_ERROR:
2336 good_bytes = sd_completed_bytes(SCpnt);
2338 case RECOVERED_ERROR:
2339 good_bytes = scsi_bufflen(SCpnt);
2342 /* This indicates a false check condition, so ignore it. An
2343 * unknown amount of data was transferred so treat it as an
2347 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
2349 case ABORTED_COMMAND:
2350 if (sshdr.asc == 0x10) /* DIF: Target detected corruption */
2351 good_bytes = sd_completed_bytes(SCpnt);
2353 case ILLEGAL_REQUEST:
2354 switch (sshdr.asc) {
2355 case 0x10: /* DIX: Host detected corruption */
2356 good_bytes = sd_completed_bytes(SCpnt);
2358 case 0x20: /* INVALID COMMAND OPCODE */
2359 case 0x24: /* INVALID FIELD IN CDB */
2360 switch (SCpnt->cmnd[0]) {
2362 sd_disable_discard(sdkp);
2366 if (SCpnt->cmnd[1] & 8) { /* UNMAP */
2367 sd_disable_discard(sdkp);
2369 sd_disable_write_same(sdkp);
2370 req->rq_flags |= RQF_QUIET;
2381 if (sdkp->device->type == TYPE_ZBC)
2382 good_bytes = sd_zbc_complete(SCpnt, good_bytes, &sshdr);
2384 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
2385 "sd_done: completed %d of %d bytes\n",
2386 good_bytes, scsi_bufflen(SCpnt)));
2392 * spinup disk - called only in sd_revalidate_disk()
2395 sd_spinup_disk(struct scsi_disk *sdkp)
2397 static const u8 cmd[10] = { TEST_UNIT_READY };
2398 unsigned long spintime_expire = 0;
2399 int spintime, sense_valid = 0;
2400 unsigned int the_result;
2401 struct scsi_sense_hdr sshdr;
2402 struct scsi_failure failure_defs[] = {
2403 /* Do not retry Medium Not Present */
2405 .sense = UNIT_ATTENTION,
2407 .ascq = SCMD_FAILURE_ASCQ_ANY,
2408 .result = SAM_STAT_CHECK_CONDITION,
2413 .ascq = SCMD_FAILURE_ASCQ_ANY,
2414 .result = SAM_STAT_CHECK_CONDITION,
2416 /* Retry when scsi_status_is_good would return false 3 times */
2418 .result = SCMD_FAILURE_STAT_ANY,
2423 struct scsi_failures failures = {
2424 .failure_definitions = failure_defs,
2426 const struct scsi_exec_args exec_args = {
2428 .failures = &failures,
2433 /* Spin up drives, as required. Only do this at boot time */
2434 /* Spinup needs to be done for module loads too. */
2436 bool media_was_present = sdkp->media_present;
2438 scsi_failures_reset_retries(&failures);
2440 the_result = scsi_execute_cmd(sdkp->device, cmd, REQ_OP_DRV_IN,
2441 NULL, 0, SD_TIMEOUT,
2442 sdkp->max_retries, &exec_args);
2445 if (the_result > 0) {
2447 * If the drive has indicated to us that it doesn't
2448 * have any media in it, don't bother with any more
2451 if (media_not_present(sdkp, &sshdr)) {
2452 if (media_was_present)
2453 sd_printk(KERN_NOTICE, sdkp,
2454 "Media removed, stopped polling\n");
2457 sense_valid = scsi_sense_valid(&sshdr);
2460 if (!scsi_status_is_check_condition(the_result)) {
2461 /* no sense, TUR either succeeded or failed
2462 * with a status error */
2463 if(!spintime && !scsi_status_is_good(the_result)) {
2464 sd_print_result(sdkp, "Test Unit Ready failed",
2471 * The device does not want the automatic start to be issued.
2473 if (sdkp->device->no_start_on_add)
2476 if (sense_valid && sshdr.sense_key == NOT_READY) {
2477 if (sshdr.asc == 4 && sshdr.ascq == 3)
2478 break; /* manual intervention required */
2479 if (sshdr.asc == 4 && sshdr.ascq == 0xb)
2480 break; /* standby */
2481 if (sshdr.asc == 4 && sshdr.ascq == 0xc)
2482 break; /* unavailable */
2483 if (sshdr.asc == 4 && sshdr.ascq == 0x1b)
2484 break; /* sanitize in progress */
2485 if (sshdr.asc == 4 && sshdr.ascq == 0x24)
2486 break; /* depopulation in progress */
2487 if (sshdr.asc == 4 && sshdr.ascq == 0x25)
2488 break; /* depopulation restoration in progress */
2490 * Issue command to spin up drive when not ready
2493 /* Return immediately and start spin cycle */
2494 const u8 start_cmd[10] = {
2497 [4] = sdkp->device->start_stop_pwr_cond ?
2501 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
2502 scsi_execute_cmd(sdkp->device, start_cmd,
2503 REQ_OP_DRV_IN, NULL, 0,
2504 SD_TIMEOUT, sdkp->max_retries,
2506 spintime_expire = jiffies + 100 * HZ;
2509 /* Wait 1 second for next try */
2511 printk(KERN_CONT ".");
2514 * Wait for USB flash devices with slow firmware.
2515 * Yes, this sense key/ASC combination shouldn't
2516 * occur here. It's characteristic of these devices.
2518 } else if (sense_valid &&
2519 sshdr.sense_key == UNIT_ATTENTION &&
2520 sshdr.asc == 0x28) {
2522 spintime_expire = jiffies + 5 * HZ;
2525 /* Wait 1 second for next try */
2528 /* we don't understand the sense code, so it's
2529 * probably pointless to loop */
2531 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
2532 sd_print_sense_hdr(sdkp, &sshdr);
2537 } while (spintime && time_before_eq(jiffies, spintime_expire));
2540 if (scsi_status_is_good(the_result))
2541 printk(KERN_CONT "ready\n");
2543 printk(KERN_CONT "not responding...\n");
2548 * Determine whether disk supports Data Integrity Field.
2550 static int sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
2552 struct scsi_device *sdp = sdkp->device;
2555 if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0) {
2556 sdkp->protection_type = 0;
2560 type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
2562 if (type > T10_PI_TYPE3_PROTECTION) {
2563 sd_printk(KERN_ERR, sdkp, "formatted with unsupported" \
2564 " protection type %u. Disabling disk!\n",
2566 sdkp->protection_type = 0;
2570 sdkp->protection_type = type;
2575 static void sd_config_protection(struct scsi_disk *sdkp,
2576 struct queue_limits *lim)
2578 struct scsi_device *sdp = sdkp->device;
2580 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY))
2581 sd_dif_config_host(sdkp, lim);
2583 if (!sdkp->protection_type)
2586 if (!scsi_host_dif_capable(sdp->host, sdkp->protection_type)) {
2587 sd_first_printk(KERN_NOTICE, sdkp,
2588 "Disabling DIF Type %u protection\n",
2589 sdkp->protection_type);
2590 sdkp->protection_type = 0;
2593 sd_first_printk(KERN_NOTICE, sdkp, "Enabling DIF Type %u protection\n",
2594 sdkp->protection_type);
2597 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
2598 struct scsi_sense_hdr *sshdr, int sense_valid,
2602 sd_print_sense_hdr(sdkp, sshdr);
2604 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
2607 * Set dirty bit for removable devices if not ready -
2608 * sometimes drives will not report this properly.
2610 if (sdp->removable &&
2611 sense_valid && sshdr->sense_key == NOT_READY)
2612 set_media_not_present(sdkp);
2615 * We used to set media_present to 0 here to indicate no media
2616 * in the drive, but some drives fail read capacity even with
2617 * media present, so we can't do that.
2619 sdkp->capacity = 0; /* unknown mapped to zero - as usual */
2623 #if RC16_LEN > SD_BUF_SIZE
2624 #error RC16_LEN must not be more than SD_BUF_SIZE
2627 #define READ_CAPACITY_RETRIES_ON_RESET 10
2629 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
2630 struct queue_limits *lim, unsigned char *buffer)
2632 unsigned char cmd[16];
2633 struct scsi_sense_hdr sshdr;
2634 const struct scsi_exec_args exec_args = {
2637 int sense_valid = 0;
2639 int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2640 unsigned int alignment;
2641 unsigned long long lba;
2642 unsigned sector_size;
2644 if (sdp->no_read_capacity_16)
2649 cmd[0] = SERVICE_ACTION_IN_16;
2650 cmd[1] = SAI_READ_CAPACITY_16;
2652 memset(buffer, 0, RC16_LEN);
2654 the_result = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN,
2655 buffer, RC16_LEN, SD_TIMEOUT,
2656 sdkp->max_retries, &exec_args);
2657 if (the_result > 0) {
2658 if (media_not_present(sdkp, &sshdr))
2661 sense_valid = scsi_sense_valid(&sshdr);
2663 sshdr.sense_key == ILLEGAL_REQUEST &&
2664 (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
2666 /* Invalid Command Operation Code or
2667 * Invalid Field in CDB, just retry
2668 * silently with RC10 */
2671 sshdr.sense_key == UNIT_ATTENTION &&
2672 sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2673 /* Device reset might occur several times,
2674 * give it one more chance */
2675 if (--reset_retries > 0)
2680 } while (the_result && retries);
2683 sd_print_result(sdkp, "Read Capacity(16) failed", the_result);
2684 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2688 sector_size = get_unaligned_be32(&buffer[8]);
2689 lba = get_unaligned_be64(&buffer[0]);
2691 if (sd_read_protection_type(sdkp, buffer) < 0) {
2696 /* Logical blocks per physical block exponent */
2697 sdkp->physical_block_size = (1 << (buffer[13] & 0xf)) * sector_size;
2700 sdkp->rc_basis = (buffer[12] >> 4) & 0x3;
2702 /* Lowest aligned logical block */
2703 alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
2704 lim->alignment_offset = alignment;
2705 if (alignment && sdkp->first_scan)
2706 sd_printk(KERN_NOTICE, sdkp,
2707 "physical block alignment offset: %u\n", alignment);
2709 if (buffer[14] & 0x80) { /* LBPME */
2712 if (buffer[14] & 0x40) /* LBPRZ */
2716 sdkp->capacity = lba + 1;
2720 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
2721 unsigned char *buffer)
2723 static const u8 cmd[10] = { READ_CAPACITY };
2724 struct scsi_sense_hdr sshdr;
2725 struct scsi_failure failure_defs[] = {
2726 /* Do not retry Medium Not Present */
2728 .sense = UNIT_ATTENTION,
2730 .result = SAM_STAT_CHECK_CONDITION,
2735 .result = SAM_STAT_CHECK_CONDITION,
2737 /* Device reset might occur several times so retry a lot */
2739 .sense = UNIT_ATTENTION,
2741 .allowed = READ_CAPACITY_RETRIES_ON_RESET,
2742 .result = SAM_STAT_CHECK_CONDITION,
2744 /* Any other error not listed above retry 3 times */
2746 .result = SCMD_FAILURE_RESULT_ANY,
2751 struct scsi_failures failures = {
2752 .failure_definitions = failure_defs,
2754 const struct scsi_exec_args exec_args = {
2756 .failures = &failures,
2758 int sense_valid = 0;
2761 unsigned sector_size;
2763 memset(buffer, 0, 8);
2765 the_result = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, buffer,
2766 8, SD_TIMEOUT, sdkp->max_retries,
2769 if (the_result > 0) {
2770 sense_valid = scsi_sense_valid(&sshdr);
2772 if (media_not_present(sdkp, &sshdr))
2777 sd_print_result(sdkp, "Read Capacity(10) failed", the_result);
2778 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2782 sector_size = get_unaligned_be32(&buffer[4]);
2783 lba = get_unaligned_be32(&buffer[0]);
2785 if (sdp->no_read_capacity_16 && (lba == 0xffffffff)) {
2786 /* Some buggy (usb cardreader) devices return an lba of
2787 0xffffffff when the want to report a size of 0 (with
2788 which they really mean no media is present) */
2790 sdkp->physical_block_size = sector_size;
2794 sdkp->capacity = lba + 1;
2795 sdkp->physical_block_size = sector_size;
2799 static int sd_try_rc16_first(struct scsi_device *sdp)
2801 if (sdp->host->max_cmd_len < 16)
2803 if (sdp->try_rc_10_first)
2805 if (sdp->scsi_level > SCSI_SPC_2)
2807 if (scsi_device_protection(sdp))
2813 * read disk capacity
2816 sd_read_capacity(struct scsi_disk *sdkp, struct queue_limits *lim,
2817 unsigned char *buffer)
2820 struct scsi_device *sdp = sdkp->device;
2822 if (sd_try_rc16_first(sdp)) {
2823 sector_size = read_capacity_16(sdkp, sdp, lim, buffer);
2824 if (sector_size == -EOVERFLOW)
2826 if (sector_size == -ENODEV)
2828 if (sector_size < 0)
2829 sector_size = read_capacity_10(sdkp, sdp, buffer);
2830 if (sector_size < 0)
2833 sector_size = read_capacity_10(sdkp, sdp, buffer);
2834 if (sector_size == -EOVERFLOW)
2836 if (sector_size < 0)
2838 if ((sizeof(sdkp->capacity) > 4) &&
2839 (sdkp->capacity > 0xffffffffULL)) {
2840 int old_sector_size = sector_size;
2841 sd_printk(KERN_NOTICE, sdkp, "Very big device. "
2842 "Trying to use READ CAPACITY(16).\n");
2843 sector_size = read_capacity_16(sdkp, sdp, lim, buffer);
2844 if (sector_size < 0) {
2845 sd_printk(KERN_NOTICE, sdkp,
2846 "Using 0xffffffff as device size\n");
2847 sdkp->capacity = 1 + (sector_t) 0xffffffff;
2848 sector_size = old_sector_size;
2851 /* Remember that READ CAPACITY(16) succeeded */
2852 sdp->try_rc_10_first = 0;
2856 /* Some devices are known to return the total number of blocks,
2857 * not the highest block number. Some devices have versions
2858 * which do this and others which do not. Some devices we might
2859 * suspect of doing this but we don't know for certain.
2861 * If we know the reported capacity is wrong, decrement it. If
2862 * we can only guess, then assume the number of blocks is even
2863 * (usually true but not always) and err on the side of lowering
2866 if (sdp->fix_capacity ||
2867 (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
2868 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
2869 "from its reported value: %llu\n",
2870 (unsigned long long) sdkp->capacity);
2875 if (sector_size == 0) {
2877 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
2881 if (sector_size != 512 &&
2882 sector_size != 1024 &&
2883 sector_size != 2048 &&
2884 sector_size != 4096) {
2885 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
2888 * The user might want to re-format the drive with
2889 * a supported sectorsize. Once this happens, it
2890 * would be relatively trivial to set the thing up.
2891 * For this reason, we leave the thing in the table.
2895 * set a bogus sector size so the normal read/write
2896 * logic in the block layer will eventually refuse any
2897 * request on this device without tripping over power
2898 * of two sector size assumptions
2902 lim->logical_block_size = sector_size;
2903 lim->physical_block_size = sdkp->physical_block_size;
2904 sdkp->device->sector_size = sector_size;
2906 if (sdkp->capacity > 0xffffffff)
2907 sdp->use_16_for_rw = 1;
2912 * Print disk capacity
2915 sd_print_capacity(struct scsi_disk *sdkp,
2916 sector_t old_capacity)
2918 int sector_size = sdkp->device->sector_size;
2919 char cap_str_2[10], cap_str_10[10];
2921 if (!sdkp->first_scan && old_capacity == sdkp->capacity)
2924 string_get_size(sdkp->capacity, sector_size,
2925 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
2926 string_get_size(sdkp->capacity, sector_size,
2927 STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
2929 sd_printk(KERN_NOTICE, sdkp,
2930 "%llu %d-byte logical blocks: (%s/%s)\n",
2931 (unsigned long long)sdkp->capacity,
2932 sector_size, cap_str_10, cap_str_2);
2934 if (sdkp->physical_block_size != sector_size)
2935 sd_printk(KERN_NOTICE, sdkp,
2936 "%u-byte physical blocks\n",
2937 sdkp->physical_block_size);
2940 /* called with buffer of length 512 */
2942 sd_do_mode_sense(struct scsi_disk *sdkp, int dbd, int modepage,
2943 unsigned char *buffer, int len, struct scsi_mode_data *data,
2944 struct scsi_sense_hdr *sshdr)
2947 * If we must use MODE SENSE(10), make sure that the buffer length
2948 * is at least 8 bytes so that the mode sense header fits.
2950 if (sdkp->device->use_10_for_ms && len < 8)
2953 return scsi_mode_sense(sdkp->device, dbd, modepage, 0, buffer, len,
2954 SD_TIMEOUT, sdkp->max_retries, data, sshdr);
2958 * read write protect setting, if possible - called only in sd_revalidate_disk()
2959 * called with buffer of length SD_BUF_SIZE
2962 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
2965 struct scsi_device *sdp = sdkp->device;
2966 struct scsi_mode_data data;
2967 int old_wp = sdkp->write_prot;
2969 set_disk_ro(sdkp->disk, 0);
2970 if (sdp->skip_ms_page_3f) {
2971 sd_first_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
2975 if (sdp->use_192_bytes_for_3f) {
2976 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 192, &data, NULL);
2979 * First attempt: ask for all pages (0x3F), but only 4 bytes.
2980 * We have to start carefully: some devices hang if we ask
2981 * for more than is available.
2983 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 4, &data, NULL);
2986 * Second attempt: ask for page 0 When only page 0 is
2987 * implemented, a request for page 3F may return Sense Key
2988 * 5: Illegal Request, Sense Code 24: Invalid field in
2992 res = sd_do_mode_sense(sdkp, 0, 0, buffer, 4, &data, NULL);
2995 * Third attempt: ask 255 bytes, as we did earlier.
2998 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 255,
3003 sd_first_printk(KERN_WARNING, sdkp,
3004 "Test WP failed, assume Write Enabled\n");
3006 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
3007 set_disk_ro(sdkp->disk, sdkp->write_prot);
3008 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
3009 sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
3010 sdkp->write_prot ? "on" : "off");
3011 sd_printk(KERN_DEBUG, sdkp, "Mode Sense: %4ph\n", buffer);
3017 * sd_read_cache_type - called only from sd_revalidate_disk()
3018 * called with buffer of length SD_BUF_SIZE
3021 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
3024 struct scsi_device *sdp = sdkp->device;
3029 struct scsi_mode_data data;
3030 struct scsi_sense_hdr sshdr;
3031 int old_wce = sdkp->WCE;
3032 int old_rcd = sdkp->RCD;
3033 int old_dpofua = sdkp->DPOFUA;
3036 if (sdkp->cache_override)
3040 if (sdp->skip_ms_page_8) {
3041 if (sdp->type == TYPE_RBC)
3044 if (sdp->skip_ms_page_3f)
3047 if (sdp->use_192_bytes_for_3f)
3051 } else if (sdp->type == TYPE_RBC) {
3059 /* cautiously ask */
3060 res = sd_do_mode_sense(sdkp, dbd, modepage, buffer, first_len,
3066 if (!data.header_length) {
3069 sd_first_printk(KERN_ERR, sdkp,
3070 "Missing header in MODE_SENSE response\n");
3073 /* that went OK, now ask for the proper length */
3077 * We're only interested in the first three bytes, actually.
3078 * But the data cache page is defined for the first 20.
3082 else if (len > SD_BUF_SIZE) {
3083 sd_first_printk(KERN_NOTICE, sdkp, "Truncating mode parameter "
3084 "data from %d to %d bytes\n", len, SD_BUF_SIZE);
3087 if (modepage == 0x3F && sdp->use_192_bytes_for_3f)
3091 if (len > first_len)
3092 res = sd_do_mode_sense(sdkp, dbd, modepage, buffer, len,
3096 int offset = data.header_length + data.block_descriptor_length;
3098 while (offset < len) {
3099 u8 page_code = buffer[offset] & 0x3F;
3100 u8 spf = buffer[offset] & 0x40;
3102 if (page_code == 8 || page_code == 6) {
3103 /* We're interested only in the first 3 bytes.
3105 if (len - offset <= 2) {
3106 sd_first_printk(KERN_ERR, sdkp,
3107 "Incomplete mode parameter "
3111 modepage = page_code;
3115 /* Go to the next page */
3116 if (spf && len - offset > 3)
3117 offset += 4 + (buffer[offset+2] << 8) +
3119 else if (!spf && len - offset > 1)
3120 offset += 2 + buffer[offset+1];
3122 sd_first_printk(KERN_ERR, sdkp,
3124 "parameter data\n");
3130 sd_first_printk(KERN_WARNING, sdkp,
3131 "No Caching mode page found\n");
3135 if (modepage == 8) {
3136 sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
3137 sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
3139 sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
3143 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
3144 if (sdp->broken_fua) {
3145 sd_first_printk(KERN_NOTICE, sdkp, "Disabling FUA\n");
3147 } else if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw &&
3148 !sdkp->device->use_16_for_rw) {
3149 sd_first_printk(KERN_NOTICE, sdkp,
3150 "Uses READ/WRITE(6), disabling FUA\n");
3154 /* No cache flush allowed for write protected devices */
3155 if (sdkp->WCE && sdkp->write_prot)
3158 if (sdkp->first_scan || old_wce != sdkp->WCE ||
3159 old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
3160 sd_printk(KERN_NOTICE, sdkp,
3161 "Write cache: %s, read cache: %s, %s\n",
3162 sdkp->WCE ? "enabled" : "disabled",
3163 sdkp->RCD ? "disabled" : "enabled",
3164 sdkp->DPOFUA ? "supports DPO and FUA"
3165 : "doesn't support DPO or FUA");
3171 if (res == -EIO && scsi_sense_valid(&sshdr) &&
3172 sshdr.sense_key == ILLEGAL_REQUEST &&
3173 sshdr.asc == 0x24 && sshdr.ascq == 0x0)
3174 /* Invalid field in CDB */
3175 sd_first_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
3177 sd_first_printk(KERN_ERR, sdkp,
3178 "Asking for cache data failed\n");
3181 if (sdp->wce_default_on) {
3182 sd_first_printk(KERN_NOTICE, sdkp,
3183 "Assuming drive cache: write back\n");
3186 sd_first_printk(KERN_WARNING, sdkp,
3187 "Assuming drive cache: write through\n");
3194 static bool sd_is_perm_stream(struct scsi_disk *sdkp, unsigned int stream_id)
3196 u8 cdb[16] = { SERVICE_ACTION_IN_16, SAI_GET_STREAM_STATUS };
3198 struct scsi_stream_status_header h;
3199 struct scsi_stream_status s;
3201 struct scsi_device *sdev = sdkp->device;
3202 struct scsi_sense_hdr sshdr;
3203 const struct scsi_exec_args exec_args = {
3208 put_unaligned_be16(stream_id, &cdb[4]);
3209 put_unaligned_be32(sizeof(buf), &cdb[10]);
3211 res = scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, &buf, sizeof(buf),
3212 SD_TIMEOUT, sdkp->max_retries, &exec_args);
3215 if (scsi_status_is_check_condition(res) && scsi_sense_valid(&sshdr))
3216 sd_print_sense_hdr(sdkp, &sshdr);
3219 if (get_unaligned_be32(&buf.h.len) < sizeof(struct scsi_stream_status))
3221 return buf.h.stream_status[0].perm;
3224 static void sd_read_io_hints(struct scsi_disk *sdkp, unsigned char *buffer)
3226 struct scsi_device *sdp = sdkp->device;
3227 const struct scsi_io_group_descriptor *desc, *start, *end;
3228 u16 permanent_stream_count_old;
3229 struct scsi_sense_hdr sshdr;
3230 struct scsi_mode_data data;
3233 if (sdp->sdev_bflags & BLIST_SKIP_IO_HINTS)
3236 res = scsi_mode_sense(sdp, /*dbd=*/0x8, /*modepage=*/0x0a,
3237 /*subpage=*/0x05, buffer, SD_BUF_SIZE, SD_TIMEOUT,
3238 sdkp->max_retries, &data, &sshdr);
3241 start = (void *)buffer + data.header_length + 16;
3242 end = (void *)buffer + ALIGN_DOWN(data.header_length + data.length,
3245 * From "SBC-5 Constrained Streams with Data Lifetimes": Device severs
3246 * should assign the lowest numbered stream identifiers to permanent
3249 for (desc = start; desc < end; desc++)
3250 if (!desc->st_enble || !sd_is_perm_stream(sdkp, desc - start))
3252 permanent_stream_count_old = sdkp->permanent_stream_count;
3253 sdkp->permanent_stream_count = desc - start;
3254 if (sdkp->rscs && sdkp->permanent_stream_count < 2)
3255 sd_printk(KERN_INFO, sdkp,
3256 "Unexpected: RSCS has been set and the permanent stream count is %u\n",
3257 sdkp->permanent_stream_count);
3258 else if (sdkp->permanent_stream_count != permanent_stream_count_old)
3259 sd_printk(KERN_INFO, sdkp, "permanent stream count = %d\n",
3260 sdkp->permanent_stream_count);
3264 * The ATO bit indicates whether the DIF application tag is available
3265 * for use by the operating system.
3267 static void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
3270 struct scsi_device *sdp = sdkp->device;
3271 struct scsi_mode_data data;
3272 struct scsi_sense_hdr sshdr;
3274 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
3277 if (sdkp->protection_type == 0)
3280 res = scsi_mode_sense(sdp, 1, 0x0a, 0, buffer, 36, SD_TIMEOUT,
3281 sdkp->max_retries, &data, &sshdr);
3283 if (res < 0 || !data.header_length ||
3285 sd_first_printk(KERN_WARNING, sdkp,
3286 "getting Control mode page failed, assume no ATO\n");
3288 if (res == -EIO && scsi_sense_valid(&sshdr))
3289 sd_print_sense_hdr(sdkp, &sshdr);
3294 offset = data.header_length + data.block_descriptor_length;
3296 if ((buffer[offset] & 0x3f) != 0x0a) {
3297 sd_first_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
3301 if ((buffer[offset + 5] & 0x80) == 0)
3309 static unsigned int sd_discard_mode(struct scsi_disk *sdkp)
3311 if (!sdkp->lbpvpd) {
3312 /* LBP VPD page not provided */
3313 if (sdkp->max_unmap_blocks)
3314 return SD_LBP_UNMAP;
3318 /* LBP VPD page tells us what to use */
3319 if (sdkp->lbpu && sdkp->max_unmap_blocks)
3320 return SD_LBP_UNMAP;
3325 return SD_LBP_DISABLE;
3329 * Query disk device for preferred I/O sizes.
3331 static void sd_read_block_limits(struct scsi_disk *sdkp,
3332 struct queue_limits *lim)
3334 struct scsi_vpd *vpd;
3338 vpd = rcu_dereference(sdkp->device->vpd_pgb0);
3339 if (!vpd || vpd->len < 16)
3342 sdkp->min_xfer_blocks = get_unaligned_be16(&vpd->data[6]);
3343 sdkp->max_xfer_blocks = get_unaligned_be32(&vpd->data[8]);
3344 sdkp->opt_xfer_blocks = get_unaligned_be32(&vpd->data[12]);
3346 if (vpd->len >= 64) {
3347 unsigned int lba_count, desc_count;
3349 sdkp->max_ws_blocks = (u32)get_unaligned_be64(&vpd->data[36]);
3354 lba_count = get_unaligned_be32(&vpd->data[20]);
3355 desc_count = get_unaligned_be32(&vpd->data[24]);
3357 if (lba_count && desc_count)
3358 sdkp->max_unmap_blocks = lba_count;
3360 sdkp->unmap_granularity = get_unaligned_be32(&vpd->data[28]);
3362 if (vpd->data[32] & 0x80)
3363 sdkp->unmap_alignment =
3364 get_unaligned_be32(&vpd->data[32]) & ~(1 << 31);
3367 sdkp->max_atomic = get_unaligned_be32(&vpd->data[44]);
3368 sdkp->atomic_alignment = get_unaligned_be32(&vpd->data[48]);
3369 sdkp->atomic_granularity = get_unaligned_be32(&vpd->data[52]);
3370 sdkp->max_atomic_with_boundary = get_unaligned_be32(&vpd->data[56]);
3371 sdkp->max_atomic_boundary = get_unaligned_be32(&vpd->data[60]);
3373 sd_config_atomic(sdkp, lim);
3380 /* Parse the Block Limits Extension VPD page (0xb7) */
3381 static void sd_read_block_limits_ext(struct scsi_disk *sdkp)
3383 struct scsi_vpd *vpd;
3386 vpd = rcu_dereference(sdkp->device->vpd_pgb7);
3387 if (vpd && vpd->len >= 2)
3388 sdkp->rscs = vpd->data[5] & 1;
3392 /* Query block device characteristics */
3393 static void sd_read_block_characteristics(struct scsi_disk *sdkp,
3394 struct queue_limits *lim)
3396 struct scsi_vpd *vpd;
3400 vpd = rcu_dereference(sdkp->device->vpd_pgb1);
3402 if (!vpd || vpd->len < 8) {
3407 rot = get_unaligned_be16(&vpd->data[4]);
3408 sdkp->zoned = (vpd->data[8] >> 4) & 3;
3412 lim->features &= ~(BLK_FEAT_ROTATIONAL | BLK_FEAT_ADD_RANDOM);
3414 if (!sdkp->first_scan)
3417 if (sdkp->device->type == TYPE_ZBC)
3418 sd_printk(KERN_NOTICE, sdkp, "Host-managed zoned block device\n");
3419 else if (sdkp->zoned == 1)
3420 sd_printk(KERN_NOTICE, sdkp, "Host-aware SMR disk used as regular disk\n");
3421 else if (sdkp->zoned == 2)
3422 sd_printk(KERN_NOTICE, sdkp, "Drive-managed SMR disk\n");
3426 * sd_read_block_provisioning - Query provisioning VPD page
3427 * @sdkp: disk to query
3429 static void sd_read_block_provisioning(struct scsi_disk *sdkp)
3431 struct scsi_vpd *vpd;
3433 if (sdkp->lbpme == 0)
3437 vpd = rcu_dereference(sdkp->device->vpd_pgb2);
3439 if (!vpd || vpd->len < 8) {
3445 sdkp->lbpu = (vpd->data[5] >> 7) & 1; /* UNMAP */
3446 sdkp->lbpws = (vpd->data[5] >> 6) & 1; /* WRITE SAME(16) w/ UNMAP */
3447 sdkp->lbpws10 = (vpd->data[5] >> 5) & 1; /* WRITE SAME(10) w/ UNMAP */
3451 static void sd_read_write_same(struct scsi_disk *sdkp, unsigned char *buffer)
3453 struct scsi_device *sdev = sdkp->device;
3455 if (sdev->host->no_write_same) {
3456 sdev->no_write_same = 1;
3461 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, INQUIRY, 0) < 0) {
3462 struct scsi_vpd *vpd;
3464 sdev->no_report_opcodes = 1;
3466 /* Disable WRITE SAME if REPORT SUPPORTED OPERATION
3467 * CODES is unsupported and the device has an ATA
3468 * Information VPD page (SAT).
3471 vpd = rcu_dereference(sdev->vpd_pg89);
3473 sdev->no_write_same = 1;
3477 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME_16, 0) == 1)
3480 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME, 0) == 1)
3484 static void sd_read_security(struct scsi_disk *sdkp, unsigned char *buffer)
3486 struct scsi_device *sdev = sdkp->device;
3488 if (!sdev->security_supported)
3491 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3492 SECURITY_PROTOCOL_IN, 0) == 1 &&
3493 scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3494 SECURITY_PROTOCOL_OUT, 0) == 1)
3498 static inline sector_t sd64_to_sectors(struct scsi_disk *sdkp, u8 *buf)
3500 return logical_to_sectors(sdkp->device, get_unaligned_be64(buf));
3504 * sd_read_cpr - Query concurrent positioning ranges
3505 * @sdkp: disk to query
3507 static void sd_read_cpr(struct scsi_disk *sdkp)
3509 struct blk_independent_access_ranges *iars = NULL;
3510 unsigned char *buffer = NULL;
3511 unsigned int nr_cpr = 0;
3512 int i, vpd_len, buf_len = SD_BUF_SIZE;
3516 * We need to have the capacity set first for the block layer to be
3517 * able to check the ranges.
3519 if (sdkp->first_scan)
3522 if (!sdkp->capacity)
3526 * Concurrent Positioning Ranges VPD: there can be at most 256 ranges,
3527 * leading to a maximum page size of 64 + 256*32 bytes.
3529 buf_len = 64 + 256*32;
3530 buffer = kmalloc(buf_len, GFP_KERNEL);
3531 if (!buffer || scsi_get_vpd_page(sdkp->device, 0xb9, buffer, buf_len))
3534 /* We must have at least a 64B header and one 32B range descriptor */
3535 vpd_len = get_unaligned_be16(&buffer[2]) + 4;
3536 if (vpd_len > buf_len || vpd_len < 64 + 32 || (vpd_len & 31)) {
3537 sd_printk(KERN_ERR, sdkp,
3538 "Invalid Concurrent Positioning Ranges VPD page\n");
3542 nr_cpr = (vpd_len - 64) / 32;
3548 iars = disk_alloc_independent_access_ranges(sdkp->disk, nr_cpr);
3555 for (i = 0; i < nr_cpr; i++, desc += 32) {
3557 sd_printk(KERN_ERR, sdkp,
3558 "Invalid Concurrent Positioning Range number\n");
3563 iars->ia_range[i].sector = sd64_to_sectors(sdkp, desc + 8);
3564 iars->ia_range[i].nr_sectors = sd64_to_sectors(sdkp, desc + 16);
3568 disk_set_independent_access_ranges(sdkp->disk, iars);
3569 if (nr_cpr && sdkp->nr_actuators != nr_cpr) {
3570 sd_printk(KERN_NOTICE, sdkp,
3571 "%u concurrent positioning ranges\n", nr_cpr);
3572 sdkp->nr_actuators = nr_cpr;
3578 static bool sd_validate_min_xfer_size(struct scsi_disk *sdkp)
3580 struct scsi_device *sdp = sdkp->device;
3581 unsigned int min_xfer_bytes =
3582 logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3584 if (sdkp->min_xfer_blocks == 0)
3587 if (min_xfer_bytes & (sdkp->physical_block_size - 1)) {
3588 sd_first_printk(KERN_WARNING, sdkp,
3589 "Preferred minimum I/O size %u bytes not a " \
3590 "multiple of physical block size (%u bytes)\n",
3591 min_xfer_bytes, sdkp->physical_block_size);
3592 sdkp->min_xfer_blocks = 0;
3596 sd_first_printk(KERN_INFO, sdkp, "Preferred minimum I/O size %u bytes\n",
3602 * Determine the device's preferred I/O size for reads and writes
3603 * unless the reported value is unreasonably small, large, not a
3604 * multiple of the physical block size, or simply garbage.
3606 static bool sd_validate_opt_xfer_size(struct scsi_disk *sdkp,
3607 unsigned int dev_max)
3609 struct scsi_device *sdp = sdkp->device;
3610 unsigned int opt_xfer_bytes =
3611 logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
3612 unsigned int min_xfer_bytes =
3613 logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3615 if (sdkp->opt_xfer_blocks == 0)
3618 if (sdkp->opt_xfer_blocks > dev_max) {
3619 sd_first_printk(KERN_WARNING, sdkp,
3620 "Optimal transfer size %u logical blocks " \
3621 "> dev_max (%u logical blocks)\n",
3622 sdkp->opt_xfer_blocks, dev_max);
3626 if (sdkp->opt_xfer_blocks > SD_DEF_XFER_BLOCKS) {
3627 sd_first_printk(KERN_WARNING, sdkp,
3628 "Optimal transfer size %u logical blocks " \
3629 "> sd driver limit (%u logical blocks)\n",
3630 sdkp->opt_xfer_blocks, SD_DEF_XFER_BLOCKS);
3634 if (opt_xfer_bytes < PAGE_SIZE) {
3635 sd_first_printk(KERN_WARNING, sdkp,
3636 "Optimal transfer size %u bytes < " \
3637 "PAGE_SIZE (%u bytes)\n",
3638 opt_xfer_bytes, (unsigned int)PAGE_SIZE);
3642 if (min_xfer_bytes && opt_xfer_bytes % min_xfer_bytes) {
3643 sd_first_printk(KERN_WARNING, sdkp,
3644 "Optimal transfer size %u bytes not a " \
3645 "multiple of preferred minimum block " \
3646 "size (%u bytes)\n",
3647 opt_xfer_bytes, min_xfer_bytes);
3651 if (opt_xfer_bytes & (sdkp->physical_block_size - 1)) {
3652 sd_first_printk(KERN_WARNING, sdkp,
3653 "Optimal transfer size %u bytes not a " \
3654 "multiple of physical block size (%u bytes)\n",
3655 opt_xfer_bytes, sdkp->physical_block_size);
3659 sd_first_printk(KERN_INFO, sdkp, "Optimal transfer size %u bytes\n",
3664 static void sd_read_block_zero(struct scsi_disk *sdkp)
3666 struct scsi_device *sdev = sdkp->device;
3667 unsigned int buf_len = sdev->sector_size;
3668 u8 *buffer, cmd[16] = { };
3670 buffer = kmalloc(buf_len, GFP_KERNEL);
3674 if (sdev->use_16_for_rw) {
3676 put_unaligned_be64(0, &cmd[2]); /* Logical block address 0 */
3677 put_unaligned_be32(1, &cmd[10]);/* Transfer 1 logical block */
3680 put_unaligned_be32(0, &cmd[2]); /* Logical block address 0 */
3681 put_unaligned_be16(1, &cmd[7]); /* Transfer 1 logical block */
3684 scsi_execute_cmd(sdkp->device, cmd, REQ_OP_DRV_IN, buffer, buf_len,
3685 SD_TIMEOUT, sdkp->max_retries, NULL);
3690 * sd_revalidate_disk - called the first time a new disk is seen,
3691 * performs disk spin up, read_capacity, etc.
3692 * @disk: struct gendisk we care about
3694 static int sd_revalidate_disk(struct gendisk *disk)
3696 struct scsi_disk *sdkp = scsi_disk(disk);
3697 struct scsi_device *sdp = sdkp->device;
3698 sector_t old_capacity = sdkp->capacity;
3699 struct queue_limits lim;
3700 unsigned char *buffer;
3701 unsigned int dev_max;
3704 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
3705 "sd_revalidate_disk\n"));
3708 * If the device is offline, don't try and read capacity or any
3709 * of the other niceties.
3711 if (!scsi_device_online(sdp))
3714 buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
3716 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
3717 "allocation failure.\n");
3721 sd_spinup_disk(sdkp);
3723 lim = queue_limits_start_update(sdkp->disk->queue);
3726 * Without media there is no reason to ask; moreover, some devices
3727 * react badly if we do.
3729 if (sdkp->media_present) {
3730 sd_read_capacity(sdkp, &lim, buffer);
3732 * Some USB/UAS devices return generic values for mode pages
3733 * until the media has been accessed. Trigger a READ operation
3734 * to force the device to populate mode pages.
3736 if (sdp->read_before_ms)
3737 sd_read_block_zero(sdkp);
3739 * set the default to rotational. All non-rotational devices
3740 * support the block characteristics VPD page, which will
3741 * cause this to be updated correctly and any device which
3742 * doesn't support it should be treated as rotational.
3744 lim.features |= (BLK_FEAT_ROTATIONAL | BLK_FEAT_ADD_RANDOM);
3746 if (scsi_device_supports_vpd(sdp)) {
3747 sd_read_block_provisioning(sdkp);
3748 sd_read_block_limits(sdkp, &lim);
3749 sd_read_block_limits_ext(sdkp);
3750 sd_read_block_characteristics(sdkp, &lim);
3751 sd_zbc_read_zones(sdkp, &lim, buffer);
3754 sd_config_discard(sdkp, &lim, sd_discard_mode(sdkp));
3756 sd_print_capacity(sdkp, old_capacity);
3758 sd_read_write_protect_flag(sdkp, buffer);
3759 sd_read_cache_type(sdkp, buffer);
3760 sd_read_io_hints(sdkp, buffer);
3761 sd_read_app_tag_own(sdkp, buffer);
3762 sd_read_write_same(sdkp, buffer);
3763 sd_read_security(sdkp, buffer);
3764 sd_config_protection(sdkp, &lim);
3768 * We now have all cache related info, determine how we deal
3769 * with flush requests.
3771 sd_set_flush_flag(sdkp, &lim);
3773 /* Initial block count limit based on CDB TRANSFER LENGTH field size. */
3774 dev_max = sdp->use_16_for_rw ? SD_MAX_XFER_BLOCKS : SD_DEF_XFER_BLOCKS;
3776 /* Some devices report a maximum block count for READ/WRITE requests. */
3777 dev_max = min_not_zero(dev_max, sdkp->max_xfer_blocks);
3778 lim.max_dev_sectors = logical_to_sectors(sdp, dev_max);
3780 if (sd_validate_min_xfer_size(sdkp))
3781 lim.io_min = logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3786 * Limit default to SCSI host optimal sector limit if set. There may be
3787 * an impact on performance for when the size of a request exceeds this
3790 lim.io_opt = sdp->host->opt_sectors << SECTOR_SHIFT;
3791 if (sd_validate_opt_xfer_size(sdkp, dev_max)) {
3792 lim.io_opt = min_not_zero(lim.io_opt,
3793 logical_to_bytes(sdp, sdkp->opt_xfer_blocks));
3796 sdkp->first_scan = 0;
3798 set_capacity_and_notify(disk, logical_to_sectors(sdp, sdkp->capacity));
3799 sd_config_write_same(sdkp, &lim);
3802 blk_mq_freeze_queue(sdkp->disk->queue);
3803 err = queue_limits_commit_update(sdkp->disk->queue, &lim);
3804 blk_mq_unfreeze_queue(sdkp->disk->queue);
3809 * Query concurrent positioning ranges after
3810 * queue_limits_commit_update() unlocked q->limits_lock to avoid
3811 * deadlock with q->sysfs_dir_lock and q->sysfs_lock.
3813 if (sdkp->media_present && scsi_device_supports_vpd(sdp))
3817 * For a zoned drive, revalidating the zones can be done only once
3818 * the gendisk capacity is set. So if this fails, set back the gendisk
3821 if (sd_zbc_revalidate_zones(sdkp))
3822 set_capacity_and_notify(disk, 0);
3829 * sd_unlock_native_capacity - unlock native capacity
3830 * @disk: struct gendisk to set capacity for
3832 * Block layer calls this function if it detects that partitions
3833 * on @disk reach beyond the end of the device. If the SCSI host
3834 * implements ->unlock_native_capacity() method, it's invoked to
3835 * give it a chance to adjust the device capacity.
3838 * Defined by block layer. Might sleep.
3840 static void sd_unlock_native_capacity(struct gendisk *disk)
3842 struct scsi_device *sdev = scsi_disk(disk)->device;
3844 if (sdev->host->hostt->unlock_native_capacity)
3845 sdev->host->hostt->unlock_native_capacity(sdev);
3849 * sd_format_disk_name - format disk name
3850 * @prefix: name prefix - ie. "sd" for SCSI disks
3851 * @index: index of the disk to format name for
3852 * @buf: output buffer
3853 * @buflen: length of the output buffer
3855 * SCSI disk names starts at sda. The 26th device is sdz and the
3856 * 27th is sdaa. The last one for two lettered suffix is sdzz
3857 * which is followed by sdaaa.
3859 * This is basically 26 base counting with one extra 'nil' entry
3860 * at the beginning from the second digit on and can be
3861 * determined using similar method as 26 base conversion with the
3862 * index shifted -1 after each digit is computed.
3868 * 0 on success, -errno on failure.
3870 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
3872 const int base = 'z' - 'a' + 1;
3873 char *begin = buf + strlen(prefix);
3874 char *end = buf + buflen;
3884 *--p = 'a' + (index % unit);
3885 index = (index / unit) - 1;
3886 } while (index >= 0);
3888 memmove(begin, p, end - p);
3889 memcpy(buf, prefix, strlen(prefix));
3895 * sd_probe - called during driver initialization and whenever a
3896 * new scsi device is attached to the system. It is called once
3897 * for each scsi device (not just disks) present.
3898 * @dev: pointer to device object
3900 * Returns 0 if successful (or not interested in this scsi device
3901 * (e.g. scanner)); 1 when there is an error.
3903 * Note: this function is invoked from the scsi mid-level.
3904 * This function sets up the mapping between a given
3905 * <host,channel,id,lun> (found in sdp) and new device name
3906 * (e.g. /dev/sda). More precisely it is the block device major
3907 * and minor number that is chosen here.
3909 * Assume sd_probe is not re-entrant (for time being)
3910 * Also think about sd_probe() and sd_remove() running coincidentally.
3912 static int sd_probe(struct device *dev)
3914 struct scsi_device *sdp = to_scsi_device(dev);
3915 struct scsi_disk *sdkp;
3920 scsi_autopm_get_device(sdp);
3922 if (sdp->type != TYPE_DISK &&
3923 sdp->type != TYPE_ZBC &&
3924 sdp->type != TYPE_MOD &&
3925 sdp->type != TYPE_RBC)
3928 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) && sdp->type == TYPE_ZBC) {
3929 sdev_printk(KERN_WARNING, sdp,
3930 "Unsupported ZBC host-managed device.\n");
3934 SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
3938 sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
3942 gd = blk_mq_alloc_disk_for_queue(sdp->request_queue,
3943 &sd_bio_compl_lkclass);
3947 index = ida_alloc(&sd_index_ida, GFP_KERNEL);
3949 sdev_printk(KERN_WARNING, sdp, "sd_probe: memory exhausted.\n");
3953 error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
3955 sdev_printk(KERN_WARNING, sdp, "SCSI disk (sd) name length exceeded.\n");
3956 goto out_free_index;
3961 sdkp->index = index;
3962 sdkp->max_retries = SD_MAX_RETRIES;
3963 atomic_set(&sdkp->openers, 0);
3964 atomic_set(&sdkp->device->ioerr_cnt, 0);
3966 if (!sdp->request_queue->rq_timeout) {
3967 if (sdp->type != TYPE_MOD)
3968 blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
3970 blk_queue_rq_timeout(sdp->request_queue,
3974 device_initialize(&sdkp->disk_dev);
3975 sdkp->disk_dev.parent = get_device(dev);
3976 sdkp->disk_dev.class = &sd_disk_class;
3977 dev_set_name(&sdkp->disk_dev, "%s", dev_name(dev));
3979 error = device_add(&sdkp->disk_dev);
3981 put_device(&sdkp->disk_dev);
3985 dev_set_drvdata(dev, sdkp);
3987 gd->major = sd_major((index & 0xf0) >> 4);
3988 gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
3989 gd->minors = SD_MINORS;
3991 gd->fops = &sd_fops;
3992 gd->private_data = sdkp;
3994 /* defaults, until the device tells us otherwise */
3995 sdp->sector_size = 512;
3997 sdkp->media_present = 1;
3998 sdkp->write_prot = 0;
3999 sdkp->cache_override = 0;
4003 sdkp->first_scan = 1;
4004 sdkp->max_medium_access_timeouts = SD_MAX_MEDIUM_TIMEOUTS;
4006 sd_revalidate_disk(gd);
4008 if (sdp->removable) {
4009 gd->flags |= GENHD_FL_REMOVABLE;
4010 gd->events |= DISK_EVENT_MEDIA_CHANGE;
4011 gd->event_flags = DISK_EVENT_FLAG_POLL | DISK_EVENT_FLAG_UEVENT;
4014 blk_pm_runtime_init(sdp->request_queue, dev);
4015 if (sdp->rpm_autosuspend) {
4016 pm_runtime_set_autosuspend_delay(dev,
4017 sdp->host->rpm_autosuspend_delay);
4020 error = device_add_disk(dev, gd, NULL);
4022 device_unregister(&sdkp->disk_dev);
4027 if (sdkp->security) {
4028 sdkp->opal_dev = init_opal_dev(sdkp, &sd_sec_submit);
4030 sd_printk(KERN_NOTICE, sdkp, "supports TCG Opal\n");
4033 sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
4034 sdp->removable ? "removable " : "");
4035 scsi_autopm_put_device(sdp);
4040 ida_free(&sd_index_ida, index);
4046 scsi_autopm_put_device(sdp);
4051 * sd_remove - called whenever a scsi disk (previously recognized by
4052 * sd_probe) is detached from the system. It is called (potentially
4053 * multiple times) during sd module unload.
4054 * @dev: pointer to device object
4056 * Note: this function is invoked from the scsi mid-level.
4057 * This function potentially frees up a device name (e.g. /dev/sdc)
4058 * that could be re-used by a subsequent sd_probe().
4059 * This function is not called when the built-in sd driver is "exit-ed".
4061 static int sd_remove(struct device *dev)
4063 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4065 scsi_autopm_get_device(sdkp->device);
4067 device_del(&sdkp->disk_dev);
4068 del_gendisk(sdkp->disk);
4069 if (!sdkp->suspended)
4072 put_disk(sdkp->disk);
4076 static void scsi_disk_release(struct device *dev)
4078 struct scsi_disk *sdkp = to_scsi_disk(dev);
4080 ida_free(&sd_index_ida, sdkp->index);
4081 put_device(&sdkp->device->sdev_gendev);
4082 free_opal_dev(sdkp->opal_dev);
4087 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
4089 unsigned char cmd[6] = { START_STOP }; /* START_VALID */
4090 struct scsi_sense_hdr sshdr;
4091 const struct scsi_exec_args exec_args = {
4093 .req_flags = BLK_MQ_REQ_PM,
4095 struct scsi_device *sdp = sdkp->device;
4099 cmd[4] |= 1; /* START */
4101 if (sdp->start_stop_pwr_cond)
4102 cmd[4] |= start ? 1 << 4 : 3 << 4; /* Active or Standby */
4104 if (!scsi_device_online(sdp))
4107 res = scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, NULL, 0, SD_TIMEOUT,
4108 sdkp->max_retries, &exec_args);
4110 sd_print_result(sdkp, "Start/Stop Unit failed", res);
4111 if (res > 0 && scsi_sense_valid(&sshdr)) {
4112 sd_print_sense_hdr(sdkp, &sshdr);
4113 /* 0x3a is medium not present */
4114 if (sshdr.asc == 0x3a)
4119 /* SCSI error codes must not go to the generic layer */
4127 * Send a SYNCHRONIZE CACHE instruction down to the device through
4128 * the normal SCSI command structure. Wait for the command to
4131 static void sd_shutdown(struct device *dev)
4133 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4136 return; /* this can happen */
4138 if (pm_runtime_suspended(dev))
4141 if (sdkp->WCE && sdkp->media_present) {
4142 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
4143 sd_sync_cache(sdkp);
4146 if ((system_state != SYSTEM_RESTART &&
4147 sdkp->device->manage_system_start_stop) ||
4148 (system_state == SYSTEM_POWER_OFF &&
4149 sdkp->device->manage_shutdown)) {
4150 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
4151 sd_start_stop_device(sdkp, 0);
4155 static inline bool sd_do_start_stop(struct scsi_device *sdev, bool runtime)
4157 return (sdev->manage_system_start_stop && !runtime) ||
4158 (sdev->manage_runtime_start_stop && runtime);
4161 static int sd_suspend_common(struct device *dev, bool runtime)
4163 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4166 if (!sdkp) /* E.g.: runtime suspend following sd_remove() */
4169 if (sdkp->WCE && sdkp->media_present) {
4170 if (!sdkp->device->silence_suspend)
4171 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
4172 ret = sd_sync_cache(sdkp);
4173 /* ignore OFFLINE device */
4181 if (sd_do_start_stop(sdkp->device, runtime)) {
4182 if (!sdkp->device->silence_suspend)
4183 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
4184 /* an error is not worth aborting a system sleep */
4185 ret = sd_start_stop_device(sdkp, 0);
4191 sdkp->suspended = true;
4196 static int sd_suspend_system(struct device *dev)
4198 if (pm_runtime_suspended(dev))
4201 return sd_suspend_common(dev, false);
4204 static int sd_suspend_runtime(struct device *dev)
4206 return sd_suspend_common(dev, true);
4209 static int sd_resume(struct device *dev)
4211 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4213 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
4215 if (opal_unlock_from_suspend(sdkp->opal_dev)) {
4216 sd_printk(KERN_NOTICE, sdkp, "OPAL unlock failed\n");
4223 static int sd_resume_common(struct device *dev, bool runtime)
4225 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4228 if (!sdkp) /* E.g.: runtime resume at the start of sd_probe() */
4231 if (!sd_do_start_stop(sdkp->device, runtime)) {
4232 sdkp->suspended = false;
4236 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
4237 ret = sd_start_stop_device(sdkp, 1);
4240 sdkp->suspended = false;
4246 static int sd_resume_system(struct device *dev)
4248 if (pm_runtime_suspended(dev)) {
4249 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4250 struct scsi_device *sdp = sdkp ? sdkp->device : NULL;
4252 if (sdp && sdp->force_runtime_start_on_system_start)
4253 pm_request_resume(dev);
4258 return sd_resume_common(dev, false);
4261 static int sd_resume_runtime(struct device *dev)
4263 struct scsi_disk *sdkp = dev_get_drvdata(dev);
4264 struct scsi_device *sdp;
4266 if (!sdkp) /* E.g.: runtime resume at the start of sd_probe() */
4271 if (sdp->ignore_media_change) {
4272 /* clear the device's sense data */
4273 static const u8 cmd[10] = { REQUEST_SENSE };
4274 const struct scsi_exec_args exec_args = {
4275 .req_flags = BLK_MQ_REQ_PM,
4278 if (scsi_execute_cmd(sdp, cmd, REQ_OP_DRV_IN, NULL, 0,
4279 sdp->request_queue->rq_timeout, 1,
4281 sd_printk(KERN_NOTICE, sdkp,
4282 "Failed to clear sense data\n");
4285 return sd_resume_common(dev, true);
4288 static const struct dev_pm_ops sd_pm_ops = {
4289 .suspend = sd_suspend_system,
4290 .resume = sd_resume_system,
4291 .poweroff = sd_suspend_system,
4292 .restore = sd_resume_system,
4293 .runtime_suspend = sd_suspend_runtime,
4294 .runtime_resume = sd_resume_runtime,
4297 static struct scsi_driver sd_template = {
4301 .probe_type = PROBE_PREFER_ASYNCHRONOUS,
4302 .remove = sd_remove,
4303 .shutdown = sd_shutdown,
4306 .rescan = sd_rescan,
4307 .resume = sd_resume,
4308 .init_command = sd_init_command,
4309 .uninit_command = sd_uninit_command,
4311 .eh_action = sd_eh_action,
4312 .eh_reset = sd_eh_reset,
4316 * init_sd - entry point for this driver (both when built in or when
4319 * Note: this function registers this driver with the scsi mid-level.
4321 static int __init init_sd(void)
4323 int majors = 0, i, err;
4325 SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
4327 for (i = 0; i < SD_MAJORS; i++) {
4328 if (__register_blkdev(sd_major(i), "sd", sd_default_probe))
4336 err = class_register(&sd_disk_class);
4340 sd_page_pool = mempool_create_page_pool(SD_MEMPOOL_SIZE, 0);
4341 if (!sd_page_pool) {
4342 printk(KERN_ERR "sd: can't init discard page pool\n");
4347 err = scsi_register_driver(&sd_template.gendrv);
4349 goto err_out_driver;
4354 mempool_destroy(sd_page_pool);
4356 class_unregister(&sd_disk_class);
4358 for (i = 0; i < SD_MAJORS; i++)
4359 unregister_blkdev(sd_major(i), "sd");
4364 * exit_sd - exit point for this driver (when it is a module).
4366 * Note: this function unregisters this driver from the scsi mid-level.
4368 static void __exit exit_sd(void)
4372 SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
4374 scsi_unregister_driver(&sd_template.gendrv);
4375 mempool_destroy(sd_page_pool);
4377 class_unregister(&sd_disk_class);
4379 for (i = 0; i < SD_MAJORS; i++)
4380 unregister_blkdev(sd_major(i), "sd");
4383 module_init(init_sd);
4384 module_exit(exit_sd);
4386 void sd_print_sense_hdr(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr)
4388 scsi_print_sense_hdr(sdkp->device,
4389 sdkp->disk ? sdkp->disk->disk_name : NULL, sshdr);
4392 void sd_print_result(const struct scsi_disk *sdkp, const char *msg, int result)
4394 const char *hb_string = scsi_hostbyte_string(result);
4397 sd_printk(KERN_INFO, sdkp,
4398 "%s: Result: hostbyte=%s driverbyte=%s\n", msg,
4399 hb_string ? hb_string : "invalid",
4402 sd_printk(KERN_INFO, sdkp,
4403 "%s: Result: hostbyte=0x%02x driverbyte=%s\n",
4404 msg, host_byte(result), "DRIVER_OK");