Linux 4.19.133
[linux/fpc-iii.git] / drivers / scsi / sd.c
blobf2f14d8d59432454c9c86d652cc4b0294b8145c8
1 /*
2 * sd.c Copyright (C) 1992 Drew Eckhardt
3 * Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
5 * Linux scsi disk driver
6 * Initial versions: Drew Eckhardt
7 * Subsequent revisions: Eric Youngdale
8 * Modification history:
9 * - Drew Eckhardt <drew@colorado.edu> original
10 * - Eric Youngdale <eric@andante.org> add scatter-gather, multiple
11 * outstanding request, and other enhancements.
12 * Support loadable low-level scsi drivers.
13 * - Jirka Hanika <geo@ff.cuni.cz> support more scsi disks using
14 * eight major numbers.
15 * - Richard Gooch <rgooch@atnf.csiro.au> support devfs.
16 * - Torben Mathiasen <tmm@image.dk> Resource allocation fixes in
17 * sd_init and cleanups.
18 * - Alex Davis <letmein@erols.com> Fix problem where partition info
19 * not being read in sd_open. Fix problem where removable media
20 * could be ejected after sd_open.
21 * - Douglas Gilbert <dgilbert@interlog.com> cleanup for lk 2.5.x
22 * - Badari Pulavarty <pbadari@us.ibm.com>, Matthew Wilcox
23 * <willy@debian.org>, Kurt Garloff <garloff@suse.de>:
24 * Support 32k/1M disks.
26 * Logging policy (needs CONFIG_SCSI_LOGGING defined):
27 * - setting up transfer: SCSI_LOG_HLQUEUE levels 1 and 2
28 * - end of transfer (bh + scsi_lib): SCSI_LOG_HLCOMPLETE level 1
29 * - entering sd_ioctl: SCSI_LOG_IOCTL level 1
30 * - entering other commands: SCSI_LOG_HLQUEUE level 3
31 * Note: when the logging level is set by the user, it must be greater
32 * than the level indicated above to trigger output.
35 #include <linux/module.h>
36 #include <linux/fs.h>
37 #include <linux/kernel.h>
38 #include <linux/mm.h>
39 #include <linux/bio.h>
40 #include <linux/genhd.h>
41 #include <linux/hdreg.h>
42 #include <linux/errno.h>
43 #include <linux/idr.h>
44 #include <linux/interrupt.h>
45 #include <linux/init.h>
46 #include <linux/blkdev.h>
47 #include <linux/blkpg.h>
48 #include <linux/delay.h>
49 #include <linux/mutex.h>
50 #include <linux/string_helpers.h>
51 #include <linux/async.h>
52 #include <linux/slab.h>
53 #include <linux/sed-opal.h>
54 #include <linux/pm_runtime.h>
55 #include <linux/pr.h>
56 #include <linux/t10-pi.h>
57 #include <linux/uaccess.h>
58 #include <asm/unaligned.h>
60 #include <scsi/scsi.h>
61 #include <scsi/scsi_cmnd.h>
62 #include <scsi/scsi_dbg.h>
63 #include <scsi/scsi_device.h>
64 #include <scsi/scsi_driver.h>
65 #include <scsi/scsi_eh.h>
66 #include <scsi/scsi_host.h>
67 #include <scsi/scsi_ioctl.h>
68 #include <scsi/scsicam.h>
70 #include "sd.h"
71 #include "scsi_priv.h"
72 #include "scsi_logging.h"
74 MODULE_AUTHOR("Eric Youngdale");
75 MODULE_DESCRIPTION("SCSI disk (sd) driver");
76 MODULE_LICENSE("GPL");
78 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
79 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
80 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
81 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
82 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
88 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
89 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
90 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
91 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
92 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
93 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
94 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
95 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
96 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
97 MODULE_ALIAS_SCSI_DEVICE(TYPE_ZBC);
99 #if !defined(CONFIG_DEBUG_BLOCK_EXT_DEVT)
100 #define SD_MINORS 16
101 #else
102 #define SD_MINORS 0
103 #endif
105 static void sd_config_discard(struct scsi_disk *, unsigned int);
106 static void sd_config_write_same(struct scsi_disk *);
107 static int sd_revalidate_disk(struct gendisk *);
108 static void sd_unlock_native_capacity(struct gendisk *disk);
109 static int sd_probe(struct device *);
110 static int sd_remove(struct device *);
111 static void sd_shutdown(struct device *);
112 static int sd_suspend_system(struct device *);
113 static int sd_suspend_runtime(struct device *);
114 static int sd_resume(struct device *);
115 static void sd_rescan(struct device *);
116 static int sd_init_command(struct scsi_cmnd *SCpnt);
117 static void sd_uninit_command(struct scsi_cmnd *SCpnt);
118 static int sd_done(struct scsi_cmnd *);
119 static void sd_eh_reset(struct scsi_cmnd *);
120 static int sd_eh_action(struct scsi_cmnd *, int);
121 static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer);
122 static void scsi_disk_release(struct device *cdev);
123 static void sd_print_sense_hdr(struct scsi_disk *, struct scsi_sense_hdr *);
124 static void sd_print_result(const struct scsi_disk *, const char *, int);
126 static DEFINE_IDA(sd_index_ida);
128 /* This semaphore is used to mediate the 0->1 reference get in the
129 * face of object destruction (i.e. we can't allow a get on an
130 * object after last put) */
131 static DEFINE_MUTEX(sd_ref_mutex);
133 static struct kmem_cache *sd_cdb_cache;
134 static mempool_t *sd_cdb_pool;
135 static mempool_t *sd_page_pool;
137 static const char *sd_cache_types[] = {
138 "write through", "none", "write back",
139 "write back, no read (daft)"
142 static void sd_set_flush_flag(struct scsi_disk *sdkp)
144 bool wc = false, fua = false;
146 if (sdkp->WCE) {
147 wc = true;
148 if (sdkp->DPOFUA)
149 fua = true;
152 blk_queue_write_cache(sdkp->disk->queue, wc, fua);
155 static ssize_t
156 cache_type_store(struct device *dev, struct device_attribute *attr,
157 const char *buf, size_t count)
159 int ct, rcd, wce, sp;
160 struct scsi_disk *sdkp = to_scsi_disk(dev);
161 struct scsi_device *sdp = sdkp->device;
162 char buffer[64];
163 char *buffer_data;
164 struct scsi_mode_data data;
165 struct scsi_sense_hdr sshdr;
166 static const char temp[] = "temporary ";
167 int len;
169 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
170 /* no cache control on RBC devices; theoretically they
171 * can do it, but there's probably so many exceptions
172 * it's not worth the risk */
173 return -EINVAL;
175 if (strncmp(buf, temp, sizeof(temp) - 1) == 0) {
176 buf += sizeof(temp) - 1;
177 sdkp->cache_override = 1;
178 } else {
179 sdkp->cache_override = 0;
182 ct = sysfs_match_string(sd_cache_types, buf);
183 if (ct < 0)
184 return -EINVAL;
186 rcd = ct & 0x01 ? 1 : 0;
187 wce = (ct & 0x02) && !sdkp->write_prot ? 1 : 0;
189 if (sdkp->cache_override) {
190 sdkp->WCE = wce;
191 sdkp->RCD = rcd;
192 sd_set_flush_flag(sdkp);
193 return count;
196 if (scsi_mode_sense(sdp, 0x08, 8, buffer, sizeof(buffer), SD_TIMEOUT,
197 SD_MAX_RETRIES, &data, NULL))
198 return -EINVAL;
199 len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
200 data.block_descriptor_length);
201 buffer_data = buffer + data.header_length +
202 data.block_descriptor_length;
203 buffer_data[2] &= ~0x05;
204 buffer_data[2] |= wce << 2 | rcd;
205 sp = buffer_data[0] & 0x80 ? 1 : 0;
206 buffer_data[0] &= ~0x80;
209 * Ensure WP, DPOFUA, and RESERVED fields are cleared in
210 * received mode parameter buffer before doing MODE SELECT.
212 data.device_specific = 0;
214 if (scsi_mode_select(sdp, 1, sp, 8, buffer_data, len, SD_TIMEOUT,
215 SD_MAX_RETRIES, &data, &sshdr)) {
216 if (scsi_sense_valid(&sshdr))
217 sd_print_sense_hdr(sdkp, &sshdr);
218 return -EINVAL;
220 revalidate_disk(sdkp->disk);
221 return count;
224 static ssize_t
225 manage_start_stop_show(struct device *dev, struct device_attribute *attr,
226 char *buf)
228 struct scsi_disk *sdkp = to_scsi_disk(dev);
229 struct scsi_device *sdp = sdkp->device;
231 return sprintf(buf, "%u\n", sdp->manage_start_stop);
234 static ssize_t
235 manage_start_stop_store(struct device *dev, struct device_attribute *attr,
236 const char *buf, size_t count)
238 struct scsi_disk *sdkp = to_scsi_disk(dev);
239 struct scsi_device *sdp = sdkp->device;
240 bool v;
242 if (!capable(CAP_SYS_ADMIN))
243 return -EACCES;
245 if (kstrtobool(buf, &v))
246 return -EINVAL;
248 sdp->manage_start_stop = v;
250 return count;
252 static DEVICE_ATTR_RW(manage_start_stop);
254 static ssize_t
255 allow_restart_show(struct device *dev, struct device_attribute *attr, char *buf)
257 struct scsi_disk *sdkp = to_scsi_disk(dev);
259 return sprintf(buf, "%u\n", sdkp->device->allow_restart);
262 static ssize_t
263 allow_restart_store(struct device *dev, struct device_attribute *attr,
264 const char *buf, size_t count)
266 bool v;
267 struct scsi_disk *sdkp = to_scsi_disk(dev);
268 struct scsi_device *sdp = sdkp->device;
270 if (!capable(CAP_SYS_ADMIN))
271 return -EACCES;
273 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
274 return -EINVAL;
276 if (kstrtobool(buf, &v))
277 return -EINVAL;
279 sdp->allow_restart = v;
281 return count;
283 static DEVICE_ATTR_RW(allow_restart);
285 static ssize_t
286 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
288 struct scsi_disk *sdkp = to_scsi_disk(dev);
289 int ct = sdkp->RCD + 2*sdkp->WCE;
291 return sprintf(buf, "%s\n", sd_cache_types[ct]);
293 static DEVICE_ATTR_RW(cache_type);
295 static ssize_t
296 FUA_show(struct device *dev, struct device_attribute *attr, char *buf)
298 struct scsi_disk *sdkp = to_scsi_disk(dev);
300 return sprintf(buf, "%u\n", sdkp->DPOFUA);
302 static DEVICE_ATTR_RO(FUA);
304 static ssize_t
305 protection_type_show(struct device *dev, struct device_attribute *attr,
306 char *buf)
308 struct scsi_disk *sdkp = to_scsi_disk(dev);
310 return sprintf(buf, "%u\n", sdkp->protection_type);
313 static ssize_t
314 protection_type_store(struct device *dev, struct device_attribute *attr,
315 const char *buf, size_t count)
317 struct scsi_disk *sdkp = to_scsi_disk(dev);
318 unsigned int val;
319 int err;
321 if (!capable(CAP_SYS_ADMIN))
322 return -EACCES;
324 err = kstrtouint(buf, 10, &val);
326 if (err)
327 return err;
329 if (val <= T10_PI_TYPE3_PROTECTION)
330 sdkp->protection_type = val;
332 return count;
334 static DEVICE_ATTR_RW(protection_type);
336 static ssize_t
337 protection_mode_show(struct device *dev, struct device_attribute *attr,
338 char *buf)
340 struct scsi_disk *sdkp = to_scsi_disk(dev);
341 struct scsi_device *sdp = sdkp->device;
342 unsigned int dif, dix;
344 dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
345 dix = scsi_host_dix_capable(sdp->host, sdkp->protection_type);
347 if (!dix && scsi_host_dix_capable(sdp->host, T10_PI_TYPE0_PROTECTION)) {
348 dif = 0;
349 dix = 1;
352 if (!dif && !dix)
353 return sprintf(buf, "none\n");
355 return sprintf(buf, "%s%u\n", dix ? "dix" : "dif", dif);
357 static DEVICE_ATTR_RO(protection_mode);
359 static ssize_t
360 app_tag_own_show(struct device *dev, struct device_attribute *attr, char *buf)
362 struct scsi_disk *sdkp = to_scsi_disk(dev);
364 return sprintf(buf, "%u\n", sdkp->ATO);
366 static DEVICE_ATTR_RO(app_tag_own);
368 static ssize_t
369 thin_provisioning_show(struct device *dev, struct device_attribute *attr,
370 char *buf)
372 struct scsi_disk *sdkp = to_scsi_disk(dev);
374 return sprintf(buf, "%u\n", sdkp->lbpme);
376 static DEVICE_ATTR_RO(thin_provisioning);
378 /* sysfs_match_string() requires dense arrays */
379 static const char *lbp_mode[] = {
380 [SD_LBP_FULL] = "full",
381 [SD_LBP_UNMAP] = "unmap",
382 [SD_LBP_WS16] = "writesame_16",
383 [SD_LBP_WS10] = "writesame_10",
384 [SD_LBP_ZERO] = "writesame_zero",
385 [SD_LBP_DISABLE] = "disabled",
388 static ssize_t
389 provisioning_mode_show(struct device *dev, struct device_attribute *attr,
390 char *buf)
392 struct scsi_disk *sdkp = to_scsi_disk(dev);
394 return sprintf(buf, "%s\n", lbp_mode[sdkp->provisioning_mode]);
397 static ssize_t
398 provisioning_mode_store(struct device *dev, struct device_attribute *attr,
399 const char *buf, size_t count)
401 struct scsi_disk *sdkp = to_scsi_disk(dev);
402 struct scsi_device *sdp = sdkp->device;
403 int mode;
405 if (!capable(CAP_SYS_ADMIN))
406 return -EACCES;
408 if (sd_is_zoned(sdkp)) {
409 sd_config_discard(sdkp, SD_LBP_DISABLE);
410 return count;
413 if (sdp->type != TYPE_DISK)
414 return -EINVAL;
416 mode = sysfs_match_string(lbp_mode, buf);
417 if (mode < 0)
418 return -EINVAL;
420 sd_config_discard(sdkp, mode);
422 return count;
424 static DEVICE_ATTR_RW(provisioning_mode);
426 /* sysfs_match_string() requires dense arrays */
427 static const char *zeroing_mode[] = {
428 [SD_ZERO_WRITE] = "write",
429 [SD_ZERO_WS] = "writesame",
430 [SD_ZERO_WS16_UNMAP] = "writesame_16_unmap",
431 [SD_ZERO_WS10_UNMAP] = "writesame_10_unmap",
434 static ssize_t
435 zeroing_mode_show(struct device *dev, struct device_attribute *attr,
436 char *buf)
438 struct scsi_disk *sdkp = to_scsi_disk(dev);
440 return sprintf(buf, "%s\n", zeroing_mode[sdkp->zeroing_mode]);
443 static ssize_t
444 zeroing_mode_store(struct device *dev, struct device_attribute *attr,
445 const char *buf, size_t count)
447 struct scsi_disk *sdkp = to_scsi_disk(dev);
448 int mode;
450 if (!capable(CAP_SYS_ADMIN))
451 return -EACCES;
453 mode = sysfs_match_string(zeroing_mode, buf);
454 if (mode < 0)
455 return -EINVAL;
457 sdkp->zeroing_mode = mode;
459 return count;
461 static DEVICE_ATTR_RW(zeroing_mode);
463 static ssize_t
464 max_medium_access_timeouts_show(struct device *dev,
465 struct device_attribute *attr, char *buf)
467 struct scsi_disk *sdkp = to_scsi_disk(dev);
469 return sprintf(buf, "%u\n", sdkp->max_medium_access_timeouts);
472 static ssize_t
473 max_medium_access_timeouts_store(struct device *dev,
474 struct device_attribute *attr, const char *buf,
475 size_t count)
477 struct scsi_disk *sdkp = to_scsi_disk(dev);
478 int err;
480 if (!capable(CAP_SYS_ADMIN))
481 return -EACCES;
483 err = kstrtouint(buf, 10, &sdkp->max_medium_access_timeouts);
485 return err ? err : count;
487 static DEVICE_ATTR_RW(max_medium_access_timeouts);
489 static ssize_t
490 max_write_same_blocks_show(struct device *dev, struct device_attribute *attr,
491 char *buf)
493 struct scsi_disk *sdkp = to_scsi_disk(dev);
495 return sprintf(buf, "%u\n", sdkp->max_ws_blocks);
498 static ssize_t
499 max_write_same_blocks_store(struct device *dev, struct device_attribute *attr,
500 const char *buf, size_t count)
502 struct scsi_disk *sdkp = to_scsi_disk(dev);
503 struct scsi_device *sdp = sdkp->device;
504 unsigned long max;
505 int err;
507 if (!capable(CAP_SYS_ADMIN))
508 return -EACCES;
510 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
511 return -EINVAL;
513 err = kstrtoul(buf, 10, &max);
515 if (err)
516 return err;
518 if (max == 0)
519 sdp->no_write_same = 1;
520 else if (max <= SD_MAX_WS16_BLOCKS) {
521 sdp->no_write_same = 0;
522 sdkp->max_ws_blocks = max;
525 sd_config_write_same(sdkp);
527 return count;
529 static DEVICE_ATTR_RW(max_write_same_blocks);
531 static struct attribute *sd_disk_attrs[] = {
532 &dev_attr_cache_type.attr,
533 &dev_attr_FUA.attr,
534 &dev_attr_allow_restart.attr,
535 &dev_attr_manage_start_stop.attr,
536 &dev_attr_protection_type.attr,
537 &dev_attr_protection_mode.attr,
538 &dev_attr_app_tag_own.attr,
539 &dev_attr_thin_provisioning.attr,
540 &dev_attr_provisioning_mode.attr,
541 &dev_attr_zeroing_mode.attr,
542 &dev_attr_max_write_same_blocks.attr,
543 &dev_attr_max_medium_access_timeouts.attr,
544 NULL,
546 ATTRIBUTE_GROUPS(sd_disk);
548 static struct class sd_disk_class = {
549 .name = "scsi_disk",
550 .owner = THIS_MODULE,
551 .dev_release = scsi_disk_release,
552 .dev_groups = sd_disk_groups,
555 static const struct dev_pm_ops sd_pm_ops = {
556 .suspend = sd_suspend_system,
557 .resume = sd_resume,
558 .poweroff = sd_suspend_system,
559 .restore = sd_resume,
560 .runtime_suspend = sd_suspend_runtime,
561 .runtime_resume = sd_resume,
564 static struct scsi_driver sd_template = {
565 .gendrv = {
566 .name = "sd",
567 .owner = THIS_MODULE,
568 .probe = sd_probe,
569 .remove = sd_remove,
570 .shutdown = sd_shutdown,
571 .pm = &sd_pm_ops,
573 .rescan = sd_rescan,
574 .init_command = sd_init_command,
575 .uninit_command = sd_uninit_command,
576 .done = sd_done,
577 .eh_action = sd_eh_action,
578 .eh_reset = sd_eh_reset,
582 * Dummy kobj_map->probe function.
583 * The default ->probe function will call modprobe, which is
584 * pointless as this module is already loaded.
586 static struct kobject *sd_default_probe(dev_t devt, int *partno, void *data)
588 return NULL;
592 * Device no to disk mapping:
594 * major disc2 disc p1
595 * |............|.............|....|....| <- dev_t
596 * 31 20 19 8 7 4 3 0
598 * Inside a major, we have 16k disks, however mapped non-
599 * contiguously. The first 16 disks are for major0, the next
600 * ones with major1, ... Disk 256 is for major0 again, disk 272
601 * for major1, ...
602 * As we stay compatible with our numbering scheme, we can reuse
603 * the well-know SCSI majors 8, 65--71, 136--143.
605 static int sd_major(int major_idx)
607 switch (major_idx) {
608 case 0:
609 return SCSI_DISK0_MAJOR;
610 case 1 ... 7:
611 return SCSI_DISK1_MAJOR + major_idx - 1;
612 case 8 ... 15:
613 return SCSI_DISK8_MAJOR + major_idx - 8;
614 default:
615 BUG();
616 return 0; /* shut up gcc */
620 static struct scsi_disk *scsi_disk_get(struct gendisk *disk)
622 struct scsi_disk *sdkp = NULL;
624 mutex_lock(&sd_ref_mutex);
626 if (disk->private_data) {
627 sdkp = scsi_disk(disk);
628 if (scsi_device_get(sdkp->device) == 0)
629 get_device(&sdkp->dev);
630 else
631 sdkp = NULL;
633 mutex_unlock(&sd_ref_mutex);
634 return sdkp;
637 static void scsi_disk_put(struct scsi_disk *sdkp)
639 struct scsi_device *sdev = sdkp->device;
641 mutex_lock(&sd_ref_mutex);
642 put_device(&sdkp->dev);
643 scsi_device_put(sdev);
644 mutex_unlock(&sd_ref_mutex);
647 #ifdef CONFIG_BLK_SED_OPAL
648 static int sd_sec_submit(void *data, u16 spsp, u8 secp, void *buffer,
649 size_t len, bool send)
651 struct scsi_device *sdev = data;
652 u8 cdb[12] = { 0, };
653 int ret;
655 cdb[0] = send ? SECURITY_PROTOCOL_OUT : SECURITY_PROTOCOL_IN;
656 cdb[1] = secp;
657 put_unaligned_be16(spsp, &cdb[2]);
658 put_unaligned_be32(len, &cdb[6]);
660 ret = scsi_execute_req(sdev, cdb,
661 send ? DMA_TO_DEVICE : DMA_FROM_DEVICE,
662 buffer, len, NULL, SD_TIMEOUT, SD_MAX_RETRIES, NULL);
663 return ret <= 0 ? ret : -EIO;
665 #endif /* CONFIG_BLK_SED_OPAL */
667 static unsigned char sd_setup_protect_cmnd(struct scsi_cmnd *scmd,
668 unsigned int dix, unsigned int dif)
670 struct bio *bio = scmd->request->bio;
671 unsigned int prot_op = sd_prot_op(rq_data_dir(scmd->request), dix, dif);
672 unsigned int protect = 0;
674 if (dix) { /* DIX Type 0, 1, 2, 3 */
675 if (bio_integrity_flagged(bio, BIP_IP_CHECKSUM))
676 scmd->prot_flags |= SCSI_PROT_IP_CHECKSUM;
678 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
679 scmd->prot_flags |= SCSI_PROT_GUARD_CHECK;
682 if (dif != T10_PI_TYPE3_PROTECTION) { /* DIX/DIF Type 0, 1, 2 */
683 scmd->prot_flags |= SCSI_PROT_REF_INCREMENT;
685 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
686 scmd->prot_flags |= SCSI_PROT_REF_CHECK;
689 if (dif) { /* DIX/DIF Type 1, 2, 3 */
690 scmd->prot_flags |= SCSI_PROT_TRANSFER_PI;
692 if (bio_integrity_flagged(bio, BIP_DISK_NOCHECK))
693 protect = 3 << 5; /* Disable target PI checking */
694 else
695 protect = 1 << 5; /* Enable target PI checking */
698 scsi_set_prot_op(scmd, prot_op);
699 scsi_set_prot_type(scmd, dif);
700 scmd->prot_flags &= sd_prot_flag_mask(prot_op);
702 return protect;
705 static void sd_config_discard(struct scsi_disk *sdkp, unsigned int mode)
707 struct request_queue *q = sdkp->disk->queue;
708 unsigned int logical_block_size = sdkp->device->sector_size;
709 unsigned int max_blocks = 0;
711 q->limits.discard_alignment =
712 sdkp->unmap_alignment * logical_block_size;
713 q->limits.discard_granularity =
714 max(sdkp->physical_block_size,
715 sdkp->unmap_granularity * logical_block_size);
716 sdkp->provisioning_mode = mode;
718 switch (mode) {
720 case SD_LBP_FULL:
721 case SD_LBP_DISABLE:
722 blk_queue_max_discard_sectors(q, 0);
723 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
724 return;
726 case SD_LBP_UNMAP:
727 max_blocks = min_not_zero(sdkp->max_unmap_blocks,
728 (u32)SD_MAX_WS16_BLOCKS);
729 break;
731 case SD_LBP_WS16:
732 if (sdkp->device->unmap_limit_for_ws)
733 max_blocks = sdkp->max_unmap_blocks;
734 else
735 max_blocks = sdkp->max_ws_blocks;
737 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS16_BLOCKS);
738 break;
740 case SD_LBP_WS10:
741 if (sdkp->device->unmap_limit_for_ws)
742 max_blocks = sdkp->max_unmap_blocks;
743 else
744 max_blocks = sdkp->max_ws_blocks;
746 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS10_BLOCKS);
747 break;
749 case SD_LBP_ZERO:
750 max_blocks = min_not_zero(sdkp->max_ws_blocks,
751 (u32)SD_MAX_WS10_BLOCKS);
752 break;
755 blk_queue_max_discard_sectors(q, max_blocks * (logical_block_size >> 9));
756 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
759 static int sd_setup_unmap_cmnd(struct scsi_cmnd *cmd)
761 struct scsi_device *sdp = cmd->device;
762 struct request *rq = cmd->request;
763 u64 sector = blk_rq_pos(rq) >> (ilog2(sdp->sector_size) - 9);
764 u32 nr_sectors = blk_rq_sectors(rq) >> (ilog2(sdp->sector_size) - 9);
765 unsigned int data_len = 24;
766 char *buf;
768 rq->special_vec.bv_page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
769 if (!rq->special_vec.bv_page)
770 return BLKPREP_DEFER;
771 clear_highpage(rq->special_vec.bv_page);
772 rq->special_vec.bv_offset = 0;
773 rq->special_vec.bv_len = data_len;
774 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
776 cmd->cmd_len = 10;
777 cmd->cmnd[0] = UNMAP;
778 cmd->cmnd[8] = 24;
780 buf = page_address(rq->special_vec.bv_page);
781 put_unaligned_be16(6 + 16, &buf[0]);
782 put_unaligned_be16(16, &buf[2]);
783 put_unaligned_be64(sector, &buf[8]);
784 put_unaligned_be32(nr_sectors, &buf[16]);
786 cmd->allowed = SD_MAX_RETRIES;
787 cmd->transfersize = data_len;
788 rq->timeout = SD_TIMEOUT;
789 scsi_req(rq)->resid_len = data_len;
791 return scsi_init_io(cmd);
794 static int sd_setup_write_same16_cmnd(struct scsi_cmnd *cmd, bool unmap)
796 struct scsi_device *sdp = cmd->device;
797 struct request *rq = cmd->request;
798 u64 sector = blk_rq_pos(rq) >> (ilog2(sdp->sector_size) - 9);
799 u32 nr_sectors = blk_rq_sectors(rq) >> (ilog2(sdp->sector_size) - 9);
800 u32 data_len = sdp->sector_size;
802 rq->special_vec.bv_page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
803 if (!rq->special_vec.bv_page)
804 return BLKPREP_DEFER;
805 clear_highpage(rq->special_vec.bv_page);
806 rq->special_vec.bv_offset = 0;
807 rq->special_vec.bv_len = data_len;
808 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
810 cmd->cmd_len = 16;
811 cmd->cmnd[0] = WRITE_SAME_16;
812 if (unmap)
813 cmd->cmnd[1] = 0x8; /* UNMAP */
814 put_unaligned_be64(sector, &cmd->cmnd[2]);
815 put_unaligned_be32(nr_sectors, &cmd->cmnd[10]);
817 cmd->allowed = SD_MAX_RETRIES;
818 cmd->transfersize = data_len;
819 rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
820 scsi_req(rq)->resid_len = data_len;
822 return scsi_init_io(cmd);
825 static int sd_setup_write_same10_cmnd(struct scsi_cmnd *cmd, bool unmap)
827 struct scsi_device *sdp = cmd->device;
828 struct request *rq = cmd->request;
829 u64 sector = blk_rq_pos(rq) >> (ilog2(sdp->sector_size) - 9);
830 u32 nr_sectors = blk_rq_sectors(rq) >> (ilog2(sdp->sector_size) - 9);
831 u32 data_len = sdp->sector_size;
833 rq->special_vec.bv_page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
834 if (!rq->special_vec.bv_page)
835 return BLKPREP_DEFER;
836 clear_highpage(rq->special_vec.bv_page);
837 rq->special_vec.bv_offset = 0;
838 rq->special_vec.bv_len = data_len;
839 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
841 cmd->cmd_len = 10;
842 cmd->cmnd[0] = WRITE_SAME;
843 if (unmap)
844 cmd->cmnd[1] = 0x8; /* UNMAP */
845 put_unaligned_be32(sector, &cmd->cmnd[2]);
846 put_unaligned_be16(nr_sectors, &cmd->cmnd[7]);
848 cmd->allowed = SD_MAX_RETRIES;
849 cmd->transfersize = data_len;
850 rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
851 scsi_req(rq)->resid_len = data_len;
853 return scsi_init_io(cmd);
856 static int sd_setup_write_zeroes_cmnd(struct scsi_cmnd *cmd)
858 struct request *rq = cmd->request;
859 struct scsi_device *sdp = cmd->device;
860 struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
861 u64 sector = blk_rq_pos(rq) >> (ilog2(sdp->sector_size) - 9);
862 u32 nr_sectors = blk_rq_sectors(rq) >> (ilog2(sdp->sector_size) - 9);
864 if (!(rq->cmd_flags & REQ_NOUNMAP)) {
865 switch (sdkp->zeroing_mode) {
866 case SD_ZERO_WS16_UNMAP:
867 return sd_setup_write_same16_cmnd(cmd, true);
868 case SD_ZERO_WS10_UNMAP:
869 return sd_setup_write_same10_cmnd(cmd, true);
873 if (sdp->no_write_same)
874 return BLKPREP_INVALID;
876 if (sdkp->ws16 || sector > 0xffffffff || nr_sectors > 0xffff)
877 return sd_setup_write_same16_cmnd(cmd, false);
879 return sd_setup_write_same10_cmnd(cmd, false);
882 static void sd_config_write_same(struct scsi_disk *sdkp)
884 struct request_queue *q = sdkp->disk->queue;
885 unsigned int logical_block_size = sdkp->device->sector_size;
887 if (sdkp->device->no_write_same) {
888 sdkp->max_ws_blocks = 0;
889 goto out;
892 /* Some devices can not handle block counts above 0xffff despite
893 * supporting WRITE SAME(16). Consequently we default to 64k
894 * blocks per I/O unless the device explicitly advertises a
895 * bigger limit.
897 if (sdkp->max_ws_blocks > SD_MAX_WS10_BLOCKS)
898 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
899 (u32)SD_MAX_WS16_BLOCKS);
900 else if (sdkp->ws16 || sdkp->ws10 || sdkp->device->no_report_opcodes)
901 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
902 (u32)SD_MAX_WS10_BLOCKS);
903 else {
904 sdkp->device->no_write_same = 1;
905 sdkp->max_ws_blocks = 0;
908 if (sdkp->lbprz && sdkp->lbpws)
909 sdkp->zeroing_mode = SD_ZERO_WS16_UNMAP;
910 else if (sdkp->lbprz && sdkp->lbpws10)
911 sdkp->zeroing_mode = SD_ZERO_WS10_UNMAP;
912 else if (sdkp->max_ws_blocks)
913 sdkp->zeroing_mode = SD_ZERO_WS;
914 else
915 sdkp->zeroing_mode = SD_ZERO_WRITE;
917 if (sdkp->max_ws_blocks &&
918 sdkp->physical_block_size > logical_block_size) {
920 * Reporting a maximum number of blocks that is not aligned
921 * on the device physical size would cause a large write same
922 * request to be split into physically unaligned chunks by
923 * __blkdev_issue_write_zeroes() and __blkdev_issue_write_same()
924 * even if the caller of these functions took care to align the
925 * large request. So make sure the maximum reported is aligned
926 * to the device physical block size. This is only an optional
927 * optimization for regular disks, but this is mandatory to
928 * avoid failure of large write same requests directed at
929 * sequential write required zones of host-managed ZBC disks.
931 sdkp->max_ws_blocks =
932 round_down(sdkp->max_ws_blocks,
933 bytes_to_logical(sdkp->device,
934 sdkp->physical_block_size));
937 out:
938 blk_queue_max_write_same_sectors(q, sdkp->max_ws_blocks *
939 (logical_block_size >> 9));
940 blk_queue_max_write_zeroes_sectors(q, sdkp->max_ws_blocks *
941 (logical_block_size >> 9));
945 * sd_setup_write_same_cmnd - write the same data to multiple blocks
946 * @cmd: command to prepare
948 * Will set up either WRITE SAME(10) or WRITE SAME(16) depending on
949 * the preference indicated by the target device.
951 static int sd_setup_write_same_cmnd(struct scsi_cmnd *cmd)
953 struct request *rq = cmd->request;
954 struct scsi_device *sdp = cmd->device;
955 struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
956 struct bio *bio = rq->bio;
957 sector_t sector = blk_rq_pos(rq);
958 unsigned int nr_sectors = blk_rq_sectors(rq);
959 unsigned int nr_bytes = blk_rq_bytes(rq);
960 int ret;
962 if (sdkp->device->no_write_same)
963 return BLKPREP_INVALID;
965 BUG_ON(bio_offset(bio) || bio_iovec(bio).bv_len != sdp->sector_size);
967 sector >>= ilog2(sdp->sector_size) - 9;
968 nr_sectors >>= ilog2(sdp->sector_size) - 9;
970 rq->timeout = SD_WRITE_SAME_TIMEOUT;
972 if (sdkp->ws16 || sector > 0xffffffff || nr_sectors > 0xffff) {
973 cmd->cmd_len = 16;
974 cmd->cmnd[0] = WRITE_SAME_16;
975 put_unaligned_be64(sector, &cmd->cmnd[2]);
976 put_unaligned_be32(nr_sectors, &cmd->cmnd[10]);
977 } else {
978 cmd->cmd_len = 10;
979 cmd->cmnd[0] = WRITE_SAME;
980 put_unaligned_be32(sector, &cmd->cmnd[2]);
981 put_unaligned_be16(nr_sectors, &cmd->cmnd[7]);
984 cmd->transfersize = sdp->sector_size;
985 cmd->allowed = SD_MAX_RETRIES;
988 * For WRITE SAME the data transferred via the DATA OUT buffer is
989 * different from the amount of data actually written to the target.
991 * We set up __data_len to the amount of data transferred via the
992 * DATA OUT buffer so that blk_rq_map_sg sets up the proper S/G list
993 * to transfer a single sector of data first, but then reset it to
994 * the amount of data to be written right after so that the I/O path
995 * knows how much to actually write.
997 rq->__data_len = sdp->sector_size;
998 ret = scsi_init_io(cmd);
999 rq->__data_len = nr_bytes;
1001 return ret;
1004 static int sd_setup_flush_cmnd(struct scsi_cmnd *cmd)
1006 struct request *rq = cmd->request;
1008 /* flush requests don't perform I/O, zero the S/G table */
1009 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1011 cmd->cmnd[0] = SYNCHRONIZE_CACHE;
1012 cmd->cmd_len = 10;
1013 cmd->transfersize = 0;
1014 cmd->allowed = SD_MAX_RETRIES;
1016 rq->timeout = rq->q->rq_timeout * SD_FLUSH_TIMEOUT_MULTIPLIER;
1017 return BLKPREP_OK;
1020 static int sd_setup_read_write_cmnd(struct scsi_cmnd *SCpnt)
1022 struct request *rq = SCpnt->request;
1023 struct scsi_device *sdp = SCpnt->device;
1024 struct gendisk *disk = rq->rq_disk;
1025 struct scsi_disk *sdkp = scsi_disk(disk);
1026 sector_t block = blk_rq_pos(rq);
1027 sector_t threshold;
1028 unsigned int this_count = blk_rq_sectors(rq);
1029 unsigned int dif, dix;
1030 int ret;
1031 unsigned char protect;
1033 ret = scsi_init_io(SCpnt);
1034 if (ret != BLKPREP_OK)
1035 return ret;
1036 WARN_ON_ONCE(SCpnt != rq->special);
1038 /* from here on until we're complete, any goto out
1039 * is used for a killable error condition */
1040 ret = BLKPREP_KILL;
1042 SCSI_LOG_HLQUEUE(1,
1043 scmd_printk(KERN_INFO, SCpnt,
1044 "%s: block=%llu, count=%d\n",
1045 __func__, (unsigned long long)block, this_count));
1047 if (!sdp || !scsi_device_online(sdp) ||
1048 block + blk_rq_sectors(rq) > get_capacity(disk)) {
1049 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
1050 "Finishing %u sectors\n",
1051 blk_rq_sectors(rq)));
1052 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
1053 "Retry with 0x%p\n", SCpnt));
1054 goto out;
1057 if (sdp->changed) {
1059 * quietly refuse to do anything to a changed disc until
1060 * the changed bit has been reset
1062 /* printk("SCSI disk has been changed or is not present. Prohibiting further I/O.\n"); */
1063 goto out;
1067 * Some SD card readers can't handle multi-sector accesses which touch
1068 * the last one or two hardware sectors. Split accesses as needed.
1070 threshold = get_capacity(disk) - SD_LAST_BUGGY_SECTORS *
1071 (sdp->sector_size / 512);
1073 if (unlikely(sdp->last_sector_bug && block + this_count > threshold)) {
1074 if (block < threshold) {
1075 /* Access up to the threshold but not beyond */
1076 this_count = threshold - block;
1077 } else {
1078 /* Access only a single hardware sector */
1079 this_count = sdp->sector_size / 512;
1083 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "block=%llu\n",
1084 (unsigned long long)block));
1087 * If we have a 1K hardware sectorsize, prevent access to single
1088 * 512 byte sectors. In theory we could handle this - in fact
1089 * the scsi cdrom driver must be able to handle this because
1090 * we typically use 1K blocksizes, and cdroms typically have
1091 * 2K hardware sectorsizes. Of course, things are simpler
1092 * with the cdrom, since it is read-only. For performance
1093 * reasons, the filesystems should be able to handle this
1094 * and not force the scsi disk driver to use bounce buffers
1095 * for this.
1097 if (sdp->sector_size == 1024) {
1098 if ((block & 1) || (blk_rq_sectors(rq) & 1)) {
1099 scmd_printk(KERN_ERR, SCpnt,
1100 "Bad block number requested\n");
1101 goto out;
1102 } else {
1103 block = block >> 1;
1104 this_count = this_count >> 1;
1107 if (sdp->sector_size == 2048) {
1108 if ((block & 3) || (blk_rq_sectors(rq) & 3)) {
1109 scmd_printk(KERN_ERR, SCpnt,
1110 "Bad block number requested\n");
1111 goto out;
1112 } else {
1113 block = block >> 2;
1114 this_count = this_count >> 2;
1117 if (sdp->sector_size == 4096) {
1118 if ((block & 7) || (blk_rq_sectors(rq) & 7)) {
1119 scmd_printk(KERN_ERR, SCpnt,
1120 "Bad block number requested\n");
1121 goto out;
1122 } else {
1123 block = block >> 3;
1124 this_count = this_count >> 3;
1127 if (rq_data_dir(rq) == WRITE) {
1128 SCpnt->cmnd[0] = WRITE_6;
1130 if (blk_integrity_rq(rq))
1131 t10_pi_prepare(SCpnt->request, sdkp->protection_type);
1133 } else if (rq_data_dir(rq) == READ) {
1134 SCpnt->cmnd[0] = READ_6;
1135 } else {
1136 scmd_printk(KERN_ERR, SCpnt, "Unknown command %d\n", req_op(rq));
1137 goto out;
1140 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
1141 "%s %d/%u 512 byte blocks.\n",
1142 (rq_data_dir(rq) == WRITE) ?
1143 "writing" : "reading", this_count,
1144 blk_rq_sectors(rq)));
1146 dix = scsi_prot_sg_count(SCpnt);
1147 dif = scsi_host_dif_capable(SCpnt->device->host, sdkp->protection_type);
1149 if (dif || dix)
1150 protect = sd_setup_protect_cmnd(SCpnt, dix, dif);
1151 else
1152 protect = 0;
1154 if (protect && sdkp->protection_type == T10_PI_TYPE2_PROTECTION) {
1155 SCpnt->cmnd = mempool_alloc(sd_cdb_pool, GFP_ATOMIC);
1157 if (unlikely(SCpnt->cmnd == NULL)) {
1158 ret = BLKPREP_DEFER;
1159 goto out;
1162 SCpnt->cmd_len = SD_EXT_CDB_SIZE;
1163 memset(SCpnt->cmnd, 0, SCpnt->cmd_len);
1164 SCpnt->cmnd[0] = VARIABLE_LENGTH_CMD;
1165 SCpnt->cmnd[7] = 0x18;
1166 SCpnt->cmnd[9] = (rq_data_dir(rq) == READ) ? READ_32 : WRITE_32;
1167 SCpnt->cmnd[10] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0);
1169 /* LBA */
1170 SCpnt->cmnd[12] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
1171 SCpnt->cmnd[13] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
1172 SCpnt->cmnd[14] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
1173 SCpnt->cmnd[15] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
1174 SCpnt->cmnd[16] = (unsigned char) (block >> 24) & 0xff;
1175 SCpnt->cmnd[17] = (unsigned char) (block >> 16) & 0xff;
1176 SCpnt->cmnd[18] = (unsigned char) (block >> 8) & 0xff;
1177 SCpnt->cmnd[19] = (unsigned char) block & 0xff;
1179 /* Expected Indirect LBA */
1180 SCpnt->cmnd[20] = (unsigned char) (block >> 24) & 0xff;
1181 SCpnt->cmnd[21] = (unsigned char) (block >> 16) & 0xff;
1182 SCpnt->cmnd[22] = (unsigned char) (block >> 8) & 0xff;
1183 SCpnt->cmnd[23] = (unsigned char) block & 0xff;
1185 /* Transfer length */
1186 SCpnt->cmnd[28] = (unsigned char) (this_count >> 24) & 0xff;
1187 SCpnt->cmnd[29] = (unsigned char) (this_count >> 16) & 0xff;
1188 SCpnt->cmnd[30] = (unsigned char) (this_count >> 8) & 0xff;
1189 SCpnt->cmnd[31] = (unsigned char) this_count & 0xff;
1190 } else if (sdp->use_16_for_rw || (this_count > 0xffff)) {
1191 SCpnt->cmnd[0] += READ_16 - READ_6;
1192 SCpnt->cmnd[1] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0);
1193 SCpnt->cmnd[2] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
1194 SCpnt->cmnd[3] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
1195 SCpnt->cmnd[4] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
1196 SCpnt->cmnd[5] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
1197 SCpnt->cmnd[6] = (unsigned char) (block >> 24) & 0xff;
1198 SCpnt->cmnd[7] = (unsigned char) (block >> 16) & 0xff;
1199 SCpnt->cmnd[8] = (unsigned char) (block >> 8) & 0xff;
1200 SCpnt->cmnd[9] = (unsigned char) block & 0xff;
1201 SCpnt->cmnd[10] = (unsigned char) (this_count >> 24) & 0xff;
1202 SCpnt->cmnd[11] = (unsigned char) (this_count >> 16) & 0xff;
1203 SCpnt->cmnd[12] = (unsigned char) (this_count >> 8) & 0xff;
1204 SCpnt->cmnd[13] = (unsigned char) this_count & 0xff;
1205 SCpnt->cmnd[14] = SCpnt->cmnd[15] = 0;
1206 } else if ((this_count > 0xff) || (block > 0x1fffff) ||
1207 scsi_device_protection(SCpnt->device) ||
1208 SCpnt->device->use_10_for_rw) {
1209 SCpnt->cmnd[0] += READ_10 - READ_6;
1210 SCpnt->cmnd[1] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0);
1211 SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
1212 SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
1213 SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
1214 SCpnt->cmnd[5] = (unsigned char) block & 0xff;
1215 SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
1216 SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
1217 SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
1218 } else {
1219 if (unlikely(rq->cmd_flags & REQ_FUA)) {
1221 * This happens only if this drive failed
1222 * 10byte rw command with ILLEGAL_REQUEST
1223 * during operation and thus turned off
1224 * use_10_for_rw.
1226 scmd_printk(KERN_ERR, SCpnt,
1227 "FUA write on READ/WRITE(6) drive\n");
1228 goto out;
1231 SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f);
1232 SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff);
1233 SCpnt->cmnd[3] = (unsigned char) block & 0xff;
1234 SCpnt->cmnd[4] = (unsigned char) this_count;
1235 SCpnt->cmnd[5] = 0;
1237 SCpnt->sdb.length = this_count * sdp->sector_size;
1240 * We shouldn't disconnect in the middle of a sector, so with a dumb
1241 * host adapter, it's safe to assume that we can at least transfer
1242 * this many bytes between each connect / disconnect.
1244 SCpnt->transfersize = sdp->sector_size;
1245 SCpnt->underflow = this_count << 9;
1246 SCpnt->allowed = SD_MAX_RETRIES;
1249 * This indicates that the command is ready from our end to be
1250 * queued.
1252 ret = BLKPREP_OK;
1253 out:
1254 return ret;
1257 static int sd_init_command(struct scsi_cmnd *cmd)
1259 struct request *rq = cmd->request;
1261 switch (req_op(rq)) {
1262 case REQ_OP_DISCARD:
1263 switch (scsi_disk(rq->rq_disk)->provisioning_mode) {
1264 case SD_LBP_UNMAP:
1265 return sd_setup_unmap_cmnd(cmd);
1266 case SD_LBP_WS16:
1267 return sd_setup_write_same16_cmnd(cmd, true);
1268 case SD_LBP_WS10:
1269 return sd_setup_write_same10_cmnd(cmd, true);
1270 case SD_LBP_ZERO:
1271 return sd_setup_write_same10_cmnd(cmd, false);
1272 default:
1273 return BLKPREP_INVALID;
1275 case REQ_OP_WRITE_ZEROES:
1276 return sd_setup_write_zeroes_cmnd(cmd);
1277 case REQ_OP_WRITE_SAME:
1278 return sd_setup_write_same_cmnd(cmd);
1279 case REQ_OP_FLUSH:
1280 return sd_setup_flush_cmnd(cmd);
1281 case REQ_OP_READ:
1282 case REQ_OP_WRITE:
1283 return sd_setup_read_write_cmnd(cmd);
1284 case REQ_OP_ZONE_REPORT:
1285 return sd_zbc_setup_report_cmnd(cmd);
1286 case REQ_OP_ZONE_RESET:
1287 return sd_zbc_setup_reset_cmnd(cmd);
1288 default:
1289 WARN_ON_ONCE(1);
1290 return BLKPREP_KILL;
1294 static void sd_uninit_command(struct scsi_cmnd *SCpnt)
1296 struct request *rq = SCpnt->request;
1297 u8 *cmnd;
1299 if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1300 mempool_free(rq->special_vec.bv_page, sd_page_pool);
1302 if (SCpnt->cmnd != scsi_req(rq)->cmd) {
1303 cmnd = SCpnt->cmnd;
1304 SCpnt->cmnd = NULL;
1305 SCpnt->cmd_len = 0;
1306 mempool_free(cmnd, sd_cdb_pool);
1311 * sd_open - open a scsi disk device
1312 * @bdev: Block device of the scsi disk to open
1313 * @mode: FMODE_* mask
1315 * Returns 0 if successful. Returns a negated errno value in case
1316 * of error.
1318 * Note: This can be called from a user context (e.g. fsck(1) )
1319 * or from within the kernel (e.g. as a result of a mount(1) ).
1320 * In the latter case @inode and @filp carry an abridged amount
1321 * of information as noted above.
1323 * Locking: called with bdev->bd_mutex held.
1325 static int sd_open(struct block_device *bdev, fmode_t mode)
1327 struct scsi_disk *sdkp = scsi_disk_get(bdev->bd_disk);
1328 struct scsi_device *sdev;
1329 int retval;
1331 if (!sdkp)
1332 return -ENXIO;
1334 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
1336 sdev = sdkp->device;
1339 * If the device is in error recovery, wait until it is done.
1340 * If the device is offline, then disallow any access to it.
1342 retval = -ENXIO;
1343 if (!scsi_block_when_processing_errors(sdev))
1344 goto error_out;
1346 if (sdev->removable || sdkp->write_prot)
1347 check_disk_change(bdev);
1350 * If the drive is empty, just let the open fail.
1352 retval = -ENOMEDIUM;
1353 if (sdev->removable && !sdkp->media_present && !(mode & FMODE_NDELAY))
1354 goto error_out;
1357 * If the device has the write protect tab set, have the open fail
1358 * if the user expects to be able to write to the thing.
1360 retval = -EROFS;
1361 if (sdkp->write_prot && (mode & FMODE_WRITE))
1362 goto error_out;
1365 * It is possible that the disk changing stuff resulted in
1366 * the device being taken offline. If this is the case,
1367 * report this to the user, and don't pretend that the
1368 * open actually succeeded.
1370 retval = -ENXIO;
1371 if (!scsi_device_online(sdev))
1372 goto error_out;
1374 if ((atomic_inc_return(&sdkp->openers) == 1) && sdev->removable) {
1375 if (scsi_block_when_processing_errors(sdev))
1376 scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
1379 return 0;
1381 error_out:
1382 scsi_disk_put(sdkp);
1383 return retval;
1387 * sd_release - invoked when the (last) close(2) is called on this
1388 * scsi disk.
1389 * @disk: disk to release
1390 * @mode: FMODE_* mask
1392 * Returns 0.
1394 * Note: may block (uninterruptible) if error recovery is underway
1395 * on this disk.
1397 * Locking: called with bdev->bd_mutex held.
1399 static void sd_release(struct gendisk *disk, fmode_t mode)
1401 struct scsi_disk *sdkp = scsi_disk(disk);
1402 struct scsi_device *sdev = sdkp->device;
1404 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
1406 if (atomic_dec_return(&sdkp->openers) == 0 && sdev->removable) {
1407 if (scsi_block_when_processing_errors(sdev))
1408 scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
1411 scsi_disk_put(sdkp);
1414 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1416 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1417 struct scsi_device *sdp = sdkp->device;
1418 struct Scsi_Host *host = sdp->host;
1419 sector_t capacity = logical_to_sectors(sdp, sdkp->capacity);
1420 int diskinfo[4];
1422 /* default to most commonly used values */
1423 diskinfo[0] = 0x40; /* 1 << 6 */
1424 diskinfo[1] = 0x20; /* 1 << 5 */
1425 diskinfo[2] = capacity >> 11;
1427 /* override with calculated, extended default, or driver values */
1428 if (host->hostt->bios_param)
1429 host->hostt->bios_param(sdp, bdev, capacity, diskinfo);
1430 else
1431 scsicam_bios_param(bdev, capacity, diskinfo);
1433 geo->heads = diskinfo[0];
1434 geo->sectors = diskinfo[1];
1435 geo->cylinders = diskinfo[2];
1436 return 0;
1440 * sd_ioctl - process an ioctl
1441 * @bdev: target block device
1442 * @mode: FMODE_* mask
1443 * @cmd: ioctl command number
1444 * @arg: this is third argument given to ioctl(2) system call.
1445 * Often contains a pointer.
1447 * Returns 0 if successful (some ioctls return positive numbers on
1448 * success as well). Returns a negated errno value in case of error.
1450 * Note: most ioctls are forward onto the block subsystem or further
1451 * down in the scsi subsystem.
1453 static int sd_ioctl(struct block_device *bdev, fmode_t mode,
1454 unsigned int cmd, unsigned long arg)
1456 struct gendisk *disk = bdev->bd_disk;
1457 struct scsi_disk *sdkp = scsi_disk(disk);
1458 struct scsi_device *sdp = sdkp->device;
1459 void __user *p = (void __user *)arg;
1460 int error;
1462 SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, "
1463 "cmd=0x%x\n", disk->disk_name, cmd));
1465 error = scsi_verify_blk_ioctl(bdev, cmd);
1466 if (error < 0)
1467 return error;
1470 * If we are in the middle of error recovery, don't let anyone
1471 * else try and use this device. Also, if error recovery fails, it
1472 * may try and take the device offline, in which case all further
1473 * access to the device is prohibited.
1475 error = scsi_ioctl_block_when_processing_errors(sdp, cmd,
1476 (mode & FMODE_NDELAY) != 0);
1477 if (error)
1478 goto out;
1480 if (is_sed_ioctl(cmd))
1481 return sed_ioctl(sdkp->opal_dev, cmd, p);
1484 * Send SCSI addressing ioctls directly to mid level, send other
1485 * ioctls to block level and then onto mid level if they can't be
1486 * resolved.
1488 switch (cmd) {
1489 case SCSI_IOCTL_GET_IDLUN:
1490 case SCSI_IOCTL_GET_BUS_NUMBER:
1491 error = scsi_ioctl(sdp, cmd, p);
1492 break;
1493 default:
1494 error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p);
1495 if (error != -ENOTTY)
1496 break;
1497 error = scsi_ioctl(sdp, cmd, p);
1498 break;
1500 out:
1501 return error;
1504 static void set_media_not_present(struct scsi_disk *sdkp)
1506 if (sdkp->media_present)
1507 sdkp->device->changed = 1;
1509 if (sdkp->device->removable) {
1510 sdkp->media_present = 0;
1511 sdkp->capacity = 0;
1515 static int media_not_present(struct scsi_disk *sdkp,
1516 struct scsi_sense_hdr *sshdr)
1518 if (!scsi_sense_valid(sshdr))
1519 return 0;
1521 /* not invoked for commands that could return deferred errors */
1522 switch (sshdr->sense_key) {
1523 case UNIT_ATTENTION:
1524 case NOT_READY:
1525 /* medium not present */
1526 if (sshdr->asc == 0x3A) {
1527 set_media_not_present(sdkp);
1528 return 1;
1531 return 0;
1535 * sd_check_events - check media events
1536 * @disk: kernel device descriptor
1537 * @clearing: disk events currently being cleared
1539 * Returns mask of DISK_EVENT_*.
1541 * Note: this function is invoked from the block subsystem.
1543 static unsigned int sd_check_events(struct gendisk *disk, unsigned int clearing)
1545 struct scsi_disk *sdkp = scsi_disk_get(disk);
1546 struct scsi_device *sdp;
1547 int retval;
1549 if (!sdkp)
1550 return 0;
1552 sdp = sdkp->device;
1553 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_check_events\n"));
1556 * If the device is offline, don't send any commands - just pretend as
1557 * if the command failed. If the device ever comes back online, we
1558 * can deal with it then. It is only because of unrecoverable errors
1559 * that we would ever take a device offline in the first place.
1561 if (!scsi_device_online(sdp)) {
1562 set_media_not_present(sdkp);
1563 goto out;
1567 * Using TEST_UNIT_READY enables differentiation between drive with
1568 * no cartridge loaded - NOT READY, drive with changed cartridge -
1569 * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
1571 * Drives that auto spin down. eg iomega jaz 1G, will be started
1572 * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
1573 * sd_revalidate() is called.
1575 if (scsi_block_when_processing_errors(sdp)) {
1576 struct scsi_sense_hdr sshdr = { 0, };
1578 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, SD_MAX_RETRIES,
1579 &sshdr);
1581 /* failed to execute TUR, assume media not present */
1582 if (host_byte(retval)) {
1583 set_media_not_present(sdkp);
1584 goto out;
1587 if (media_not_present(sdkp, &sshdr))
1588 goto out;
1592 * For removable scsi disk we have to recognise the presence
1593 * of a disk in the drive.
1595 if (!sdkp->media_present)
1596 sdp->changed = 1;
1597 sdkp->media_present = 1;
1598 out:
1600 * sdp->changed is set under the following conditions:
1602 * Medium present state has changed in either direction.
1603 * Device has indicated UNIT_ATTENTION.
1605 retval = sdp->changed ? DISK_EVENT_MEDIA_CHANGE : 0;
1606 sdp->changed = 0;
1607 scsi_disk_put(sdkp);
1608 return retval;
1611 static int sd_sync_cache(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr)
1613 int retries, res;
1614 struct scsi_device *sdp = sdkp->device;
1615 const int timeout = sdp->request_queue->rq_timeout
1616 * SD_FLUSH_TIMEOUT_MULTIPLIER;
1617 struct scsi_sense_hdr my_sshdr;
1619 if (!scsi_device_online(sdp))
1620 return -ENODEV;
1622 /* caller might not be interested in sense, but we need it */
1623 if (!sshdr)
1624 sshdr = &my_sshdr;
1626 for (retries = 3; retries > 0; --retries) {
1627 unsigned char cmd[10] = { 0 };
1629 cmd[0] = SYNCHRONIZE_CACHE;
1631 * Leave the rest of the command zero to indicate
1632 * flush everything.
1634 res = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, sshdr,
1635 timeout, SD_MAX_RETRIES, 0, RQF_PM, NULL);
1636 if (res == 0)
1637 break;
1640 if (res) {
1641 sd_print_result(sdkp, "Synchronize Cache(10) failed", res);
1643 if (driver_byte(res) == DRIVER_SENSE)
1644 sd_print_sense_hdr(sdkp, sshdr);
1646 /* we need to evaluate the error return */
1647 if (scsi_sense_valid(sshdr) &&
1648 (sshdr->asc == 0x3a || /* medium not present */
1649 sshdr->asc == 0x20 || /* invalid command */
1650 (sshdr->asc == 0x74 && sshdr->ascq == 0x71))) /* drive is password locked */
1651 /* this is no error here */
1652 return 0;
1654 switch (host_byte(res)) {
1655 /* ignore errors due to racing a disconnection */
1656 case DID_BAD_TARGET:
1657 case DID_NO_CONNECT:
1658 return 0;
1659 /* signal the upper layer it might try again */
1660 case DID_BUS_BUSY:
1661 case DID_IMM_RETRY:
1662 case DID_REQUEUE:
1663 case DID_SOFT_ERROR:
1664 return -EBUSY;
1665 default:
1666 return -EIO;
1669 return 0;
1672 static void sd_rescan(struct device *dev)
1674 struct scsi_disk *sdkp = dev_get_drvdata(dev);
1676 revalidate_disk(sdkp->disk);
1680 #ifdef CONFIG_COMPAT
1682 * This gets directly called from VFS. When the ioctl
1683 * is not recognized we go back to the other translation paths.
1685 static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode,
1686 unsigned int cmd, unsigned long arg)
1688 struct gendisk *disk = bdev->bd_disk;
1689 struct scsi_disk *sdkp = scsi_disk(disk);
1690 struct scsi_device *sdev = sdkp->device;
1691 void __user *p = compat_ptr(arg);
1692 int error;
1694 error = scsi_verify_blk_ioctl(bdev, cmd);
1695 if (error < 0)
1696 return error;
1698 error = scsi_ioctl_block_when_processing_errors(sdev, cmd,
1699 (mode & FMODE_NDELAY) != 0);
1700 if (error)
1701 return error;
1703 if (is_sed_ioctl(cmd))
1704 return sed_ioctl(sdkp->opal_dev, cmd, p);
1707 * Let the static ioctl translation table take care of it.
1709 if (!sdev->host->hostt->compat_ioctl)
1710 return -ENOIOCTLCMD;
1711 return sdev->host->hostt->compat_ioctl(sdev, cmd, p);
1713 #endif
1715 static char sd_pr_type(enum pr_type type)
1717 switch (type) {
1718 case PR_WRITE_EXCLUSIVE:
1719 return 0x01;
1720 case PR_EXCLUSIVE_ACCESS:
1721 return 0x03;
1722 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1723 return 0x05;
1724 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1725 return 0x06;
1726 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1727 return 0x07;
1728 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1729 return 0x08;
1730 default:
1731 return 0;
1735 static int sd_pr_command(struct block_device *bdev, u8 sa,
1736 u64 key, u64 sa_key, u8 type, u8 flags)
1738 struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device;
1739 struct scsi_sense_hdr sshdr;
1740 int result;
1741 u8 cmd[16] = { 0, };
1742 u8 data[24] = { 0, };
1744 cmd[0] = PERSISTENT_RESERVE_OUT;
1745 cmd[1] = sa;
1746 cmd[2] = type;
1747 put_unaligned_be32(sizeof(data), &cmd[5]);
1749 put_unaligned_be64(key, &data[0]);
1750 put_unaligned_be64(sa_key, &data[8]);
1751 data[20] = flags;
1753 result = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, &data, sizeof(data),
1754 &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL);
1756 if (driver_byte(result) == DRIVER_SENSE &&
1757 scsi_sense_valid(&sshdr)) {
1758 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
1759 scsi_print_sense_hdr(sdev, NULL, &sshdr);
1762 return result;
1765 static int sd_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
1766 u32 flags)
1768 if (flags & ~PR_FL_IGNORE_KEY)
1769 return -EOPNOTSUPP;
1770 return sd_pr_command(bdev, (flags & PR_FL_IGNORE_KEY) ? 0x06 : 0x00,
1771 old_key, new_key, 0,
1772 (1 << 0) /* APTPL */);
1775 static int sd_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
1776 u32 flags)
1778 if (flags)
1779 return -EOPNOTSUPP;
1780 return sd_pr_command(bdev, 0x01, key, 0, sd_pr_type(type), 0);
1783 static int sd_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1785 return sd_pr_command(bdev, 0x02, key, 0, sd_pr_type(type), 0);
1788 static int sd_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
1789 enum pr_type type, bool abort)
1791 return sd_pr_command(bdev, abort ? 0x05 : 0x04, old_key, new_key,
1792 sd_pr_type(type), 0);
1795 static int sd_pr_clear(struct block_device *bdev, u64 key)
1797 return sd_pr_command(bdev, 0x03, key, 0, 0, 0);
1800 static const struct pr_ops sd_pr_ops = {
1801 .pr_register = sd_pr_register,
1802 .pr_reserve = sd_pr_reserve,
1803 .pr_release = sd_pr_release,
1804 .pr_preempt = sd_pr_preempt,
1805 .pr_clear = sd_pr_clear,
1808 static const struct block_device_operations sd_fops = {
1809 .owner = THIS_MODULE,
1810 .open = sd_open,
1811 .release = sd_release,
1812 .ioctl = sd_ioctl,
1813 .getgeo = sd_getgeo,
1814 #ifdef CONFIG_COMPAT
1815 .compat_ioctl = sd_compat_ioctl,
1816 #endif
1817 .check_events = sd_check_events,
1818 .revalidate_disk = sd_revalidate_disk,
1819 .unlock_native_capacity = sd_unlock_native_capacity,
1820 .pr_ops = &sd_pr_ops,
1824 * sd_eh_reset - reset error handling callback
1825 * @scmd: sd-issued command that has failed
1827 * This function is called by the SCSI midlayer before starting
1828 * SCSI EH. When counting medium access failures we have to be
1829 * careful to register it only only once per device and SCSI EH run;
1830 * there might be several timed out commands which will cause the
1831 * 'max_medium_access_timeouts' counter to trigger after the first
1832 * SCSI EH run already and set the device to offline.
1833 * So this function resets the internal counter before starting SCSI EH.
1835 static void sd_eh_reset(struct scsi_cmnd *scmd)
1837 struct scsi_disk *sdkp = scsi_disk(scmd->request->rq_disk);
1839 /* New SCSI EH run, reset gate variable */
1840 sdkp->ignore_medium_access_errors = false;
1844 * sd_eh_action - error handling callback
1845 * @scmd: sd-issued command that has failed
1846 * @eh_disp: The recovery disposition suggested by the midlayer
1848 * This function is called by the SCSI midlayer upon completion of an
1849 * error test command (currently TEST UNIT READY). The result of sending
1850 * the eh command is passed in eh_disp. We're looking for devices that
1851 * fail medium access commands but are OK with non access commands like
1852 * test unit ready (so wrongly see the device as having a successful
1853 * recovery)
1855 static int sd_eh_action(struct scsi_cmnd *scmd, int eh_disp)
1857 struct scsi_disk *sdkp = scsi_disk(scmd->request->rq_disk);
1858 struct scsi_device *sdev = scmd->device;
1860 if (!scsi_device_online(sdev) ||
1861 !scsi_medium_access_command(scmd) ||
1862 host_byte(scmd->result) != DID_TIME_OUT ||
1863 eh_disp != SUCCESS)
1864 return eh_disp;
1867 * The device has timed out executing a medium access command.
1868 * However, the TEST UNIT READY command sent during error
1869 * handling completed successfully. Either the device is in the
1870 * process of recovering or has it suffered an internal failure
1871 * that prevents access to the storage medium.
1873 if (!sdkp->ignore_medium_access_errors) {
1874 sdkp->medium_access_timed_out++;
1875 sdkp->ignore_medium_access_errors = true;
1879 * If the device keeps failing read/write commands but TEST UNIT
1880 * READY always completes successfully we assume that medium
1881 * access is no longer possible and take the device offline.
1883 if (sdkp->medium_access_timed_out >= sdkp->max_medium_access_timeouts) {
1884 scmd_printk(KERN_ERR, scmd,
1885 "Medium access timeout failure. Offlining disk!\n");
1886 mutex_lock(&sdev->state_mutex);
1887 scsi_device_set_state(sdev, SDEV_OFFLINE);
1888 mutex_unlock(&sdev->state_mutex);
1890 return SUCCESS;
1893 return eh_disp;
1896 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
1898 struct request *req = scmd->request;
1899 struct scsi_device *sdev = scmd->device;
1900 unsigned int transferred, good_bytes;
1901 u64 start_lba, end_lba, bad_lba;
1904 * Some commands have a payload smaller than the device logical
1905 * block size (e.g. INQUIRY on a 4K disk).
1907 if (scsi_bufflen(scmd) <= sdev->sector_size)
1908 return 0;
1910 /* Check if we have a 'bad_lba' information */
1911 if (!scsi_get_sense_info_fld(scmd->sense_buffer,
1912 SCSI_SENSE_BUFFERSIZE,
1913 &bad_lba))
1914 return 0;
1917 * If the bad lba was reported incorrectly, we have no idea where
1918 * the error is.
1920 start_lba = sectors_to_logical(sdev, blk_rq_pos(req));
1921 end_lba = start_lba + bytes_to_logical(sdev, scsi_bufflen(scmd));
1922 if (bad_lba < start_lba || bad_lba >= end_lba)
1923 return 0;
1926 * resid is optional but mostly filled in. When it's unused,
1927 * its value is zero, so we assume the whole buffer transferred
1929 transferred = scsi_bufflen(scmd) - scsi_get_resid(scmd);
1931 /* This computation should always be done in terms of the
1932 * resolution of the device's medium.
1934 good_bytes = logical_to_bytes(sdev, bad_lba - start_lba);
1936 return min(good_bytes, transferred);
1940 * sd_done - bottom half handler: called when the lower level
1941 * driver has completed (successfully or otherwise) a scsi command.
1942 * @SCpnt: mid-level's per command structure.
1944 * Note: potentially run from within an ISR. Must not block.
1946 static int sd_done(struct scsi_cmnd *SCpnt)
1948 int result = SCpnt->result;
1949 unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
1950 unsigned int sector_size = SCpnt->device->sector_size;
1951 unsigned int resid;
1952 struct scsi_sense_hdr sshdr;
1953 struct scsi_disk *sdkp = scsi_disk(SCpnt->request->rq_disk);
1954 struct request *req = SCpnt->request;
1955 int sense_valid = 0;
1956 int sense_deferred = 0;
1958 switch (req_op(req)) {
1959 case REQ_OP_DISCARD:
1960 case REQ_OP_WRITE_ZEROES:
1961 case REQ_OP_WRITE_SAME:
1962 case REQ_OP_ZONE_RESET:
1963 if (!result) {
1964 good_bytes = blk_rq_bytes(req);
1965 scsi_set_resid(SCpnt, 0);
1966 } else {
1967 good_bytes = 0;
1968 scsi_set_resid(SCpnt, blk_rq_bytes(req));
1970 break;
1971 case REQ_OP_ZONE_REPORT:
1972 /* To avoid that the block layer performs an incorrect
1973 * bio_advance() call and restart of the remainder of
1974 * incomplete report zone BIOs, always indicate a full
1975 * completion of REQ_OP_ZONE_REPORT.
1977 if (!result) {
1978 good_bytes = scsi_bufflen(SCpnt);
1979 scsi_set_resid(SCpnt, 0);
1980 } else {
1981 good_bytes = 0;
1982 scsi_set_resid(SCpnt, blk_rq_bytes(req));
1984 break;
1985 default:
1987 * In case of bogus fw or device, we could end up having
1988 * an unaligned partial completion. Check this here and force
1989 * alignment.
1991 resid = scsi_get_resid(SCpnt);
1992 if (resid & (sector_size - 1)) {
1993 sd_printk(KERN_INFO, sdkp,
1994 "Unaligned partial completion (resid=%u, sector_sz=%u)\n",
1995 resid, sector_size);
1996 resid = min(scsi_bufflen(SCpnt),
1997 round_up(resid, sector_size));
1998 scsi_set_resid(SCpnt, resid);
2002 if (result) {
2003 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
2004 if (sense_valid)
2005 sense_deferred = scsi_sense_is_deferred(&sshdr);
2007 sdkp->medium_access_timed_out = 0;
2009 if (driver_byte(result) != DRIVER_SENSE &&
2010 (!sense_valid || sense_deferred))
2011 goto out;
2013 switch (sshdr.sense_key) {
2014 case HARDWARE_ERROR:
2015 case MEDIUM_ERROR:
2016 good_bytes = sd_completed_bytes(SCpnt);
2017 break;
2018 case RECOVERED_ERROR:
2019 good_bytes = scsi_bufflen(SCpnt);
2020 break;
2021 case NO_SENSE:
2022 /* This indicates a false check condition, so ignore it. An
2023 * unknown amount of data was transferred so treat it as an
2024 * error.
2026 SCpnt->result = 0;
2027 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
2028 break;
2029 case ABORTED_COMMAND:
2030 if (sshdr.asc == 0x10) /* DIF: Target detected corruption */
2031 good_bytes = sd_completed_bytes(SCpnt);
2032 break;
2033 case ILLEGAL_REQUEST:
2034 switch (sshdr.asc) {
2035 case 0x10: /* DIX: Host detected corruption */
2036 good_bytes = sd_completed_bytes(SCpnt);
2037 break;
2038 case 0x20: /* INVALID COMMAND OPCODE */
2039 case 0x24: /* INVALID FIELD IN CDB */
2040 switch (SCpnt->cmnd[0]) {
2041 case UNMAP:
2042 sd_config_discard(sdkp, SD_LBP_DISABLE);
2043 break;
2044 case WRITE_SAME_16:
2045 case WRITE_SAME:
2046 if (SCpnt->cmnd[1] & 8) { /* UNMAP */
2047 sd_config_discard(sdkp, SD_LBP_DISABLE);
2048 } else {
2049 sdkp->device->no_write_same = 1;
2050 sd_config_write_same(sdkp);
2051 req->rq_flags |= RQF_QUIET;
2053 break;
2056 break;
2057 default:
2058 break;
2061 out:
2062 if (sd_is_zoned(sdkp))
2063 sd_zbc_complete(SCpnt, good_bytes, &sshdr);
2065 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
2066 "sd_done: completed %d of %d bytes\n",
2067 good_bytes, scsi_bufflen(SCpnt)));
2069 if (rq_data_dir(SCpnt->request) == READ && scsi_prot_sg_count(SCpnt) &&
2070 good_bytes)
2071 t10_pi_complete(SCpnt->request, sdkp->protection_type,
2072 good_bytes / scsi_prot_interval(SCpnt));
2074 return good_bytes;
2078 * spinup disk - called only in sd_revalidate_disk()
2080 static void
2081 sd_spinup_disk(struct scsi_disk *sdkp)
2083 unsigned char cmd[10];
2084 unsigned long spintime_expire = 0;
2085 int retries, spintime;
2086 unsigned int the_result;
2087 struct scsi_sense_hdr sshdr;
2088 int sense_valid = 0;
2090 spintime = 0;
2092 /* Spin up drives, as required. Only do this at boot time */
2093 /* Spinup needs to be done for module loads too. */
2094 do {
2095 retries = 0;
2097 do {
2098 cmd[0] = TEST_UNIT_READY;
2099 memset((void *) &cmd[1], 0, 9);
2101 the_result = scsi_execute_req(sdkp->device, cmd,
2102 DMA_NONE, NULL, 0,
2103 &sshdr, SD_TIMEOUT,
2104 SD_MAX_RETRIES, NULL);
2107 * If the drive has indicated to us that it
2108 * doesn't have any media in it, don't bother
2109 * with any more polling.
2111 if (media_not_present(sdkp, &sshdr))
2112 return;
2114 if (the_result)
2115 sense_valid = scsi_sense_valid(&sshdr);
2116 retries++;
2117 } while (retries < 3 &&
2118 (!scsi_status_is_good(the_result) ||
2119 ((driver_byte(the_result) == DRIVER_SENSE) &&
2120 sense_valid && sshdr.sense_key == UNIT_ATTENTION)));
2122 if (driver_byte(the_result) != DRIVER_SENSE) {
2123 /* no sense, TUR either succeeded or failed
2124 * with a status error */
2125 if(!spintime && !scsi_status_is_good(the_result)) {
2126 sd_print_result(sdkp, "Test Unit Ready failed",
2127 the_result);
2129 break;
2133 * The device does not want the automatic start to be issued.
2135 if (sdkp->device->no_start_on_add)
2136 break;
2138 if (sense_valid && sshdr.sense_key == NOT_READY) {
2139 if (sshdr.asc == 4 && sshdr.ascq == 3)
2140 break; /* manual intervention required */
2141 if (sshdr.asc == 4 && sshdr.ascq == 0xb)
2142 break; /* standby */
2143 if (sshdr.asc == 4 && sshdr.ascq == 0xc)
2144 break; /* unavailable */
2145 if (sshdr.asc == 4 && sshdr.ascq == 0x1b)
2146 break; /* sanitize in progress */
2148 * Issue command to spin up drive when not ready
2150 if (!spintime) {
2151 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
2152 cmd[0] = START_STOP;
2153 cmd[1] = 1; /* Return immediately */
2154 memset((void *) &cmd[2], 0, 8);
2155 cmd[4] = 1; /* Start spin cycle */
2156 if (sdkp->device->start_stop_pwr_cond)
2157 cmd[4] |= 1 << 4;
2158 scsi_execute_req(sdkp->device, cmd, DMA_NONE,
2159 NULL, 0, &sshdr,
2160 SD_TIMEOUT, SD_MAX_RETRIES,
2161 NULL);
2162 spintime_expire = jiffies + 100 * HZ;
2163 spintime = 1;
2165 /* Wait 1 second for next try */
2166 msleep(1000);
2167 printk(KERN_CONT ".");
2170 * Wait for USB flash devices with slow firmware.
2171 * Yes, this sense key/ASC combination shouldn't
2172 * occur here. It's characteristic of these devices.
2174 } else if (sense_valid &&
2175 sshdr.sense_key == UNIT_ATTENTION &&
2176 sshdr.asc == 0x28) {
2177 if (!spintime) {
2178 spintime_expire = jiffies + 5 * HZ;
2179 spintime = 1;
2181 /* Wait 1 second for next try */
2182 msleep(1000);
2183 } else {
2184 /* we don't understand the sense code, so it's
2185 * probably pointless to loop */
2186 if(!spintime) {
2187 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
2188 sd_print_sense_hdr(sdkp, &sshdr);
2190 break;
2193 } while (spintime && time_before_eq(jiffies, spintime_expire));
2195 if (spintime) {
2196 if (scsi_status_is_good(the_result))
2197 printk(KERN_CONT "ready\n");
2198 else
2199 printk(KERN_CONT "not responding...\n");
2204 * Determine whether disk supports Data Integrity Field.
2206 static int sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
2208 struct scsi_device *sdp = sdkp->device;
2209 u8 type;
2210 int ret = 0;
2212 if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0) {
2213 sdkp->protection_type = 0;
2214 return ret;
2217 type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
2219 if (type > T10_PI_TYPE3_PROTECTION)
2220 ret = -ENODEV;
2221 else if (scsi_host_dif_capable(sdp->host, type))
2222 ret = 1;
2224 if (sdkp->first_scan || type != sdkp->protection_type)
2225 switch (ret) {
2226 case -ENODEV:
2227 sd_printk(KERN_ERR, sdkp, "formatted with unsupported" \
2228 " protection type %u. Disabling disk!\n",
2229 type);
2230 break;
2231 case 1:
2232 sd_printk(KERN_NOTICE, sdkp,
2233 "Enabling DIF Type %u protection\n", type);
2234 break;
2235 case 0:
2236 sd_printk(KERN_NOTICE, sdkp,
2237 "Disabling DIF Type %u protection\n", type);
2238 break;
2241 sdkp->protection_type = type;
2243 return ret;
2246 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
2247 struct scsi_sense_hdr *sshdr, int sense_valid,
2248 int the_result)
2250 if (driver_byte(the_result) == DRIVER_SENSE)
2251 sd_print_sense_hdr(sdkp, sshdr);
2252 else
2253 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
2256 * Set dirty bit for removable devices if not ready -
2257 * sometimes drives will not report this properly.
2259 if (sdp->removable &&
2260 sense_valid && sshdr->sense_key == NOT_READY)
2261 set_media_not_present(sdkp);
2264 * We used to set media_present to 0 here to indicate no media
2265 * in the drive, but some drives fail read capacity even with
2266 * media present, so we can't do that.
2268 sdkp->capacity = 0; /* unknown mapped to zero - as usual */
2271 #define RC16_LEN 32
2272 #if RC16_LEN > SD_BUF_SIZE
2273 #error RC16_LEN must not be more than SD_BUF_SIZE
2274 #endif
2276 #define READ_CAPACITY_RETRIES_ON_RESET 10
2279 * Ensure that we don't overflow sector_t when CONFIG_LBDAF is not set
2280 * and the reported logical block size is bigger than 512 bytes. Note
2281 * that last_sector is a u64 and therefore logical_to_sectors() is not
2282 * applicable.
2284 static bool sd_addressable_capacity(u64 lba, unsigned int sector_size)
2286 u64 last_sector = (lba + 1ULL) << (ilog2(sector_size) - 9);
2288 if (sizeof(sector_t) == 4 && last_sector > U32_MAX)
2289 return false;
2291 return true;
2294 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
2295 unsigned char *buffer)
2297 unsigned char cmd[16];
2298 struct scsi_sense_hdr sshdr;
2299 int sense_valid = 0;
2300 int the_result;
2301 int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2302 unsigned int alignment;
2303 unsigned long long lba;
2304 unsigned sector_size;
2306 if (sdp->no_read_capacity_16)
2307 return -EINVAL;
2309 do {
2310 memset(cmd, 0, 16);
2311 cmd[0] = SERVICE_ACTION_IN_16;
2312 cmd[1] = SAI_READ_CAPACITY_16;
2313 cmd[13] = RC16_LEN;
2314 memset(buffer, 0, RC16_LEN);
2316 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
2317 buffer, RC16_LEN, &sshdr,
2318 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
2320 if (media_not_present(sdkp, &sshdr))
2321 return -ENODEV;
2323 if (the_result) {
2324 sense_valid = scsi_sense_valid(&sshdr);
2325 if (sense_valid &&
2326 sshdr.sense_key == ILLEGAL_REQUEST &&
2327 (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
2328 sshdr.ascq == 0x00)
2329 /* Invalid Command Operation Code or
2330 * Invalid Field in CDB, just retry
2331 * silently with RC10 */
2332 return -EINVAL;
2333 if (sense_valid &&
2334 sshdr.sense_key == UNIT_ATTENTION &&
2335 sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2336 /* Device reset might occur several times,
2337 * give it one more chance */
2338 if (--reset_retries > 0)
2339 continue;
2341 retries--;
2343 } while (the_result && retries);
2345 if (the_result) {
2346 sd_print_result(sdkp, "Read Capacity(16) failed", the_result);
2347 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2348 return -EINVAL;
2351 sector_size = get_unaligned_be32(&buffer[8]);
2352 lba = get_unaligned_be64(&buffer[0]);
2354 if (sd_read_protection_type(sdkp, buffer) < 0) {
2355 sdkp->capacity = 0;
2356 return -ENODEV;
2359 if (!sd_addressable_capacity(lba, sector_size)) {
2360 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
2361 "kernel compiled with support for large block "
2362 "devices.\n");
2363 sdkp->capacity = 0;
2364 return -EOVERFLOW;
2367 /* Logical blocks per physical block exponent */
2368 sdkp->physical_block_size = (1 << (buffer[13] & 0xf)) * sector_size;
2370 /* RC basis */
2371 sdkp->rc_basis = (buffer[12] >> 4) & 0x3;
2373 /* Lowest aligned logical block */
2374 alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
2375 blk_queue_alignment_offset(sdp->request_queue, alignment);
2376 if (alignment && sdkp->first_scan)
2377 sd_printk(KERN_NOTICE, sdkp,
2378 "physical block alignment offset: %u\n", alignment);
2380 if (buffer[14] & 0x80) { /* LBPME */
2381 sdkp->lbpme = 1;
2383 if (buffer[14] & 0x40) /* LBPRZ */
2384 sdkp->lbprz = 1;
2386 sd_config_discard(sdkp, SD_LBP_WS16);
2389 sdkp->capacity = lba + 1;
2390 return sector_size;
2393 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
2394 unsigned char *buffer)
2396 unsigned char cmd[16];
2397 struct scsi_sense_hdr sshdr;
2398 int sense_valid = 0;
2399 int the_result;
2400 int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2401 sector_t lba;
2402 unsigned sector_size;
2404 do {
2405 cmd[0] = READ_CAPACITY;
2406 memset(&cmd[1], 0, 9);
2407 memset(buffer, 0, 8);
2409 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
2410 buffer, 8, &sshdr,
2411 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
2413 if (media_not_present(sdkp, &sshdr))
2414 return -ENODEV;
2416 if (the_result) {
2417 sense_valid = scsi_sense_valid(&sshdr);
2418 if (sense_valid &&
2419 sshdr.sense_key == UNIT_ATTENTION &&
2420 sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2421 /* Device reset might occur several times,
2422 * give it one more chance */
2423 if (--reset_retries > 0)
2424 continue;
2426 retries--;
2428 } while (the_result && retries);
2430 if (the_result) {
2431 sd_print_result(sdkp, "Read Capacity(10) failed", the_result);
2432 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2433 return -EINVAL;
2436 sector_size = get_unaligned_be32(&buffer[4]);
2437 lba = get_unaligned_be32(&buffer[0]);
2439 if (sdp->no_read_capacity_16 && (lba == 0xffffffff)) {
2440 /* Some buggy (usb cardreader) devices return an lba of
2441 0xffffffff when the want to report a size of 0 (with
2442 which they really mean no media is present) */
2443 sdkp->capacity = 0;
2444 sdkp->physical_block_size = sector_size;
2445 return sector_size;
2448 if (!sd_addressable_capacity(lba, sector_size)) {
2449 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
2450 "kernel compiled with support for large block "
2451 "devices.\n");
2452 sdkp->capacity = 0;
2453 return -EOVERFLOW;
2456 sdkp->capacity = lba + 1;
2457 sdkp->physical_block_size = sector_size;
2458 return sector_size;
2461 static int sd_try_rc16_first(struct scsi_device *sdp)
2463 if (sdp->host->max_cmd_len < 16)
2464 return 0;
2465 if (sdp->try_rc_10_first)
2466 return 0;
2467 if (sdp->scsi_level > SCSI_SPC_2)
2468 return 1;
2469 if (scsi_device_protection(sdp))
2470 return 1;
2471 return 0;
2475 * read disk capacity
2477 static void
2478 sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer)
2480 int sector_size;
2481 struct scsi_device *sdp = sdkp->device;
2483 if (sd_try_rc16_first(sdp)) {
2484 sector_size = read_capacity_16(sdkp, sdp, buffer);
2485 if (sector_size == -EOVERFLOW)
2486 goto got_data;
2487 if (sector_size == -ENODEV)
2488 return;
2489 if (sector_size < 0)
2490 sector_size = read_capacity_10(sdkp, sdp, buffer);
2491 if (sector_size < 0)
2492 return;
2493 } else {
2494 sector_size = read_capacity_10(sdkp, sdp, buffer);
2495 if (sector_size == -EOVERFLOW)
2496 goto got_data;
2497 if (sector_size < 0)
2498 return;
2499 if ((sizeof(sdkp->capacity) > 4) &&
2500 (sdkp->capacity > 0xffffffffULL)) {
2501 int old_sector_size = sector_size;
2502 sd_printk(KERN_NOTICE, sdkp, "Very big device. "
2503 "Trying to use READ CAPACITY(16).\n");
2504 sector_size = read_capacity_16(sdkp, sdp, buffer);
2505 if (sector_size < 0) {
2506 sd_printk(KERN_NOTICE, sdkp,
2507 "Using 0xffffffff as device size\n");
2508 sdkp->capacity = 1 + (sector_t) 0xffffffff;
2509 sector_size = old_sector_size;
2510 goto got_data;
2512 /* Remember that READ CAPACITY(16) succeeded */
2513 sdp->try_rc_10_first = 0;
2517 /* Some devices are known to return the total number of blocks,
2518 * not the highest block number. Some devices have versions
2519 * which do this and others which do not. Some devices we might
2520 * suspect of doing this but we don't know for certain.
2522 * If we know the reported capacity is wrong, decrement it. If
2523 * we can only guess, then assume the number of blocks is even
2524 * (usually true but not always) and err on the side of lowering
2525 * the capacity.
2527 if (sdp->fix_capacity ||
2528 (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
2529 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
2530 "from its reported value: %llu\n",
2531 (unsigned long long) sdkp->capacity);
2532 --sdkp->capacity;
2535 got_data:
2536 if (sector_size == 0) {
2537 sector_size = 512;
2538 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
2539 "assuming 512.\n");
2542 if (sector_size != 512 &&
2543 sector_size != 1024 &&
2544 sector_size != 2048 &&
2545 sector_size != 4096) {
2546 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
2547 sector_size);
2549 * The user might want to re-format the drive with
2550 * a supported sectorsize. Once this happens, it
2551 * would be relatively trivial to set the thing up.
2552 * For this reason, we leave the thing in the table.
2554 sdkp->capacity = 0;
2556 * set a bogus sector size so the normal read/write
2557 * logic in the block layer will eventually refuse any
2558 * request on this device without tripping over power
2559 * of two sector size assumptions
2561 sector_size = 512;
2563 blk_queue_logical_block_size(sdp->request_queue, sector_size);
2564 blk_queue_physical_block_size(sdp->request_queue,
2565 sdkp->physical_block_size);
2566 sdkp->device->sector_size = sector_size;
2568 if (sdkp->capacity > 0xffffffff)
2569 sdp->use_16_for_rw = 1;
2574 * Print disk capacity
2576 static void
2577 sd_print_capacity(struct scsi_disk *sdkp,
2578 sector_t old_capacity)
2580 int sector_size = sdkp->device->sector_size;
2581 char cap_str_2[10], cap_str_10[10];
2583 string_get_size(sdkp->capacity, sector_size,
2584 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
2585 string_get_size(sdkp->capacity, sector_size,
2586 STRING_UNITS_10, cap_str_10,
2587 sizeof(cap_str_10));
2589 if (sdkp->first_scan || old_capacity != sdkp->capacity) {
2590 sd_printk(KERN_NOTICE, sdkp,
2591 "%llu %d-byte logical blocks: (%s/%s)\n",
2592 (unsigned long long)sdkp->capacity,
2593 sector_size, cap_str_10, cap_str_2);
2595 if (sdkp->physical_block_size != sector_size)
2596 sd_printk(KERN_NOTICE, sdkp,
2597 "%u-byte physical blocks\n",
2598 sdkp->physical_block_size);
2600 sd_zbc_print_zones(sdkp);
2604 /* called with buffer of length 512 */
2605 static inline int
2606 sd_do_mode_sense(struct scsi_device *sdp, int dbd, int modepage,
2607 unsigned char *buffer, int len, struct scsi_mode_data *data,
2608 struct scsi_sense_hdr *sshdr)
2610 return scsi_mode_sense(sdp, dbd, modepage, buffer, len,
2611 SD_TIMEOUT, SD_MAX_RETRIES, data,
2612 sshdr);
2616 * read write protect setting, if possible - called only in sd_revalidate_disk()
2617 * called with buffer of length SD_BUF_SIZE
2619 static void
2620 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
2622 int res;
2623 struct scsi_device *sdp = sdkp->device;
2624 struct scsi_mode_data data;
2625 int old_wp = sdkp->write_prot;
2627 set_disk_ro(sdkp->disk, 0);
2628 if (sdp->skip_ms_page_3f) {
2629 sd_first_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
2630 return;
2633 if (sdp->use_192_bytes_for_3f) {
2634 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 192, &data, NULL);
2635 } else {
2637 * First attempt: ask for all pages (0x3F), but only 4 bytes.
2638 * We have to start carefully: some devices hang if we ask
2639 * for more than is available.
2641 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 4, &data, NULL);
2644 * Second attempt: ask for page 0 When only page 0 is
2645 * implemented, a request for page 3F may return Sense Key
2646 * 5: Illegal Request, Sense Code 24: Invalid field in
2647 * CDB.
2649 if (!scsi_status_is_good(res))
2650 res = sd_do_mode_sense(sdp, 0, 0, buffer, 4, &data, NULL);
2653 * Third attempt: ask 255 bytes, as we did earlier.
2655 if (!scsi_status_is_good(res))
2656 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 255,
2657 &data, NULL);
2660 if (!scsi_status_is_good(res)) {
2661 sd_first_printk(KERN_WARNING, sdkp,
2662 "Test WP failed, assume Write Enabled\n");
2663 } else {
2664 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
2665 set_disk_ro(sdkp->disk, sdkp->write_prot);
2666 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
2667 sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
2668 sdkp->write_prot ? "on" : "off");
2669 sd_printk(KERN_DEBUG, sdkp, "Mode Sense: %4ph\n", buffer);
2675 * sd_read_cache_type - called only from sd_revalidate_disk()
2676 * called with buffer of length SD_BUF_SIZE
2678 static void
2679 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
2681 int len = 0, res;
2682 struct scsi_device *sdp = sdkp->device;
2684 int dbd;
2685 int modepage;
2686 int first_len;
2687 struct scsi_mode_data data;
2688 struct scsi_sense_hdr sshdr;
2689 int old_wce = sdkp->WCE;
2690 int old_rcd = sdkp->RCD;
2691 int old_dpofua = sdkp->DPOFUA;
2694 if (sdkp->cache_override)
2695 return;
2697 first_len = 4;
2698 if (sdp->skip_ms_page_8) {
2699 if (sdp->type == TYPE_RBC)
2700 goto defaults;
2701 else {
2702 if (sdp->skip_ms_page_3f)
2703 goto defaults;
2704 modepage = 0x3F;
2705 if (sdp->use_192_bytes_for_3f)
2706 first_len = 192;
2707 dbd = 0;
2709 } else if (sdp->type == TYPE_RBC) {
2710 modepage = 6;
2711 dbd = 8;
2712 } else {
2713 modepage = 8;
2714 dbd = 0;
2717 /* cautiously ask */
2718 res = sd_do_mode_sense(sdp, dbd, modepage, buffer, first_len,
2719 &data, &sshdr);
2721 if (!scsi_status_is_good(res))
2722 goto bad_sense;
2724 if (!data.header_length) {
2725 modepage = 6;
2726 first_len = 0;
2727 sd_first_printk(KERN_ERR, sdkp,
2728 "Missing header in MODE_SENSE response\n");
2731 /* that went OK, now ask for the proper length */
2732 len = data.length;
2735 * We're only interested in the first three bytes, actually.
2736 * But the data cache page is defined for the first 20.
2738 if (len < 3)
2739 goto bad_sense;
2740 else if (len > SD_BUF_SIZE) {
2741 sd_first_printk(KERN_NOTICE, sdkp, "Truncating mode parameter "
2742 "data from %d to %d bytes\n", len, SD_BUF_SIZE);
2743 len = SD_BUF_SIZE;
2745 if (modepage == 0x3F && sdp->use_192_bytes_for_3f)
2746 len = 192;
2748 /* Get the data */
2749 if (len > first_len)
2750 res = sd_do_mode_sense(sdp, dbd, modepage, buffer, len,
2751 &data, &sshdr);
2753 if (scsi_status_is_good(res)) {
2754 int offset = data.header_length + data.block_descriptor_length;
2756 while (offset < len) {
2757 u8 page_code = buffer[offset] & 0x3F;
2758 u8 spf = buffer[offset] & 0x40;
2760 if (page_code == 8 || page_code == 6) {
2761 /* We're interested only in the first 3 bytes.
2763 if (len - offset <= 2) {
2764 sd_first_printk(KERN_ERR, sdkp,
2765 "Incomplete mode parameter "
2766 "data\n");
2767 goto defaults;
2768 } else {
2769 modepage = page_code;
2770 goto Page_found;
2772 } else {
2773 /* Go to the next page */
2774 if (spf && len - offset > 3)
2775 offset += 4 + (buffer[offset+2] << 8) +
2776 buffer[offset+3];
2777 else if (!spf && len - offset > 1)
2778 offset += 2 + buffer[offset+1];
2779 else {
2780 sd_first_printk(KERN_ERR, sdkp,
2781 "Incomplete mode "
2782 "parameter data\n");
2783 goto defaults;
2788 sd_first_printk(KERN_ERR, sdkp, "No Caching mode page found\n");
2789 goto defaults;
2791 Page_found:
2792 if (modepage == 8) {
2793 sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
2794 sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
2795 } else {
2796 sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
2797 sdkp->RCD = 0;
2800 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
2801 if (sdp->broken_fua) {
2802 sd_first_printk(KERN_NOTICE, sdkp, "Disabling FUA\n");
2803 sdkp->DPOFUA = 0;
2804 } else if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw &&
2805 !sdkp->device->use_16_for_rw) {
2806 sd_first_printk(KERN_NOTICE, sdkp,
2807 "Uses READ/WRITE(6), disabling FUA\n");
2808 sdkp->DPOFUA = 0;
2811 /* No cache flush allowed for write protected devices */
2812 if (sdkp->WCE && sdkp->write_prot)
2813 sdkp->WCE = 0;
2815 if (sdkp->first_scan || old_wce != sdkp->WCE ||
2816 old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
2817 sd_printk(KERN_NOTICE, sdkp,
2818 "Write cache: %s, read cache: %s, %s\n",
2819 sdkp->WCE ? "enabled" : "disabled",
2820 sdkp->RCD ? "disabled" : "enabled",
2821 sdkp->DPOFUA ? "supports DPO and FUA"
2822 : "doesn't support DPO or FUA");
2824 return;
2827 bad_sense:
2828 if (scsi_sense_valid(&sshdr) &&
2829 sshdr.sense_key == ILLEGAL_REQUEST &&
2830 sshdr.asc == 0x24 && sshdr.ascq == 0x0)
2831 /* Invalid field in CDB */
2832 sd_first_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
2833 else
2834 sd_first_printk(KERN_ERR, sdkp,
2835 "Asking for cache data failed\n");
2837 defaults:
2838 if (sdp->wce_default_on) {
2839 sd_first_printk(KERN_NOTICE, sdkp,
2840 "Assuming drive cache: write back\n");
2841 sdkp->WCE = 1;
2842 } else {
2843 sd_first_printk(KERN_ERR, sdkp,
2844 "Assuming drive cache: write through\n");
2845 sdkp->WCE = 0;
2847 sdkp->RCD = 0;
2848 sdkp->DPOFUA = 0;
2852 * The ATO bit indicates whether the DIF application tag is available
2853 * for use by the operating system.
2855 static void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
2857 int res, offset;
2858 struct scsi_device *sdp = sdkp->device;
2859 struct scsi_mode_data data;
2860 struct scsi_sense_hdr sshdr;
2862 if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
2863 return;
2865 if (sdkp->protection_type == 0)
2866 return;
2868 res = scsi_mode_sense(sdp, 1, 0x0a, buffer, 36, SD_TIMEOUT,
2869 SD_MAX_RETRIES, &data, &sshdr);
2871 if (!scsi_status_is_good(res) || !data.header_length ||
2872 data.length < 6) {
2873 sd_first_printk(KERN_WARNING, sdkp,
2874 "getting Control mode page failed, assume no ATO\n");
2876 if (scsi_sense_valid(&sshdr))
2877 sd_print_sense_hdr(sdkp, &sshdr);
2879 return;
2882 offset = data.header_length + data.block_descriptor_length;
2884 if ((buffer[offset] & 0x3f) != 0x0a) {
2885 sd_first_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
2886 return;
2889 if ((buffer[offset + 5] & 0x80) == 0)
2890 return;
2892 sdkp->ATO = 1;
2894 return;
2898 * sd_read_block_limits - Query disk device for preferred I/O sizes.
2899 * @sdkp: disk to query
2901 static void sd_read_block_limits(struct scsi_disk *sdkp)
2903 unsigned int sector_sz = sdkp->device->sector_size;
2904 const int vpd_len = 64;
2905 unsigned char *buffer = kmalloc(vpd_len, GFP_KERNEL);
2907 if (!buffer ||
2908 /* Block Limits VPD */
2909 scsi_get_vpd_page(sdkp->device, 0xb0, buffer, vpd_len))
2910 goto out;
2912 blk_queue_io_min(sdkp->disk->queue,
2913 get_unaligned_be16(&buffer[6]) * sector_sz);
2915 sdkp->max_xfer_blocks = get_unaligned_be32(&buffer[8]);
2916 sdkp->opt_xfer_blocks = get_unaligned_be32(&buffer[12]);
2918 if (buffer[3] == 0x3c) {
2919 unsigned int lba_count, desc_count;
2921 sdkp->max_ws_blocks = (u32)get_unaligned_be64(&buffer[36]);
2923 if (!sdkp->lbpme)
2924 goto out;
2926 lba_count = get_unaligned_be32(&buffer[20]);
2927 desc_count = get_unaligned_be32(&buffer[24]);
2929 if (lba_count && desc_count)
2930 sdkp->max_unmap_blocks = lba_count;
2932 sdkp->unmap_granularity = get_unaligned_be32(&buffer[28]);
2934 if (buffer[32] & 0x80)
2935 sdkp->unmap_alignment =
2936 get_unaligned_be32(&buffer[32]) & ~(1 << 31);
2938 if (!sdkp->lbpvpd) { /* LBP VPD page not provided */
2940 if (sdkp->max_unmap_blocks)
2941 sd_config_discard(sdkp, SD_LBP_UNMAP);
2942 else
2943 sd_config_discard(sdkp, SD_LBP_WS16);
2945 } else { /* LBP VPD page tells us what to use */
2946 if (sdkp->lbpu && sdkp->max_unmap_blocks)
2947 sd_config_discard(sdkp, SD_LBP_UNMAP);
2948 else if (sdkp->lbpws)
2949 sd_config_discard(sdkp, SD_LBP_WS16);
2950 else if (sdkp->lbpws10)
2951 sd_config_discard(sdkp, SD_LBP_WS10);
2952 else
2953 sd_config_discard(sdkp, SD_LBP_DISABLE);
2957 out:
2958 kfree(buffer);
2962 * sd_read_block_characteristics - Query block dev. characteristics
2963 * @sdkp: disk to query
2965 static void sd_read_block_characteristics(struct scsi_disk *sdkp)
2967 struct request_queue *q = sdkp->disk->queue;
2968 unsigned char *buffer;
2969 u16 rot;
2970 const int vpd_len = 64;
2972 buffer = kmalloc(vpd_len, GFP_KERNEL);
2974 if (!buffer ||
2975 /* Block Device Characteristics VPD */
2976 scsi_get_vpd_page(sdkp->device, 0xb1, buffer, vpd_len))
2977 goto out;
2979 rot = get_unaligned_be16(&buffer[4]);
2981 if (rot == 1) {
2982 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
2983 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, q);
2986 if (sdkp->device->type == TYPE_ZBC) {
2987 /* Host-managed */
2988 q->limits.zoned = BLK_ZONED_HM;
2989 } else {
2990 sdkp->zoned = (buffer[8] >> 4) & 3;
2991 if (sdkp->zoned == 1)
2992 /* Host-aware */
2993 q->limits.zoned = BLK_ZONED_HA;
2994 else
2996 * Treat drive-managed devices as
2997 * regular block devices.
2999 q->limits.zoned = BLK_ZONED_NONE;
3001 if (blk_queue_is_zoned(q) && sdkp->first_scan)
3002 sd_printk(KERN_NOTICE, sdkp, "Host-%s zoned block device\n",
3003 q->limits.zoned == BLK_ZONED_HM ? "managed" : "aware");
3005 out:
3006 kfree(buffer);
3010 * sd_read_block_provisioning - Query provisioning VPD page
3011 * @sdkp: disk to query
3013 static void sd_read_block_provisioning(struct scsi_disk *sdkp)
3015 unsigned char *buffer;
3016 const int vpd_len = 8;
3018 if (sdkp->lbpme == 0)
3019 return;
3021 buffer = kmalloc(vpd_len, GFP_KERNEL);
3023 if (!buffer || scsi_get_vpd_page(sdkp->device, 0xb2, buffer, vpd_len))
3024 goto out;
3026 sdkp->lbpvpd = 1;
3027 sdkp->lbpu = (buffer[5] >> 7) & 1; /* UNMAP */
3028 sdkp->lbpws = (buffer[5] >> 6) & 1; /* WRITE SAME(16) with UNMAP */
3029 sdkp->lbpws10 = (buffer[5] >> 5) & 1; /* WRITE SAME(10) with UNMAP */
3031 out:
3032 kfree(buffer);
3035 static void sd_read_write_same(struct scsi_disk *sdkp, unsigned char *buffer)
3037 struct scsi_device *sdev = sdkp->device;
3039 if (sdev->host->no_write_same) {
3040 sdev->no_write_same = 1;
3042 return;
3045 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, INQUIRY) < 0) {
3046 /* too large values might cause issues with arcmsr */
3047 int vpd_buf_len = 64;
3049 sdev->no_report_opcodes = 1;
3051 /* Disable WRITE SAME if REPORT SUPPORTED OPERATION
3052 * CODES is unsupported and the device has an ATA
3053 * Information VPD page (SAT).
3055 if (!scsi_get_vpd_page(sdev, 0x89, buffer, vpd_buf_len))
3056 sdev->no_write_same = 1;
3059 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME_16) == 1)
3060 sdkp->ws16 = 1;
3062 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME) == 1)
3063 sdkp->ws10 = 1;
3066 static void sd_read_security(struct scsi_disk *sdkp, unsigned char *buffer)
3068 struct scsi_device *sdev = sdkp->device;
3070 if (!sdev->security_supported)
3071 return;
3073 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3074 SECURITY_PROTOCOL_IN) == 1 &&
3075 scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3076 SECURITY_PROTOCOL_OUT) == 1)
3077 sdkp->security = 1;
3081 * Determine the device's preferred I/O size for reads and writes
3082 * unless the reported value is unreasonably small, large, not a
3083 * multiple of the physical block size, or simply garbage.
3085 static bool sd_validate_opt_xfer_size(struct scsi_disk *sdkp,
3086 unsigned int dev_max)
3088 struct scsi_device *sdp = sdkp->device;
3089 unsigned int opt_xfer_bytes =
3090 logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
3092 if (sdkp->opt_xfer_blocks == 0)
3093 return false;
3095 if (sdkp->opt_xfer_blocks > dev_max) {
3096 sd_first_printk(KERN_WARNING, sdkp,
3097 "Optimal transfer size %u logical blocks " \
3098 "> dev_max (%u logical blocks)\n",
3099 sdkp->opt_xfer_blocks, dev_max);
3100 return false;
3103 if (sdkp->opt_xfer_blocks > SD_DEF_XFER_BLOCKS) {
3104 sd_first_printk(KERN_WARNING, sdkp,
3105 "Optimal transfer size %u logical blocks " \
3106 "> sd driver limit (%u logical blocks)\n",
3107 sdkp->opt_xfer_blocks, SD_DEF_XFER_BLOCKS);
3108 return false;
3111 if (opt_xfer_bytes < PAGE_SIZE) {
3112 sd_first_printk(KERN_WARNING, sdkp,
3113 "Optimal transfer size %u bytes < " \
3114 "PAGE_SIZE (%u bytes)\n",
3115 opt_xfer_bytes, (unsigned int)PAGE_SIZE);
3116 return false;
3119 if (opt_xfer_bytes & (sdkp->physical_block_size - 1)) {
3120 sd_first_printk(KERN_WARNING, sdkp,
3121 "Optimal transfer size %u bytes not a " \
3122 "multiple of physical block size (%u bytes)\n",
3123 opt_xfer_bytes, sdkp->physical_block_size);
3124 return false;
3127 sd_first_printk(KERN_INFO, sdkp, "Optimal transfer size %u bytes\n",
3128 opt_xfer_bytes);
3129 return true;
3133 * sd_revalidate_disk - called the first time a new disk is seen,
3134 * performs disk spin up, read_capacity, etc.
3135 * @disk: struct gendisk we care about
3137 static int sd_revalidate_disk(struct gendisk *disk)
3139 struct scsi_disk *sdkp = scsi_disk(disk);
3140 struct scsi_device *sdp = sdkp->device;
3141 struct request_queue *q = sdkp->disk->queue;
3142 sector_t old_capacity = sdkp->capacity;
3143 unsigned char *buffer;
3144 unsigned int dev_max, rw_max;
3146 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
3147 "sd_revalidate_disk\n"));
3150 * If the device is offline, don't try and read capacity or any
3151 * of the other niceties.
3153 if (!scsi_device_online(sdp))
3154 goto out;
3156 buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
3157 if (!buffer) {
3158 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
3159 "allocation failure.\n");
3160 goto out;
3163 sd_spinup_disk(sdkp);
3166 * Without media there is no reason to ask; moreover, some devices
3167 * react badly if we do.
3169 if (sdkp->media_present) {
3170 sd_read_capacity(sdkp, buffer);
3173 * set the default to rotational. All non-rotational devices
3174 * support the block characteristics VPD page, which will
3175 * cause this to be updated correctly and any device which
3176 * doesn't support it should be treated as rotational.
3178 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
3179 blk_queue_flag_set(QUEUE_FLAG_ADD_RANDOM, q);
3181 if (scsi_device_supports_vpd(sdp)) {
3182 sd_read_block_provisioning(sdkp);
3183 sd_read_block_limits(sdkp);
3184 sd_read_block_characteristics(sdkp);
3185 sd_zbc_read_zones(sdkp, buffer);
3188 sd_print_capacity(sdkp, old_capacity);
3190 sd_read_write_protect_flag(sdkp, buffer);
3191 sd_read_cache_type(sdkp, buffer);
3192 sd_read_app_tag_own(sdkp, buffer);
3193 sd_read_write_same(sdkp, buffer);
3194 sd_read_security(sdkp, buffer);
3198 * We now have all cache related info, determine how we deal
3199 * with flush requests.
3201 sd_set_flush_flag(sdkp);
3203 /* Initial block count limit based on CDB TRANSFER LENGTH field size. */
3204 dev_max = sdp->use_16_for_rw ? SD_MAX_XFER_BLOCKS : SD_DEF_XFER_BLOCKS;
3206 /* Some devices report a maximum block count for READ/WRITE requests. */
3207 dev_max = min_not_zero(dev_max, sdkp->max_xfer_blocks);
3208 q->limits.max_dev_sectors = logical_to_sectors(sdp, dev_max);
3210 if (sd_validate_opt_xfer_size(sdkp, dev_max)) {
3211 q->limits.io_opt = logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
3212 rw_max = logical_to_sectors(sdp, sdkp->opt_xfer_blocks);
3213 } else {
3214 q->limits.io_opt = 0;
3215 rw_max = min_not_zero(logical_to_sectors(sdp, dev_max),
3216 (sector_t)BLK_DEF_MAX_SECTORS);
3219 /* Do not exceed controller limit */
3220 rw_max = min(rw_max, queue_max_hw_sectors(q));
3223 * Only update max_sectors if previously unset or if the current value
3224 * exceeds the capabilities of the hardware.
3226 if (sdkp->first_scan ||
3227 q->limits.max_sectors > q->limits.max_dev_sectors ||
3228 q->limits.max_sectors > q->limits.max_hw_sectors)
3229 q->limits.max_sectors = rw_max;
3231 sdkp->first_scan = 0;
3233 set_capacity(disk, logical_to_sectors(sdp, sdkp->capacity));
3234 sd_config_write_same(sdkp);
3235 kfree(buffer);
3237 out:
3238 return 0;
3242 * sd_unlock_native_capacity - unlock native capacity
3243 * @disk: struct gendisk to set capacity for
3245 * Block layer calls this function if it detects that partitions
3246 * on @disk reach beyond the end of the device. If the SCSI host
3247 * implements ->unlock_native_capacity() method, it's invoked to
3248 * give it a chance to adjust the device capacity.
3250 * CONTEXT:
3251 * Defined by block layer. Might sleep.
3253 static void sd_unlock_native_capacity(struct gendisk *disk)
3255 struct scsi_device *sdev = scsi_disk(disk)->device;
3257 if (sdev->host->hostt->unlock_native_capacity)
3258 sdev->host->hostt->unlock_native_capacity(sdev);
3262 * sd_format_disk_name - format disk name
3263 * @prefix: name prefix - ie. "sd" for SCSI disks
3264 * @index: index of the disk to format name for
3265 * @buf: output buffer
3266 * @buflen: length of the output buffer
3268 * SCSI disk names starts at sda. The 26th device is sdz and the
3269 * 27th is sdaa. The last one for two lettered suffix is sdzz
3270 * which is followed by sdaaa.
3272 * This is basically 26 base counting with one extra 'nil' entry
3273 * at the beginning from the second digit on and can be
3274 * determined using similar method as 26 base conversion with the
3275 * index shifted -1 after each digit is computed.
3277 * CONTEXT:
3278 * Don't care.
3280 * RETURNS:
3281 * 0 on success, -errno on failure.
3283 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
3285 const int base = 'z' - 'a' + 1;
3286 char *begin = buf + strlen(prefix);
3287 char *end = buf + buflen;
3288 char *p;
3289 int unit;
3291 p = end - 1;
3292 *p = '\0';
3293 unit = base;
3294 do {
3295 if (p == begin)
3296 return -EINVAL;
3297 *--p = 'a' + (index % unit);
3298 index = (index / unit) - 1;
3299 } while (index >= 0);
3301 memmove(begin, p, end - p);
3302 memcpy(buf, prefix, strlen(prefix));
3304 return 0;
3308 * The asynchronous part of sd_probe
3310 static void sd_probe_async(void *data, async_cookie_t cookie)
3312 struct scsi_disk *sdkp = data;
3313 struct scsi_device *sdp;
3314 struct gendisk *gd;
3315 u32 index;
3316 struct device *dev;
3318 sdp = sdkp->device;
3319 gd = sdkp->disk;
3320 index = sdkp->index;
3321 dev = &sdp->sdev_gendev;
3323 gd->major = sd_major((index & 0xf0) >> 4);
3324 gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
3326 gd->fops = &sd_fops;
3327 gd->private_data = &sdkp->driver;
3328 gd->queue = sdkp->device->request_queue;
3330 /* defaults, until the device tells us otherwise */
3331 sdp->sector_size = 512;
3332 sdkp->capacity = 0;
3333 sdkp->media_present = 1;
3334 sdkp->write_prot = 0;
3335 sdkp->cache_override = 0;
3336 sdkp->WCE = 0;
3337 sdkp->RCD = 0;
3338 sdkp->ATO = 0;
3339 sdkp->first_scan = 1;
3340 sdkp->max_medium_access_timeouts = SD_MAX_MEDIUM_TIMEOUTS;
3342 sd_revalidate_disk(gd);
3344 gd->flags = GENHD_FL_EXT_DEVT;
3345 if (sdp->removable) {
3346 gd->flags |= GENHD_FL_REMOVABLE;
3347 gd->events |= DISK_EVENT_MEDIA_CHANGE;
3350 blk_pm_runtime_init(sdp->request_queue, dev);
3351 device_add_disk(dev, gd);
3352 if (sdkp->capacity)
3353 sd_dif_config_host(sdkp);
3355 sd_revalidate_disk(gd);
3357 if (sdkp->security) {
3358 sdkp->opal_dev = init_opal_dev(sdp, &sd_sec_submit);
3359 if (sdkp->opal_dev)
3360 sd_printk(KERN_NOTICE, sdkp, "supports TCG Opal\n");
3363 sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
3364 sdp->removable ? "removable " : "");
3365 scsi_autopm_put_device(sdp);
3366 put_device(&sdkp->dev);
3370 * sd_probe - called during driver initialization and whenever a
3371 * new scsi device is attached to the system. It is called once
3372 * for each scsi device (not just disks) present.
3373 * @dev: pointer to device object
3375 * Returns 0 if successful (or not interested in this scsi device
3376 * (e.g. scanner)); 1 when there is an error.
3378 * Note: this function is invoked from the scsi mid-level.
3379 * This function sets up the mapping between a given
3380 * <host,channel,id,lun> (found in sdp) and new device name
3381 * (e.g. /dev/sda). More precisely it is the block device major
3382 * and minor number that is chosen here.
3384 * Assume sd_probe is not re-entrant (for time being)
3385 * Also think about sd_probe() and sd_remove() running coincidentally.
3387 static int sd_probe(struct device *dev)
3389 struct scsi_device *sdp = to_scsi_device(dev);
3390 struct scsi_disk *sdkp;
3391 struct gendisk *gd;
3392 int index;
3393 int error;
3395 scsi_autopm_get_device(sdp);
3396 error = -ENODEV;
3397 if (sdp->type != TYPE_DISK &&
3398 sdp->type != TYPE_ZBC &&
3399 sdp->type != TYPE_MOD &&
3400 sdp->type != TYPE_RBC)
3401 goto out;
3403 #ifndef CONFIG_BLK_DEV_ZONED
3404 if (sdp->type == TYPE_ZBC)
3405 goto out;
3406 #endif
3407 SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
3408 "sd_probe\n"));
3410 error = -ENOMEM;
3411 sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
3412 if (!sdkp)
3413 goto out;
3415 gd = alloc_disk(SD_MINORS);
3416 if (!gd)
3417 goto out_free;
3419 index = ida_alloc(&sd_index_ida, GFP_KERNEL);
3420 if (index < 0) {
3421 sdev_printk(KERN_WARNING, sdp, "sd_probe: memory exhausted.\n");
3422 goto out_put;
3425 error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
3426 if (error) {
3427 sdev_printk(KERN_WARNING, sdp, "SCSI disk (sd) name length exceeded.\n");
3428 goto out_free_index;
3431 sdkp->device = sdp;
3432 sdkp->driver = &sd_template;
3433 sdkp->disk = gd;
3434 sdkp->index = index;
3435 atomic_set(&sdkp->openers, 0);
3436 atomic_set(&sdkp->device->ioerr_cnt, 0);
3438 if (!sdp->request_queue->rq_timeout) {
3439 if (sdp->type != TYPE_MOD)
3440 blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
3441 else
3442 blk_queue_rq_timeout(sdp->request_queue,
3443 SD_MOD_TIMEOUT);
3446 device_initialize(&sdkp->dev);
3447 sdkp->dev.parent = dev;
3448 sdkp->dev.class = &sd_disk_class;
3449 dev_set_name(&sdkp->dev, "%s", dev_name(dev));
3451 error = device_add(&sdkp->dev);
3452 if (error)
3453 goto out_free_index;
3455 get_device(dev);
3456 dev_set_drvdata(dev, sdkp);
3458 get_device(&sdkp->dev); /* prevent release before async_schedule */
3459 async_schedule_domain(sd_probe_async, sdkp, &scsi_sd_probe_domain);
3461 return 0;
3463 out_free_index:
3464 ida_free(&sd_index_ida, index);
3465 out_put:
3466 put_disk(gd);
3467 out_free:
3468 kfree(sdkp);
3469 out:
3470 scsi_autopm_put_device(sdp);
3471 return error;
3475 * sd_remove - called whenever a scsi disk (previously recognized by
3476 * sd_probe) is detached from the system. It is called (potentially
3477 * multiple times) during sd module unload.
3478 * @dev: pointer to device object
3480 * Note: this function is invoked from the scsi mid-level.
3481 * This function potentially frees up a device name (e.g. /dev/sdc)
3482 * that could be re-used by a subsequent sd_probe().
3483 * This function is not called when the built-in sd driver is "exit-ed".
3485 static int sd_remove(struct device *dev)
3487 struct scsi_disk *sdkp;
3488 dev_t devt;
3490 sdkp = dev_get_drvdata(dev);
3491 devt = disk_devt(sdkp->disk);
3492 scsi_autopm_get_device(sdkp->device);
3494 async_synchronize_full_domain(&scsi_sd_pm_domain);
3495 async_synchronize_full_domain(&scsi_sd_probe_domain);
3496 device_del(&sdkp->dev);
3497 del_gendisk(sdkp->disk);
3498 sd_shutdown(dev);
3500 sd_zbc_remove(sdkp);
3502 free_opal_dev(sdkp->opal_dev);
3504 blk_register_region(devt, SD_MINORS, NULL,
3505 sd_default_probe, NULL, NULL);
3507 mutex_lock(&sd_ref_mutex);
3508 dev_set_drvdata(dev, NULL);
3509 put_device(&sdkp->dev);
3510 mutex_unlock(&sd_ref_mutex);
3512 return 0;
3516 * scsi_disk_release - Called to free the scsi_disk structure
3517 * @dev: pointer to embedded class device
3519 * sd_ref_mutex must be held entering this routine. Because it is
3520 * called on last put, you should always use the scsi_disk_get()
3521 * scsi_disk_put() helpers which manipulate the semaphore directly
3522 * and never do a direct put_device.
3524 static void scsi_disk_release(struct device *dev)
3526 struct scsi_disk *sdkp = to_scsi_disk(dev);
3527 struct gendisk *disk = sdkp->disk;
3528 struct request_queue *q = disk->queue;
3530 ida_free(&sd_index_ida, sdkp->index);
3533 * Wait until all requests that are in progress have completed.
3534 * This is necessary to avoid that e.g. scsi_end_request() crashes
3535 * due to clearing the disk->private_data pointer. Wait from inside
3536 * scsi_disk_release() instead of from sd_release() to avoid that
3537 * freezing and unfreezing the request queue affects user space I/O
3538 * in case multiple processes open a /dev/sd... node concurrently.
3540 blk_mq_freeze_queue(q);
3541 blk_mq_unfreeze_queue(q);
3543 disk->private_data = NULL;
3544 put_disk(disk);
3545 put_device(&sdkp->device->sdev_gendev);
3547 kfree(sdkp);
3550 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
3552 unsigned char cmd[6] = { START_STOP }; /* START_VALID */
3553 struct scsi_sense_hdr sshdr;
3554 struct scsi_device *sdp = sdkp->device;
3555 int res;
3557 if (start)
3558 cmd[4] |= 1; /* START */
3560 if (sdp->start_stop_pwr_cond)
3561 cmd[4] |= start ? 1 << 4 : 3 << 4; /* Active or Standby */
3563 if (!scsi_device_online(sdp))
3564 return -ENODEV;
3566 res = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
3567 SD_TIMEOUT, SD_MAX_RETRIES, 0, RQF_PM, NULL);
3568 if (res) {
3569 sd_print_result(sdkp, "Start/Stop Unit failed", res);
3570 if (driver_byte(res) == DRIVER_SENSE)
3571 sd_print_sense_hdr(sdkp, &sshdr);
3572 if (scsi_sense_valid(&sshdr) &&
3573 /* 0x3a is medium not present */
3574 sshdr.asc == 0x3a)
3575 res = 0;
3578 /* SCSI error codes must not go to the generic layer */
3579 if (res)
3580 return -EIO;
3582 return 0;
3586 * Send a SYNCHRONIZE CACHE instruction down to the device through
3587 * the normal SCSI command structure. Wait for the command to
3588 * complete.
3590 static void sd_shutdown(struct device *dev)
3592 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3594 if (!sdkp)
3595 return; /* this can happen */
3597 if (pm_runtime_suspended(dev))
3598 return;
3600 if (sdkp->WCE && sdkp->media_present) {
3601 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
3602 sd_sync_cache(sdkp, NULL);
3605 if (system_state != SYSTEM_RESTART && sdkp->device->manage_start_stop) {
3606 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
3607 sd_start_stop_device(sdkp, 0);
3611 static int sd_suspend_common(struct device *dev, bool ignore_stop_errors)
3613 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3614 struct scsi_sense_hdr sshdr;
3615 int ret = 0;
3617 if (!sdkp) /* E.g.: runtime suspend following sd_remove() */
3618 return 0;
3620 if (sdkp->WCE && sdkp->media_present) {
3621 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
3622 ret = sd_sync_cache(sdkp, &sshdr);
3624 if (ret) {
3625 /* ignore OFFLINE device */
3626 if (ret == -ENODEV)
3627 return 0;
3629 if (!scsi_sense_valid(&sshdr) ||
3630 sshdr.sense_key != ILLEGAL_REQUEST)
3631 return ret;
3634 * sshdr.sense_key == ILLEGAL_REQUEST means this drive
3635 * doesn't support sync. There's not much to do and
3636 * suspend shouldn't fail.
3638 ret = 0;
3642 if (sdkp->device->manage_start_stop) {
3643 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
3644 /* an error is not worth aborting a system sleep */
3645 ret = sd_start_stop_device(sdkp, 0);
3646 if (ignore_stop_errors)
3647 ret = 0;
3650 return ret;
3653 static int sd_suspend_system(struct device *dev)
3655 return sd_suspend_common(dev, true);
3658 static int sd_suspend_runtime(struct device *dev)
3660 return sd_suspend_common(dev, false);
3663 static int sd_resume(struct device *dev)
3665 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3666 int ret;
3668 if (!sdkp) /* E.g.: runtime resume at the start of sd_probe() */
3669 return 0;
3671 if (!sdkp->device->manage_start_stop)
3672 return 0;
3674 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
3675 ret = sd_start_stop_device(sdkp, 1);
3676 if (!ret)
3677 opal_unlock_from_suspend(sdkp->opal_dev);
3678 return ret;
3682 * init_sd - entry point for this driver (both when built in or when
3683 * a module).
3685 * Note: this function registers this driver with the scsi mid-level.
3687 static int __init init_sd(void)
3689 int majors = 0, i, err;
3691 SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
3693 for (i = 0; i < SD_MAJORS; i++) {
3694 if (register_blkdev(sd_major(i), "sd") != 0)
3695 continue;
3696 majors++;
3697 blk_register_region(sd_major(i), SD_MINORS, NULL,
3698 sd_default_probe, NULL, NULL);
3701 if (!majors)
3702 return -ENODEV;
3704 err = class_register(&sd_disk_class);
3705 if (err)
3706 goto err_out;
3708 sd_cdb_cache = kmem_cache_create("sd_ext_cdb", SD_EXT_CDB_SIZE,
3709 0, 0, NULL);
3710 if (!sd_cdb_cache) {
3711 printk(KERN_ERR "sd: can't init extended cdb cache\n");
3712 err = -ENOMEM;
3713 goto err_out_class;
3716 sd_cdb_pool = mempool_create_slab_pool(SD_MEMPOOL_SIZE, sd_cdb_cache);
3717 if (!sd_cdb_pool) {
3718 printk(KERN_ERR "sd: can't init extended cdb pool\n");
3719 err = -ENOMEM;
3720 goto err_out_cache;
3723 sd_page_pool = mempool_create_page_pool(SD_MEMPOOL_SIZE, 0);
3724 if (!sd_page_pool) {
3725 printk(KERN_ERR "sd: can't init discard page pool\n");
3726 err = -ENOMEM;
3727 goto err_out_ppool;
3730 err = scsi_register_driver(&sd_template.gendrv);
3731 if (err)
3732 goto err_out_driver;
3734 return 0;
3736 err_out_driver:
3737 mempool_destroy(sd_page_pool);
3739 err_out_ppool:
3740 mempool_destroy(sd_cdb_pool);
3742 err_out_cache:
3743 kmem_cache_destroy(sd_cdb_cache);
3745 err_out_class:
3746 class_unregister(&sd_disk_class);
3747 err_out:
3748 for (i = 0; i < SD_MAJORS; i++)
3749 unregister_blkdev(sd_major(i), "sd");
3750 return err;
3754 * exit_sd - exit point for this driver (when it is a module).
3756 * Note: this function unregisters this driver from the scsi mid-level.
3758 static void __exit exit_sd(void)
3760 int i;
3762 SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
3764 scsi_unregister_driver(&sd_template.gendrv);
3765 mempool_destroy(sd_cdb_pool);
3766 mempool_destroy(sd_page_pool);
3767 kmem_cache_destroy(sd_cdb_cache);
3769 class_unregister(&sd_disk_class);
3771 for (i = 0; i < SD_MAJORS; i++) {
3772 blk_unregister_region(sd_major(i), SD_MINORS);
3773 unregister_blkdev(sd_major(i), "sd");
3777 module_init(init_sd);
3778 module_exit(exit_sd);
3780 static void sd_print_sense_hdr(struct scsi_disk *sdkp,
3781 struct scsi_sense_hdr *sshdr)
3783 scsi_print_sense_hdr(sdkp->device,
3784 sdkp->disk ? sdkp->disk->disk_name : NULL, sshdr);
3787 static void sd_print_result(const struct scsi_disk *sdkp, const char *msg,
3788 int result)
3790 const char *hb_string = scsi_hostbyte_string(result);
3791 const char *db_string = scsi_driverbyte_string(result);
3793 if (hb_string || db_string)
3794 sd_printk(KERN_INFO, sdkp,
3795 "%s: Result: hostbyte=%s driverbyte=%s\n", msg,
3796 hb_string ? hb_string : "invalid",
3797 db_string ? db_string : "invalid");
3798 else
3799 sd_printk(KERN_INFO, sdkp,
3800 "%s: Result: hostbyte=0x%02x driverbyte=0x%02x\n",
3801 msg, host_byte(result), driver_byte(result));