1 /*
2 * sd.c Copyright (C) 1992 Drew Eckhardt
3 * Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
4 *
5 * Linux scsi disk driver
6 * Initial versions: Drew Eckhardt
7 * Subsequent revisions: Eric Youngdale
8 * Modification history:
9 * - Drew Eckhardt <drew@colorado.edu> original
10 * - Eric Youngdale <eric@andante.org> add scatter-gather, multiple
11 * outstanding request, and other enhancements.
12 * Support loadable low-level scsi drivers.
13 * - Jirka Hanika <geo@ff.cuni.cz> support more scsi disks using
14 * eight major numbers.
15 * - Richard Gooch <rgooch@atnf.csiro.au> support devfs.
16 * - Torben Mathiasen <tmm@image.dk> Resource allocation fixes in
17 * sd_init and cleanups.
18 * - Alex Davis <letmein@erols.com> Fix problem where partition info
19 * not being read in sd_open. Fix problem where removable media
20 * could be ejected after sd_open.
21 * - Douglas Gilbert <dgilbert@interlog.com> cleanup for lk 2.5.x
22 * - Badari Pulavarty <pbadari@us.ibm.com>, Matthew Wilcox
23 * <willy@debian.org>, Kurt Garloff <garloff@suse.de>:
24 * Support 32k/1M disks.
25 *
26 * Logging policy (needs CONFIG_SCSI_LOGGING defined):
27 * - setting up transfer: SCSI_LOG_HLQUEUE levels 1 and 2
28 * - end of transfer (bh + scsi_lib): SCSI_LOG_HLCOMPLETE level 1
29 * - entering sd_ioctl: SCSI_LOG_IOCTL level 1
30 * - entering other commands: SCSI_LOG_HLQUEUE level 3
31 * Note: when the logging level is set by the user, it must be greater
32 * than the level indicated above to trigger output.
33 */
34
35 #include <linux/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/pm_runtime.h>
54 #include <linux/pr.h>
55 #include <asm/uaccess.h>
56 #include <asm/unaligned.h>
57
58 #include <scsi/scsi.h>
59 #include <scsi/scsi_cmnd.h>
60 #include <scsi/scsi_dbg.h>
61 #include <scsi/scsi_device.h>
62 #include <scsi/scsi_driver.h>
63 #include <scsi/scsi_eh.h>
64 #include <scsi/scsi_host.h>
65 #include <scsi/scsi_ioctl.h>
66 #include <scsi/scsicam.h>
67
68 #include "sd.h"
69 #include "scsi_priv.h"
70 #include "scsi_logging.h"
71
72 MODULE_AUTHOR("Eric Youngdale");
73 MODULE_DESCRIPTION("SCSI disk (sd) driver");
74 MODULE_LICENSE("GPL");
75
76 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
77 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
78 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
79 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
80 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
81 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
82 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
88 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
89 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
90 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
91 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
92 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
93 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
94 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
95
96 #if !defined(CONFIG_DEBUG_BLOCK_EXT_DEVT)
97 #define SD_MINORS 16
98 #else
99 #define SD_MINORS 0
100 #endif
101
102 static void sd_config_discard(struct scsi_disk *, unsigned int);
103 static void sd_config_write_same(struct scsi_disk *);
104 static int sd_revalidate_disk(struct gendisk *);
105 static void sd_unlock_native_capacity(struct gendisk *disk);
106 static int sd_probe(struct device *);
107 static int sd_remove(struct device *);
108 static void sd_shutdown(struct device *);
109 static int sd_suspend_system(struct device *);
110 static int sd_suspend_runtime(struct device *);
111 static int sd_resume(struct device *);
112 static void sd_rescan(struct device *);
113 static int sd_init_command(struct scsi_cmnd *SCpnt);
114 static void sd_uninit_command(struct scsi_cmnd *SCpnt);
115 static int sd_done(struct scsi_cmnd *);
116 static int sd_eh_action(struct scsi_cmnd *, int);
117 static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer);
118 static void scsi_disk_release(struct device *cdev);
119 static void sd_print_sense_hdr(struct scsi_disk *, struct scsi_sense_hdr *);
120 static void sd_print_result(const struct scsi_disk *, const char *, int);
121
122 static DEFINE_SPINLOCK(sd_index_lock);
123 static DEFINE_IDA(sd_index_ida);
124
125 /* This semaphore is used to mediate the 0->1 reference get in the
126 * face of object destruction (i.e. we can't allow a get on an
127 * object after last put) */
128 static DEFINE_MUTEX(sd_ref_mutex);
129
130 static struct kmem_cache *sd_cdb_cache;
131 static mempool_t *sd_cdb_pool;
132
133 static const char *sd_cache_types[] = {
134 "write through", "none", "write back",
135 "write back, no read (daft)"
136 };
137
sd_set_flush_flag(struct scsi_disk * sdkp)138 static void sd_set_flush_flag(struct scsi_disk *sdkp)
139 {
140 unsigned flush = 0;
141
142 if (sdkp->WCE) {
143 flush |= REQ_FLUSH;
144 if (sdkp->DPOFUA)
145 flush |= REQ_FUA;
146 }
147
148 blk_queue_flush(sdkp->disk->queue, flush);
149 }
150
151 static ssize_t
cache_type_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)152 cache_type_store(struct device *dev, struct device_attribute *attr,
153 const char *buf, size_t count)
154 {
155 int i, ct = -1, rcd, wce, sp;
156 struct scsi_disk *sdkp = to_scsi_disk(dev);
157 struct scsi_device *sdp = sdkp->device;
158 char buffer[64];
159 char *buffer_data;
160 struct scsi_mode_data data;
161 struct scsi_sense_hdr sshdr;
162 static const char temp[] = "temporary ";
163 int len;
164
165 if (sdp->type != TYPE_DISK)
166 /* no cache control on RBC devices; theoretically they
167 * can do it, but there's probably so many exceptions
168 * it's not worth the risk */
169 return -EINVAL;
170
171 if (strncmp(buf, temp, sizeof(temp) - 1) == 0) {
172 buf += sizeof(temp) - 1;
173 sdkp->cache_override = 1;
174 } else {
175 sdkp->cache_override = 0;
176 }
177
178 for (i = 0; i < ARRAY_SIZE(sd_cache_types); i++) {
179 len = strlen(sd_cache_types[i]);
180 if (strncmp(sd_cache_types[i], buf, len) == 0 &&
181 buf[len] == '\n') {
182 ct = i;
183 break;
184 }
185 }
186 if (ct < 0)
187 return -EINVAL;
188 rcd = ct & 0x01 ? 1 : 0;
189 wce = (ct & 0x02) && !sdkp->write_prot ? 1 : 0;
190
191 if (sdkp->cache_override) {
192 sdkp->WCE = wce;
193 sdkp->RCD = rcd;
194 sd_set_flush_flag(sdkp);
195 return count;
196 }
197
198 if (scsi_mode_sense(sdp, 0x08, 8, buffer, sizeof(buffer), SD_TIMEOUT,
199 SD_MAX_RETRIES, &data, NULL))
200 return -EINVAL;
201 len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
202 data.block_descriptor_length);
203 buffer_data = buffer + data.header_length +
204 data.block_descriptor_length;
205 buffer_data[2] &= ~0x05;
206 buffer_data[2] |= wce << 2 | rcd;
207 sp = buffer_data[0] & 0x80 ? 1 : 0;
208 buffer_data[0] &= ~0x80;
209
210 /*
211 * Ensure WP, DPOFUA, and RESERVED fields are cleared in
212 * received mode parameter buffer before doing MODE SELECT.
213 */
214 data.device_specific = 0;
215
216 if (scsi_mode_select(sdp, 1, sp, 8, buffer_data, len, SD_TIMEOUT,
217 SD_MAX_RETRIES, &data, &sshdr)) {
218 if (scsi_sense_valid(&sshdr))
219 sd_print_sense_hdr(sdkp, &sshdr);
220 return -EINVAL;
221 }
222 revalidate_disk(sdkp->disk);
223 return count;
224 }
225
226 static ssize_t
manage_start_stop_show(struct device * dev,struct device_attribute * attr,char * buf)227 manage_start_stop_show(struct device *dev, struct device_attribute *attr,
228 char *buf)
229 {
230 struct scsi_disk *sdkp = to_scsi_disk(dev);
231 struct scsi_device *sdp = sdkp->device;
232
233 return snprintf(buf, 20, "%u\n", sdp->manage_start_stop);
234 }
235
236 static ssize_t
manage_start_stop_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)237 manage_start_stop_store(struct device *dev, struct device_attribute *attr,
238 const char *buf, size_t count)
239 {
240 struct scsi_disk *sdkp = to_scsi_disk(dev);
241 struct scsi_device *sdp = sdkp->device;
242 bool v;
243
244 if (!capable(CAP_SYS_ADMIN))
245 return -EACCES;
246
247 if (kstrtobool(buf, &v))
248 return -EINVAL;
249
250 sdp->manage_start_stop = v;
251
252 return count;
253 }
254 static DEVICE_ATTR_RW(manage_start_stop);
255
256 static ssize_t
allow_restart_show(struct device * dev,struct device_attribute * attr,char * buf)257 allow_restart_show(struct device *dev, struct device_attribute *attr, char *buf)
258 {
259 struct scsi_disk *sdkp = to_scsi_disk(dev);
260
261 return snprintf(buf, 40, "%d\n", sdkp->device->allow_restart);
262 }
263
264 static ssize_t
allow_restart_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)265 allow_restart_store(struct device *dev, struct device_attribute *attr,
266 const char *buf, size_t count)
267 {
268 bool v;
269 struct scsi_disk *sdkp = to_scsi_disk(dev);
270 struct scsi_device *sdp = sdkp->device;
271
272 if (!capable(CAP_SYS_ADMIN))
273 return -EACCES;
274
275 if (sdp->type != TYPE_DISK)
276 return -EINVAL;
277
278 if (kstrtobool(buf, &v))
279 return -EINVAL;
280
281 sdp->allow_restart = v;
282
283 return count;
284 }
285 static DEVICE_ATTR_RW(allow_restart);
286
287 static ssize_t
cache_type_show(struct device * dev,struct device_attribute * attr,char * buf)288 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
289 {
290 struct scsi_disk *sdkp = to_scsi_disk(dev);
291 int ct = sdkp->RCD + 2*sdkp->WCE;
292
293 return snprintf(buf, 40, "%s\n", sd_cache_types[ct]);
294 }
295 static DEVICE_ATTR_RW(cache_type);
296
297 static ssize_t
FUA_show(struct device * dev,struct device_attribute * attr,char * buf)298 FUA_show(struct device *dev, struct device_attribute *attr, char *buf)
299 {
300 struct scsi_disk *sdkp = to_scsi_disk(dev);
301
302 return snprintf(buf, 20, "%u\n", sdkp->DPOFUA);
303 }
304 static DEVICE_ATTR_RO(FUA);
305
306 static ssize_t
protection_type_show(struct device * dev,struct device_attribute * attr,char * buf)307 protection_type_show(struct device *dev, struct device_attribute *attr,
308 char *buf)
309 {
310 struct scsi_disk *sdkp = to_scsi_disk(dev);
311
312 return snprintf(buf, 20, "%u\n", sdkp->protection_type);
313 }
314
315 static ssize_t
protection_type_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)316 protection_type_store(struct device *dev, struct device_attribute *attr,
317 const char *buf, size_t count)
318 {
319 struct scsi_disk *sdkp = to_scsi_disk(dev);
320 unsigned int val;
321 int err;
322
323 if (!capable(CAP_SYS_ADMIN))
324 return -EACCES;
325
326 err = kstrtouint(buf, 10, &val);
327
328 if (err)
329 return err;
330
331 if (val >= 0 && val <= SD_DIF_TYPE3_PROTECTION)
332 sdkp->protection_type = val;
333
334 return count;
335 }
336 static DEVICE_ATTR_RW(protection_type);
337
338 static ssize_t
protection_mode_show(struct device * dev,struct device_attribute * attr,char * buf)339 protection_mode_show(struct device *dev, struct device_attribute *attr,
340 char *buf)
341 {
342 struct scsi_disk *sdkp = to_scsi_disk(dev);
343 struct scsi_device *sdp = sdkp->device;
344 unsigned int dif, dix;
345
346 dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
347 dix = scsi_host_dix_capable(sdp->host, sdkp->protection_type);
348
349 if (!dix && scsi_host_dix_capable(sdp->host, SD_DIF_TYPE0_PROTECTION)) {
350 dif = 0;
351 dix = 1;
352 }
353
354 if (!dif && !dix)
355 return snprintf(buf, 20, "none\n");
356
357 return snprintf(buf, 20, "%s%u\n", dix ? "dix" : "dif", dif);
358 }
359 static DEVICE_ATTR_RO(protection_mode);
360
361 static ssize_t
app_tag_own_show(struct device * dev,struct device_attribute * attr,char * buf)362 app_tag_own_show(struct device *dev, struct device_attribute *attr, char *buf)
363 {
364 struct scsi_disk *sdkp = to_scsi_disk(dev);
365
366 return snprintf(buf, 20, "%u\n", sdkp->ATO);
367 }
368 static DEVICE_ATTR_RO(app_tag_own);
369
370 static ssize_t
thin_provisioning_show(struct device * dev,struct device_attribute * attr,char * buf)371 thin_provisioning_show(struct device *dev, struct device_attribute *attr,
372 char *buf)
373 {
374 struct scsi_disk *sdkp = to_scsi_disk(dev);
375
376 return snprintf(buf, 20, "%u\n", sdkp->lbpme);
377 }
378 static DEVICE_ATTR_RO(thin_provisioning);
379
380 static const char *lbp_mode[] = {
381 [SD_LBP_FULL] = "full",
382 [SD_LBP_UNMAP] = "unmap",
383 [SD_LBP_WS16] = "writesame_16",
384 [SD_LBP_WS10] = "writesame_10",
385 [SD_LBP_ZERO] = "writesame_zero",
386 [SD_LBP_DISABLE] = "disabled",
387 };
388
389 static ssize_t
provisioning_mode_show(struct device * dev,struct device_attribute * attr,char * buf)390 provisioning_mode_show(struct device *dev, struct device_attribute *attr,
391 char *buf)
392 {
393 struct scsi_disk *sdkp = to_scsi_disk(dev);
394
395 return snprintf(buf, 20, "%s\n", lbp_mode[sdkp->provisioning_mode]);
396 }
397
398 static ssize_t
provisioning_mode_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)399 provisioning_mode_store(struct device *dev, struct device_attribute *attr,
400 const char *buf, size_t count)
401 {
402 struct scsi_disk *sdkp = to_scsi_disk(dev);
403 struct scsi_device *sdp = sdkp->device;
404
405 if (!capable(CAP_SYS_ADMIN))
406 return -EACCES;
407
408 if (sdp->type != TYPE_DISK)
409 return -EINVAL;
410
411 if (!strncmp(buf, lbp_mode[SD_LBP_UNMAP], 20))
412 sd_config_discard(sdkp, SD_LBP_UNMAP);
413 else if (!strncmp(buf, lbp_mode[SD_LBP_WS16], 20))
414 sd_config_discard(sdkp, SD_LBP_WS16);
415 else if (!strncmp(buf, lbp_mode[SD_LBP_WS10], 20))
416 sd_config_discard(sdkp, SD_LBP_WS10);
417 else if (!strncmp(buf, lbp_mode[SD_LBP_ZERO], 20))
418 sd_config_discard(sdkp, SD_LBP_ZERO);
419 else if (!strncmp(buf, lbp_mode[SD_LBP_DISABLE], 20))
420 sd_config_discard(sdkp, SD_LBP_DISABLE);
421 else
422 return -EINVAL;
423
424 return count;
425 }
426 static DEVICE_ATTR_RW(provisioning_mode);
427
428 static ssize_t
max_medium_access_timeouts_show(struct device * dev,struct device_attribute * attr,char * buf)429 max_medium_access_timeouts_show(struct device *dev,
430 struct device_attribute *attr, char *buf)
431 {
432 struct scsi_disk *sdkp = to_scsi_disk(dev);
433
434 return snprintf(buf, 20, "%u\n", sdkp->max_medium_access_timeouts);
435 }
436
437 static ssize_t
max_medium_access_timeouts_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)438 max_medium_access_timeouts_store(struct device *dev,
439 struct device_attribute *attr, const char *buf,
440 size_t count)
441 {
442 struct scsi_disk *sdkp = to_scsi_disk(dev);
443 int err;
444
445 if (!capable(CAP_SYS_ADMIN))
446 return -EACCES;
447
448 err = kstrtouint(buf, 10, &sdkp->max_medium_access_timeouts);
449
450 return err ? err : count;
451 }
452 static DEVICE_ATTR_RW(max_medium_access_timeouts);
453
454 static ssize_t
max_write_same_blocks_show(struct device * dev,struct device_attribute * attr,char * buf)455 max_write_same_blocks_show(struct device *dev, struct device_attribute *attr,
456 char *buf)
457 {
458 struct scsi_disk *sdkp = to_scsi_disk(dev);
459
460 return snprintf(buf, 20, "%u\n", sdkp->max_ws_blocks);
461 }
462
463 static ssize_t
max_write_same_blocks_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)464 max_write_same_blocks_store(struct device *dev, struct device_attribute *attr,
465 const char *buf, size_t count)
466 {
467 struct scsi_disk *sdkp = to_scsi_disk(dev);
468 struct scsi_device *sdp = sdkp->device;
469 unsigned long max;
470 int err;
471
472 if (!capable(CAP_SYS_ADMIN))
473 return -EACCES;
474
475 if (sdp->type != TYPE_DISK)
476 return -EINVAL;
477
478 err = kstrtoul(buf, 10, &max);
479
480 if (err)
481 return err;
482
483 if (max == 0)
484 sdp->no_write_same = 1;
485 else if (max <= SD_MAX_WS16_BLOCKS) {
486 sdp->no_write_same = 0;
487 sdkp->max_ws_blocks = max;
488 }
489
490 sd_config_write_same(sdkp);
491
492 return count;
493 }
494 static DEVICE_ATTR_RW(max_write_same_blocks);
495
496 static struct attribute *sd_disk_attrs[] = {
497 &dev_attr_cache_type.attr,
498 &dev_attr_FUA.attr,
499 &dev_attr_allow_restart.attr,
500 &dev_attr_manage_start_stop.attr,
501 &dev_attr_protection_type.attr,
502 &dev_attr_protection_mode.attr,
503 &dev_attr_app_tag_own.attr,
504 &dev_attr_thin_provisioning.attr,
505 &dev_attr_provisioning_mode.attr,
506 &dev_attr_max_write_same_blocks.attr,
507 &dev_attr_max_medium_access_timeouts.attr,
508 NULL,
509 };
510 ATTRIBUTE_GROUPS(sd_disk);
511
512 static struct class sd_disk_class = {
513 .name = "scsi_disk",
514 .owner = THIS_MODULE,
515 .dev_release = scsi_disk_release,
516 .dev_groups = sd_disk_groups,
517 };
518
519 static const struct dev_pm_ops sd_pm_ops = {
520 .suspend = sd_suspend_system,
521 .resume = sd_resume,
522 .poweroff = sd_suspend_system,
523 .restore = sd_resume,
524 .runtime_suspend = sd_suspend_runtime,
525 .runtime_resume = sd_resume,
526 };
527
528 static struct scsi_driver sd_template = {
529 .gendrv = {
530 .name = "sd",
531 .owner = THIS_MODULE,
532 .probe = sd_probe,
533 .remove = sd_remove,
534 .shutdown = sd_shutdown,
535 .pm = &sd_pm_ops,
536 },
537 .rescan = sd_rescan,
538 .init_command = sd_init_command,
539 .uninit_command = sd_uninit_command,
540 .done = sd_done,
541 .eh_action = sd_eh_action,
542 };
543
544 /*
545 * Dummy kobj_map->probe function.
546 * The default ->probe function will call modprobe, which is
547 * pointless as this module is already loaded.
548 */
sd_default_probe(dev_t devt,int * partno,void * data)549 static struct kobject *sd_default_probe(dev_t devt, int *partno, void *data)
550 {
551 return NULL;
552 }
553
554 /*
555 * Device no to disk mapping:
556 *
557 * major disc2 disc p1
558 * |............|.............|....|....| <- dev_t
559 * 31 20 19 8 7 4 3 0
560 *
561 * Inside a major, we have 16k disks, however mapped non-
562 * contiguously. The first 16 disks are for major0, the next
563 * ones with major1, ... Disk 256 is for major0 again, disk 272
564 * for major1, ...
565 * As we stay compatible with our numbering scheme, we can reuse
566 * the well-know SCSI majors 8, 65--71, 136--143.
567 */
sd_major(int major_idx)568 static int sd_major(int major_idx)
569 {
570 switch (major_idx) {
571 case 0:
572 return SCSI_DISK0_MAJOR;
573 case 1 ... 7:
574 return SCSI_DISK1_MAJOR + major_idx - 1;
575 case 8 ... 15:
576 return SCSI_DISK8_MAJOR + major_idx - 8;
577 default:
578 BUG();
579 return 0; /* shut up gcc */
580 }
581 }
582
scsi_disk_get(struct gendisk * disk)583 static struct scsi_disk *scsi_disk_get(struct gendisk *disk)
584 {
585 struct scsi_disk *sdkp = NULL;
586
587 mutex_lock(&sd_ref_mutex);
588
589 if (disk->private_data) {
590 sdkp = scsi_disk(disk);
591 if (scsi_device_get(sdkp->device) == 0)
592 get_device(&sdkp->dev);
593 else
594 sdkp = NULL;
595 }
596 mutex_unlock(&sd_ref_mutex);
597 return sdkp;
598 }
599
scsi_disk_put(struct scsi_disk * sdkp)600 static void scsi_disk_put(struct scsi_disk *sdkp)
601 {
602 struct scsi_device *sdev = sdkp->device;
603
604 mutex_lock(&sd_ref_mutex);
605 put_device(&sdkp->dev);
606 scsi_device_put(sdev);
607 mutex_unlock(&sd_ref_mutex);
608 }
609
sd_setup_protect_cmnd(struct scsi_cmnd * scmd,unsigned int dix,unsigned int dif)610 static unsigned char sd_setup_protect_cmnd(struct scsi_cmnd *scmd,
611 unsigned int dix, unsigned int dif)
612 {
613 struct bio *bio = scmd->request->bio;
614 unsigned int prot_op = sd_prot_op(rq_data_dir(scmd->request), dix, dif);
615 unsigned int protect = 0;
616
617 if (dix) { /* DIX Type 0, 1, 2, 3 */
618 if (bio_integrity_flagged(bio, BIP_IP_CHECKSUM))
619 scmd->prot_flags |= SCSI_PROT_IP_CHECKSUM;
620
621 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
622 scmd->prot_flags |= SCSI_PROT_GUARD_CHECK;
623 }
624
625 if (dif != SD_DIF_TYPE3_PROTECTION) { /* DIX/DIF Type 0, 1, 2 */
626 scmd->prot_flags |= SCSI_PROT_REF_INCREMENT;
627
628 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
629 scmd->prot_flags |= SCSI_PROT_REF_CHECK;
630 }
631
632 if (dif) { /* DIX/DIF Type 1, 2, 3 */
633 scmd->prot_flags |= SCSI_PROT_TRANSFER_PI;
634
635 if (bio_integrity_flagged(bio, BIP_DISK_NOCHECK))
636 protect = 3 << 5; /* Disable target PI checking */
637 else
638 protect = 1 << 5; /* Enable target PI checking */
639 }
640
641 scsi_set_prot_op(scmd, prot_op);
642 scsi_set_prot_type(scmd, dif);
643 scmd->prot_flags &= sd_prot_flag_mask(prot_op);
644
645 return protect;
646 }
647
sd_config_discard(struct scsi_disk * sdkp,unsigned int mode)648 static void sd_config_discard(struct scsi_disk *sdkp, unsigned int mode)
649 {
650 struct request_queue *q = sdkp->disk->queue;
651 unsigned int logical_block_size = sdkp->device->sector_size;
652 unsigned int max_blocks = 0;
653
654 q->limits.discard_zeroes_data = 0;
655
656 /*
657 * When LBPRZ is reported, discard alignment and granularity
658 * must be fixed to the logical block size. Otherwise the block
659 * layer will drop misaligned portions of the request which can
660 * lead to data corruption. If LBPRZ is not set, we honor the
661 * device preference.
662 */
663 if (sdkp->lbprz) {
664 q->limits.discard_alignment = 0;
665 q->limits.discard_granularity = logical_block_size;
666 } else {
667 q->limits.discard_alignment = sdkp->unmap_alignment *
668 logical_block_size;
669 q->limits.discard_granularity =
670 max(sdkp->physical_block_size,
671 sdkp->unmap_granularity * logical_block_size);
672 }
673
674 sdkp->provisioning_mode = mode;
675
676 switch (mode) {
677
678 case SD_LBP_DISABLE:
679 blk_queue_max_discard_sectors(q, 0);
680 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, q);
681 return;
682
683 case SD_LBP_UNMAP:
684 max_blocks = min_not_zero(sdkp->max_unmap_blocks,
685 (u32)SD_MAX_WS16_BLOCKS);
686 break;
687
688 case SD_LBP_WS16:
689 max_blocks = min_not_zero(sdkp->max_ws_blocks,
690 (u32)SD_MAX_WS16_BLOCKS);
691 q->limits.discard_zeroes_data = sdkp->lbprz;
692 break;
693
694 case SD_LBP_WS10:
695 max_blocks = min_not_zero(sdkp->max_ws_blocks,
696 (u32)SD_MAX_WS10_BLOCKS);
697 q->limits.discard_zeroes_data = sdkp->lbprz;
698 break;
699
700 case SD_LBP_ZERO:
701 max_blocks = min_not_zero(sdkp->max_ws_blocks,
702 (u32)SD_MAX_WS10_BLOCKS);
703 q->limits.discard_zeroes_data = 1;
704 break;
705 }
706
707 blk_queue_max_discard_sectors(q, max_blocks * (logical_block_size >> 9));
708 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q);
709 }
710
711 /**
712 * sd_setup_discard_cmnd - unmap blocks on thinly provisioned device
713 * @sdp: scsi device to operate one
714 * @rq: Request to prepare
715 *
716 * Will issue either UNMAP or WRITE SAME(16) depending on preference
717 * indicated by target device.
718 **/
sd_setup_discard_cmnd(struct scsi_cmnd * cmd)719 static int sd_setup_discard_cmnd(struct scsi_cmnd *cmd)
720 {
721 struct request *rq = cmd->request;
722 struct scsi_device *sdp = cmd->device;
723 struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
724 sector_t sector = blk_rq_pos(rq);
725 unsigned int nr_sectors = blk_rq_sectors(rq);
726 unsigned int nr_bytes = blk_rq_bytes(rq);
727 unsigned int len;
728 int ret;
729 char *buf;
730 struct page *page;
731
732 sector >>= ilog2(sdp->sector_size) - 9;
733 nr_sectors >>= ilog2(sdp->sector_size) - 9;
734
735 page = alloc_page(GFP_ATOMIC | __GFP_ZERO);
736 if (!page)
737 return BLKPREP_DEFER;
738
739 switch (sdkp->provisioning_mode) {
740 case SD_LBP_UNMAP:
741 buf = page_address(page);
742
743 cmd->cmd_len = 10;
744 cmd->cmnd[0] = UNMAP;
745 cmd->cmnd[8] = 24;
746
747 put_unaligned_be16(6 + 16, &buf[0]);
748 put_unaligned_be16(16, &buf[2]);
749 put_unaligned_be64(sector, &buf[8]);
750 put_unaligned_be32(nr_sectors, &buf[16]);
751
752 len = 24;
753 break;
754
755 case SD_LBP_WS16:
756 cmd->cmd_len = 16;
757 cmd->cmnd[0] = WRITE_SAME_16;
758 cmd->cmnd[1] = 0x8; /* UNMAP */
759 put_unaligned_be64(sector, &cmd->cmnd[2]);
760 put_unaligned_be32(nr_sectors, &cmd->cmnd[10]);
761
762 len = sdkp->device->sector_size;
763 break;
764
765 case SD_LBP_WS10:
766 case SD_LBP_ZERO:
767 cmd->cmd_len = 10;
768 cmd->cmnd[0] = WRITE_SAME;
769 if (sdkp->provisioning_mode == SD_LBP_WS10)
770 cmd->cmnd[1] = 0x8; /* UNMAP */
771 put_unaligned_be32(sector, &cmd->cmnd[2]);
772 put_unaligned_be16(nr_sectors, &cmd->cmnd[7]);
773
774 len = sdkp->device->sector_size;
775 break;
776
777 default:
778 ret = BLKPREP_KILL;
779 goto out;
780 }
781
782 rq->completion_data = page;
783 rq->timeout = SD_TIMEOUT;
784
785 cmd->transfersize = len;
786 cmd->allowed = SD_MAX_RETRIES;
787
788 /*
789 * Initially __data_len is set to the amount of data that needs to be
790 * transferred to the target. This amount depends on whether WRITE SAME
791 * or UNMAP is being used. After the scatterlist has been mapped by
792 * scsi_init_io() we set __data_len to the size of the area to be
793 * discarded on disk. This allows us to report completion on the full
794 * amount of blocks described by the request.
795 */
796 blk_add_request_payload(rq, page, len);
797 ret = scsi_init_io(cmd);
798 rq->__data_len = nr_bytes;
799
800 out:
801 if (ret != BLKPREP_OK)
802 __free_page(page);
803 return ret;
804 }
805
sd_config_write_same(struct scsi_disk * sdkp)806 static void sd_config_write_same(struct scsi_disk *sdkp)
807 {
808 struct request_queue *q = sdkp->disk->queue;
809 unsigned int logical_block_size = sdkp->device->sector_size;
810
811 if (sdkp->device->no_write_same) {
812 sdkp->max_ws_blocks = 0;
813 goto out;
814 }
815
816 /* Some devices can not handle block counts above 0xffff despite
817 * supporting WRITE SAME(16). Consequently we default to 64k
818 * blocks per I/O unless the device explicitly advertises a
819 * bigger limit.
820 */
821 if (sdkp->max_ws_blocks > SD_MAX_WS10_BLOCKS)
822 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
823 (u32)SD_MAX_WS16_BLOCKS);
824 else if (sdkp->ws16 || sdkp->ws10 || sdkp->device->no_report_opcodes)
825 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
826 (u32)SD_MAX_WS10_BLOCKS);
827 else {
828 sdkp->device->no_write_same = 1;
829 sdkp->max_ws_blocks = 0;
830 }
831
832 out:
833 blk_queue_max_write_same_sectors(q, sdkp->max_ws_blocks *
834 (logical_block_size >> 9));
835 }
836
837 /**
838 * sd_setup_write_same_cmnd - write the same data to multiple blocks
839 * @cmd: command to prepare
840 *
841 * Will issue either WRITE SAME(10) or WRITE SAME(16) depending on
842 * preference indicated by target device.
843 **/
sd_setup_write_same_cmnd(struct scsi_cmnd * cmd)844 static int sd_setup_write_same_cmnd(struct scsi_cmnd *cmd)
845 {
846 struct request *rq = cmd->request;
847 struct scsi_device *sdp = cmd->device;
848 struct scsi_disk *sdkp = scsi_disk(rq->rq_disk);
849 struct bio *bio = rq->bio;
850 sector_t sector = blk_rq_pos(rq);
851 unsigned int nr_sectors = blk_rq_sectors(rq);
852 unsigned int nr_bytes = blk_rq_bytes(rq);
853 int ret;
854
855 if (sdkp->device->no_write_same)
856 return BLKPREP_KILL;
857
858 BUG_ON(bio_offset(bio) || bio_iovec(bio).bv_len != sdp->sector_size);
859
860 sector >>= ilog2(sdp->sector_size) - 9;
861 nr_sectors >>= ilog2(sdp->sector_size) - 9;
862
863 rq->timeout = SD_WRITE_SAME_TIMEOUT;
864
865 if (sdkp->ws16 || sector > 0xffffffff || nr_sectors > 0xffff) {
866 cmd->cmd_len = 16;
867 cmd->cmnd[0] = WRITE_SAME_16;
868 put_unaligned_be64(sector, &cmd->cmnd[2]);
869 put_unaligned_be32(nr_sectors, &cmd->cmnd[10]);
870 } else {
871 cmd->cmd_len = 10;
872 cmd->cmnd[0] = WRITE_SAME;
873 put_unaligned_be32(sector, &cmd->cmnd[2]);
874 put_unaligned_be16(nr_sectors, &cmd->cmnd[7]);
875 }
876
877 cmd->transfersize = sdp->sector_size;
878 cmd->allowed = SD_MAX_RETRIES;
879
880 /*
881 * For WRITE_SAME the data transferred in the DATA IN buffer is
882 * different from the amount of data actually written to the target.
883 *
884 * We set up __data_len to the amount of data transferred from the
885 * DATA IN buffer so that blk_rq_map_sg set up the proper S/G list
886 * to transfer a single sector of data first, but then reset it to
887 * the amount of data to be written right after so that the I/O path
888 * knows how much to actually write.
889 */
890 rq->__data_len = sdp->sector_size;
891 ret = scsi_init_io(cmd);
892 rq->__data_len = nr_bytes;
893 return ret;
894 }
895
sd_setup_flush_cmnd(struct scsi_cmnd * cmd)896 static int sd_setup_flush_cmnd(struct scsi_cmnd *cmd)
897 {
898 struct request *rq = cmd->request;
899
900 /* flush requests don't perform I/O, zero the S/G table */
901 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
902
903 cmd->cmnd[0] = SYNCHRONIZE_CACHE;
904 cmd->cmd_len = 10;
905 cmd->transfersize = 0;
906 cmd->allowed = SD_MAX_RETRIES;
907
908 rq->timeout = rq->q->rq_timeout * SD_FLUSH_TIMEOUT_MULTIPLIER;
909 return BLKPREP_OK;
910 }
911
sd_setup_read_write_cmnd(struct scsi_cmnd * SCpnt)912 static int sd_setup_read_write_cmnd(struct scsi_cmnd *SCpnt)
913 {
914 struct request *rq = SCpnt->request;
915 struct scsi_device *sdp = SCpnt->device;
916 struct gendisk *disk = rq->rq_disk;
917 struct scsi_disk *sdkp;
918 sector_t block = blk_rq_pos(rq);
919 sector_t threshold;
920 unsigned int this_count = blk_rq_sectors(rq);
921 unsigned int dif, dix;
922 int ret;
923 unsigned char protect;
924
925 ret = scsi_init_io(SCpnt);
926 if (ret != BLKPREP_OK)
927 goto out;
928 SCpnt = rq->special;
929 sdkp = scsi_disk(disk);
930
931 /* from here on until we're complete, any goto out
932 * is used for a killable error condition */
933 ret = BLKPREP_KILL;
934
935 SCSI_LOG_HLQUEUE(1,
936 scmd_printk(KERN_INFO, SCpnt,
937 "%s: block=%llu, count=%d\n",
938 __func__, (unsigned long long)block, this_count));
939
940 if (!sdp || !scsi_device_online(sdp) ||
941 block + blk_rq_sectors(rq) > get_capacity(disk)) {
942 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
943 "Finishing %u sectors\n",
944 blk_rq_sectors(rq)));
945 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
946 "Retry with 0x%p\n", SCpnt));
947 goto out;
948 }
949
950 if (sdp->changed) {
951 /*
952 * quietly refuse to do anything to a changed disc until
953 * the changed bit has been reset
954 */
955 /* printk("SCSI disk has been changed or is not present. Prohibiting further I/O.\n"); */
956 goto out;
957 }
958
959 /*
960 * Some SD card readers can't handle multi-sector accesses which touch
961 * the last one or two hardware sectors. Split accesses as needed.
962 */
963 threshold = get_capacity(disk) - SD_LAST_BUGGY_SECTORS *
964 (sdp->sector_size / 512);
965
966 if (unlikely(sdp->last_sector_bug && block + this_count > threshold)) {
967 if (block < threshold) {
968 /* Access up to the threshold but not beyond */
969 this_count = threshold - block;
970 } else {
971 /* Access only a single hardware sector */
972 this_count = sdp->sector_size / 512;
973 }
974 }
975
976 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "block=%llu\n",
977 (unsigned long long)block));
978
979 /*
980 * If we have a 1K hardware sectorsize, prevent access to single
981 * 512 byte sectors. In theory we could handle this - in fact
982 * the scsi cdrom driver must be able to handle this because
983 * we typically use 1K blocksizes, and cdroms typically have
984 * 2K hardware sectorsizes. Of course, things are simpler
985 * with the cdrom, since it is read-only. For performance
986 * reasons, the filesystems should be able to handle this
987 * and not force the scsi disk driver to use bounce buffers
988 * for this.
989 */
990 if (sdp->sector_size == 1024) {
991 if ((block & 1) || (blk_rq_sectors(rq) & 1)) {
992 scmd_printk(KERN_ERR, SCpnt,
993 "Bad block number requested\n");
994 goto out;
995 } else {
996 block = block >> 1;
997 this_count = this_count >> 1;
998 }
999 }
1000 if (sdp->sector_size == 2048) {
1001 if ((block & 3) || (blk_rq_sectors(rq) & 3)) {
1002 scmd_printk(KERN_ERR, SCpnt,
1003 "Bad block number requested\n");
1004 goto out;
1005 } else {
1006 block = block >> 2;
1007 this_count = this_count >> 2;
1008 }
1009 }
1010 if (sdp->sector_size == 4096) {
1011 if ((block & 7) || (blk_rq_sectors(rq) & 7)) {
1012 scmd_printk(KERN_ERR, SCpnt,
1013 "Bad block number requested\n");
1014 goto out;
1015 } else {
1016 block = block >> 3;
1017 this_count = this_count >> 3;
1018 }
1019 }
1020 if (rq_data_dir(rq) == WRITE) {
1021 SCpnt->cmnd[0] = WRITE_6;
1022
1023 if (blk_integrity_rq(rq))
1024 sd_dif_prepare(SCpnt);
1025
1026 } else if (rq_data_dir(rq) == READ) {
1027 SCpnt->cmnd[0] = READ_6;
1028 } else {
1029 scmd_printk(KERN_ERR, SCpnt, "Unknown command %llx\n", (unsigned long long) rq->cmd_flags);
1030 goto out;
1031 }
1032
1033 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
1034 "%s %d/%u 512 byte blocks.\n",
1035 (rq_data_dir(rq) == WRITE) ?
1036 "writing" : "reading", this_count,
1037 blk_rq_sectors(rq)));
1038
1039 dix = scsi_prot_sg_count(SCpnt);
1040 dif = scsi_host_dif_capable(SCpnt->device->host, sdkp->protection_type);
1041
1042 if (dif || dix)
1043 protect = sd_setup_protect_cmnd(SCpnt, dix, dif);
1044 else
1045 protect = 0;
1046
1047 if (protect && sdkp->protection_type == SD_DIF_TYPE2_PROTECTION) {
1048 SCpnt->cmnd = mempool_alloc(sd_cdb_pool, GFP_ATOMIC);
1049
1050 if (unlikely(SCpnt->cmnd == NULL)) {
1051 ret = BLKPREP_DEFER;
1052 goto out;
1053 }
1054
1055 SCpnt->cmd_len = SD_EXT_CDB_SIZE;
1056 memset(SCpnt->cmnd, 0, SCpnt->cmd_len);
1057 SCpnt->cmnd[0] = VARIABLE_LENGTH_CMD;
1058 SCpnt->cmnd[7] = 0x18;
1059 SCpnt->cmnd[9] = (rq_data_dir(rq) == READ) ? READ_32 : WRITE_32;
1060 SCpnt->cmnd[10] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0);
1061
1062 /* LBA */
1063 SCpnt->cmnd[12] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
1064 SCpnt->cmnd[13] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
1065 SCpnt->cmnd[14] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
1066 SCpnt->cmnd[15] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
1067 SCpnt->cmnd[16] = (unsigned char) (block >> 24) & 0xff;
1068 SCpnt->cmnd[17] = (unsigned char) (block >> 16) & 0xff;
1069 SCpnt->cmnd[18] = (unsigned char) (block >> 8) & 0xff;
1070 SCpnt->cmnd[19] = (unsigned char) block & 0xff;
1071
1072 /* Expected Indirect LBA */
1073 SCpnt->cmnd[20] = (unsigned char) (block >> 24) & 0xff;
1074 SCpnt->cmnd[21] = (unsigned char) (block >> 16) & 0xff;
1075 SCpnt->cmnd[22] = (unsigned char) (block >> 8) & 0xff;
1076 SCpnt->cmnd[23] = (unsigned char) block & 0xff;
1077
1078 /* Transfer length */
1079 SCpnt->cmnd[28] = (unsigned char) (this_count >> 24) & 0xff;
1080 SCpnt->cmnd[29] = (unsigned char) (this_count >> 16) & 0xff;
1081 SCpnt->cmnd[30] = (unsigned char) (this_count >> 8) & 0xff;
1082 SCpnt->cmnd[31] = (unsigned char) this_count & 0xff;
1083 } else if (sdp->use_16_for_rw || (this_count > 0xffff)) {
1084 SCpnt->cmnd[0] += READ_16 - READ_6;
1085 SCpnt->cmnd[1] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0);
1086 SCpnt->cmnd[2] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
1087 SCpnt->cmnd[3] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
1088 SCpnt->cmnd[4] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
1089 SCpnt->cmnd[5] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
1090 SCpnt->cmnd[6] = (unsigned char) (block >> 24) & 0xff;
1091 SCpnt->cmnd[7] = (unsigned char) (block >> 16) & 0xff;
1092 SCpnt->cmnd[8] = (unsigned char) (block >> 8) & 0xff;
1093 SCpnt->cmnd[9] = (unsigned char) block & 0xff;
1094 SCpnt->cmnd[10] = (unsigned char) (this_count >> 24) & 0xff;
1095 SCpnt->cmnd[11] = (unsigned char) (this_count >> 16) & 0xff;
1096 SCpnt->cmnd[12] = (unsigned char) (this_count >> 8) & 0xff;
1097 SCpnt->cmnd[13] = (unsigned char) this_count & 0xff;
1098 SCpnt->cmnd[14] = SCpnt->cmnd[15] = 0;
1099 } else if ((this_count > 0xff) || (block > 0x1fffff) ||
1100 scsi_device_protection(SCpnt->device) ||
1101 SCpnt->device->use_10_for_rw) {
1102 SCpnt->cmnd[0] += READ_10 - READ_6;
1103 SCpnt->cmnd[1] = protect | ((rq->cmd_flags & REQ_FUA) ? 0x8 : 0);
1104 SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
1105 SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
1106 SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
1107 SCpnt->cmnd[5] = (unsigned char) block & 0xff;
1108 SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
1109 SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
1110 SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
1111 } else {
1112 if (unlikely(rq->cmd_flags & REQ_FUA)) {
1113 /*
1114 * This happens only if this drive failed
1115 * 10byte rw command with ILLEGAL_REQUEST
1116 * during operation and thus turned off
1117 * use_10_for_rw.
1118 */
1119 scmd_printk(KERN_ERR, SCpnt,
1120 "FUA write on READ/WRITE(6) drive\n");
1121 goto out;
1122 }
1123
1124 SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f);
1125 SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff);
1126 SCpnt->cmnd[3] = (unsigned char) block & 0xff;
1127 SCpnt->cmnd[4] = (unsigned char) this_count;
1128 SCpnt->cmnd[5] = 0;
1129 }
1130 SCpnt->sdb.length = this_count * sdp->sector_size;
1131
1132 /*
1133 * We shouldn't disconnect in the middle of a sector, so with a dumb
1134 * host adapter, it's safe to assume that we can at least transfer
1135 * this many bytes between each connect / disconnect.
1136 */
1137 SCpnt->transfersize = sdp->sector_size;
1138 SCpnt->underflow = this_count << 9;
1139 SCpnt->allowed = SD_MAX_RETRIES;
1140
1141 /*
1142 * This indicates that the command is ready from our end to be
1143 * queued.
1144 */
1145 ret = BLKPREP_OK;
1146 out:
1147 return ret;
1148 }
1149
sd_init_command(struct scsi_cmnd * cmd)1150 static int sd_init_command(struct scsi_cmnd *cmd)
1151 {
1152 struct request *rq = cmd->request;
1153
1154 if (rq->cmd_flags & REQ_DISCARD)
1155 return sd_setup_discard_cmnd(cmd);
1156 else if (rq->cmd_flags & REQ_WRITE_SAME)
1157 return sd_setup_write_same_cmnd(cmd);
1158 else if (rq->cmd_flags & REQ_FLUSH)
1159 return sd_setup_flush_cmnd(cmd);
1160 else
1161 return sd_setup_read_write_cmnd(cmd);
1162 }
1163
sd_uninit_command(struct scsi_cmnd * SCpnt)1164 static void sd_uninit_command(struct scsi_cmnd *SCpnt)
1165 {
1166 struct request *rq = SCpnt->request;
1167
1168 if (rq->cmd_flags & REQ_DISCARD)
1169 __free_page(rq->completion_data);
1170
1171 if (SCpnt->cmnd != rq->cmd) {
1172 mempool_free(SCpnt->cmnd, sd_cdb_pool);
1173 SCpnt->cmnd = NULL;
1174 SCpnt->cmd_len = 0;
1175 }
1176 }
1177
1178 /**
1179 * sd_open - open a scsi disk device
1180 * @inode: only i_rdev member may be used
1181 * @filp: only f_mode and f_flags may be used
1182 *
1183 * Returns 0 if successful. Returns a negated errno value in case
1184 * of error.
1185 *
1186 * Note: This can be called from a user context (e.g. fsck(1) )
1187 * or from within the kernel (e.g. as a result of a mount(1) ).
1188 * In the latter case @inode and @filp carry an abridged amount
1189 * of information as noted above.
1190 *
1191 * Locking: called with bdev->bd_mutex held.
1192 **/
sd_open(struct block_device * bdev,fmode_t mode)1193 static int sd_open(struct block_device *bdev, fmode_t mode)
1194 {
1195 struct scsi_disk *sdkp = scsi_disk_get(bdev->bd_disk);
1196 struct scsi_device *sdev;
1197 int retval;
1198
1199 if (!sdkp)
1200 return -ENXIO;
1201
1202 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
1203
1204 sdev = sdkp->device;
1205
1206 /*
1207 * If the device is in error recovery, wait until it is done.
1208 * If the device is offline, then disallow any access to it.
1209 */
1210 retval = -ENXIO;
1211 if (!scsi_block_when_processing_errors(sdev))
1212 goto error_out;
1213
1214 if (sdev->removable || sdkp->write_prot)
1215 check_disk_change(bdev);
1216
1217 /*
1218 * If the drive is empty, just let the open fail.
1219 */
1220 retval = -ENOMEDIUM;
1221 if (sdev->removable && !sdkp->media_present && !(mode & FMODE_NDELAY))
1222 goto error_out;
1223
1224 /*
1225 * If the device has the write protect tab set, have the open fail
1226 * if the user expects to be able to write to the thing.
1227 */
1228 retval = -EROFS;
1229 if (sdkp->write_prot && (mode & FMODE_WRITE))
1230 goto error_out;
1231
1232 /*
1233 * It is possible that the disk changing stuff resulted in
1234 * the device being taken offline. If this is the case,
1235 * report this to the user, and don't pretend that the
1236 * open actually succeeded.
1237 */
1238 retval = -ENXIO;
1239 if (!scsi_device_online(sdev))
1240 goto error_out;
1241
1242 if ((atomic_inc_return(&sdkp->openers) == 1) && sdev->removable) {
1243 if (scsi_block_when_processing_errors(sdev))
1244 scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
1245 }
1246
1247 return 0;
1248
1249 error_out:
1250 scsi_disk_put(sdkp);
1251 return retval;
1252 }
1253
1254 /**
1255 * sd_release - invoked when the (last) close(2) is called on this
1256 * scsi disk.
1257 * @inode: only i_rdev member may be used
1258 * @filp: only f_mode and f_flags may be used
1259 *
1260 * Returns 0.
1261 *
1262 * Note: may block (uninterruptible) if error recovery is underway
1263 * on this disk.
1264 *
1265 * Locking: called with bdev->bd_mutex held.
1266 **/
sd_release(struct gendisk * disk,fmode_t mode)1267 static void sd_release(struct gendisk *disk, fmode_t mode)
1268 {
1269 struct scsi_disk *sdkp = scsi_disk(disk);
1270 struct scsi_device *sdev = sdkp->device;
1271
1272 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
1273
1274 if (atomic_dec_return(&sdkp->openers) == 0 && sdev->removable) {
1275 if (scsi_block_when_processing_errors(sdev))
1276 scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
1277 }
1278
1279 scsi_disk_put(sdkp);
1280 }
1281
sd_getgeo(struct block_device * bdev,struct hd_geometry * geo)1282 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1283 {
1284 struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1285 struct scsi_device *sdp = sdkp->device;
1286 struct Scsi_Host *host = sdp->host;
1287 sector_t capacity = logical_to_sectors(sdp, sdkp->capacity);
1288 int diskinfo[4];
1289
1290 /* default to most commonly used values */
1291 diskinfo[0] = 0x40; /* 1 << 6 */
1292 diskinfo[1] = 0x20; /* 1 << 5 */
1293 diskinfo[2] = capacity >> 11;
1294
1295 /* override with calculated, extended default, or driver values */
1296 if (host->hostt->bios_param)
1297 host->hostt->bios_param(sdp, bdev, capacity, diskinfo);
1298 else
1299 scsicam_bios_param(bdev, capacity, diskinfo);
1300
1301 geo->heads = diskinfo[0];
1302 geo->sectors = diskinfo[1];
1303 geo->cylinders = diskinfo[2];
1304 return 0;
1305 }
1306
1307 /**
1308 * sd_ioctl - process an ioctl
1309 * @inode: only i_rdev/i_bdev members may be used
1310 * @filp: only f_mode and f_flags may be used
1311 * @cmd: ioctl command number
1312 * @arg: this is third argument given to ioctl(2) system call.
1313 * Often contains a pointer.
1314 *
1315 * Returns 0 if successful (some ioctls return positive numbers on
1316 * success as well). Returns a negated errno value in case of error.
1317 *
1318 * Note: most ioctls are forward onto the block subsystem or further
1319 * down in the scsi subsystem.
1320 **/
sd_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)1321 static int sd_ioctl(struct block_device *bdev, fmode_t mode,
1322 unsigned int cmd, unsigned long arg)
1323 {
1324 struct gendisk *disk = bdev->bd_disk;
1325 struct scsi_disk *sdkp = scsi_disk(disk);
1326 struct scsi_device *sdp = sdkp->device;
1327 void __user *p = (void __user *)arg;
1328 int error;
1329
1330 SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, "
1331 "cmd=0x%x\n", disk->disk_name, cmd));
1332
1333 error = scsi_verify_blk_ioctl(bdev, cmd);
1334 if (error < 0)
1335 return error;
1336
1337 /*
1338 * If we are in the middle of error recovery, don't let anyone
1339 * else try and use this device. Also, if error recovery fails, it
1340 * may try and take the device offline, in which case all further
1341 * access to the device is prohibited.
1342 */
1343 error = scsi_ioctl_block_when_processing_errors(sdp, cmd,
1344 (mode & FMODE_NDELAY) != 0);
1345 if (error)
1346 goto out;
1347
1348 /*
1349 * Send SCSI addressing ioctls directly to mid level, send other
1350 * ioctls to block level and then onto mid level if they can't be
1351 * resolved.
1352 */
1353 switch (cmd) {
1354 case SCSI_IOCTL_GET_IDLUN:
1355 case SCSI_IOCTL_GET_BUS_NUMBER:
1356 error = scsi_ioctl(sdp, cmd, p);
1357 break;
1358 default:
1359 error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p);
1360 if (error != -ENOTTY)
1361 break;
1362 error = scsi_ioctl(sdp, cmd, p);
1363 break;
1364 }
1365 out:
1366 return error;
1367 }
1368
set_media_not_present(struct scsi_disk * sdkp)1369 static void set_media_not_present(struct scsi_disk *sdkp)
1370 {
1371 if (sdkp->media_present)
1372 sdkp->device->changed = 1;
1373
1374 if (sdkp->device->removable) {
1375 sdkp->media_present = 0;
1376 sdkp->capacity = 0;
1377 }
1378 }
1379
media_not_present(struct scsi_disk * sdkp,struct scsi_sense_hdr * sshdr)1380 static int media_not_present(struct scsi_disk *sdkp,
1381 struct scsi_sense_hdr *sshdr)
1382 {
1383 if (!scsi_sense_valid(sshdr))
1384 return 0;
1385
1386 /* not invoked for commands that could return deferred errors */
1387 switch (sshdr->sense_key) {
1388 case UNIT_ATTENTION:
1389 case NOT_READY:
1390 /* medium not present */
1391 if (sshdr->asc == 0x3A) {
1392 set_media_not_present(sdkp);
1393 return 1;
1394 }
1395 }
1396 return 0;
1397 }
1398
1399 /**
1400 * sd_check_events - check media events
1401 * @disk: kernel device descriptor
1402 * @clearing: disk events currently being cleared
1403 *
1404 * Returns mask of DISK_EVENT_*.
1405 *
1406 * Note: this function is invoked from the block subsystem.
1407 **/
sd_check_events(struct gendisk * disk,unsigned int clearing)1408 static unsigned int sd_check_events(struct gendisk *disk, unsigned int clearing)
1409 {
1410 struct scsi_disk *sdkp = scsi_disk_get(disk);
1411 struct scsi_device *sdp;
1412 struct scsi_sense_hdr *sshdr = NULL;
1413 int retval;
1414
1415 if (!sdkp)
1416 return 0;
1417
1418 sdp = sdkp->device;
1419 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_check_events\n"));
1420
1421 /*
1422 * If the device is offline, don't send any commands - just pretend as
1423 * if the command failed. If the device ever comes back online, we
1424 * can deal with it then. It is only because of unrecoverable errors
1425 * that we would ever take a device offline in the first place.
1426 */
1427 if (!scsi_device_online(sdp)) {
1428 set_media_not_present(sdkp);
1429 goto out;
1430 }
1431
1432 /*
1433 * Using TEST_UNIT_READY enables differentiation between drive with
1434 * no cartridge loaded - NOT READY, drive with changed cartridge -
1435 * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
1436 *
1437 * Drives that auto spin down. eg iomega jaz 1G, will be started
1438 * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
1439 * sd_revalidate() is called.
1440 */
1441 retval = -ENODEV;
1442
1443 if (scsi_block_when_processing_errors(sdp)) {
1444 sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL);
1445 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, SD_MAX_RETRIES,
1446 sshdr);
1447 }
1448
1449 /* failed to execute TUR, assume media not present */
1450 if (host_byte(retval)) {
1451 set_media_not_present(sdkp);
1452 goto out;
1453 }
1454
1455 if (media_not_present(sdkp, sshdr))
1456 goto out;
1457
1458 /*
1459 * For removable scsi disk we have to recognise the presence
1460 * of a disk in the drive.
1461 */
1462 if (!sdkp->media_present)
1463 sdp->changed = 1;
1464 sdkp->media_present = 1;
1465 out:
1466 /*
1467 * sdp->changed is set under the following conditions:
1468 *
1469 * Medium present state has changed in either direction.
1470 * Device has indicated UNIT_ATTENTION.
1471 */
1472 kfree(sshdr);
1473 retval = sdp->changed ? DISK_EVENT_MEDIA_CHANGE : 0;
1474 sdp->changed = 0;
1475 scsi_disk_put(sdkp);
1476 return retval;
1477 }
1478
sd_sync_cache(struct scsi_disk * sdkp)1479 static int sd_sync_cache(struct scsi_disk *sdkp)
1480 {
1481 int retries, res;
1482 struct scsi_device *sdp = sdkp->device;
1483 const int timeout = sdp->request_queue->rq_timeout
1484 * SD_FLUSH_TIMEOUT_MULTIPLIER;
1485 struct scsi_sense_hdr sshdr;
1486
1487 if (!scsi_device_online(sdp))
1488 return -ENODEV;
1489
1490 for (retries = 3; retries > 0; --retries) {
1491 unsigned char cmd[10] = { 0 };
1492
1493 cmd[0] = SYNCHRONIZE_CACHE;
1494 /*
1495 * Leave the rest of the command zero to indicate
1496 * flush everything.
1497 */
1498 res = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0,
1499 &sshdr, timeout, SD_MAX_RETRIES,
1500 NULL, REQ_PM);
1501 if (res == 0)
1502 break;
1503 }
1504
1505 if (res) {
1506 sd_print_result(sdkp, "Synchronize Cache(10) failed", res);
1507
1508 if (driver_byte(res) & DRIVER_SENSE)
1509 sd_print_sense_hdr(sdkp, &sshdr);
1510 /* we need to evaluate the error return */
1511 if (scsi_sense_valid(&sshdr) &&
1512 (sshdr.asc == 0x3a || /* medium not present */
1513 sshdr.asc == 0x20)) /* invalid command */
1514 /* this is no error here */
1515 return 0;
1516
1517 switch (host_byte(res)) {
1518 /* ignore errors due to racing a disconnection */
1519 case DID_BAD_TARGET:
1520 case DID_NO_CONNECT:
1521 return 0;
1522 /* signal the upper layer it might try again */
1523 case DID_BUS_BUSY:
1524 case DID_IMM_RETRY:
1525 case DID_REQUEUE:
1526 case DID_SOFT_ERROR:
1527 return -EBUSY;
1528 default:
1529 return -EIO;
1530 }
1531 }
1532 return 0;
1533 }
1534
sd_rescan(struct device * dev)1535 static void sd_rescan(struct device *dev)
1536 {
1537 struct scsi_disk *sdkp = dev_get_drvdata(dev);
1538
1539 revalidate_disk(sdkp->disk);
1540 }
1541
1542
1543 #ifdef CONFIG_COMPAT
1544 /*
1545 * This gets directly called from VFS. When the ioctl
1546 * is not recognized we go back to the other translation paths.
1547 */
sd_compat_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)1548 static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode,
1549 unsigned int cmd, unsigned long arg)
1550 {
1551 struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device;
1552 int error;
1553
1554 error = scsi_ioctl_block_when_processing_errors(sdev, cmd,
1555 (mode & FMODE_NDELAY) != 0);
1556 if (error)
1557 return error;
1558
1559 /*
1560 * Let the static ioctl translation table take care of it.
1561 */
1562 if (!sdev->host->hostt->compat_ioctl)
1563 return -ENOIOCTLCMD;
1564 return sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg);
1565 }
1566 #endif
1567
sd_pr_type(enum pr_type type)1568 static char sd_pr_type(enum pr_type type)
1569 {
1570 switch (type) {
1571 case PR_WRITE_EXCLUSIVE:
1572 return 0x01;
1573 case PR_EXCLUSIVE_ACCESS:
1574 return 0x03;
1575 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1576 return 0x05;
1577 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1578 return 0x06;
1579 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1580 return 0x07;
1581 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1582 return 0x08;
1583 default:
1584 return 0;
1585 }
1586 };
1587
sd_pr_command(struct block_device * bdev,u8 sa,u64 key,u64 sa_key,u8 type,u8 flags)1588 static int sd_pr_command(struct block_device *bdev, u8 sa,
1589 u64 key, u64 sa_key, u8 type, u8 flags)
1590 {
1591 struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device;
1592 struct scsi_sense_hdr sshdr;
1593 int result;
1594 u8 cmd[16] = { 0, };
1595 u8 data[24] = { 0, };
1596
1597 cmd[0] = PERSISTENT_RESERVE_OUT;
1598 cmd[1] = sa;
1599 cmd[2] = type;
1600 put_unaligned_be32(sizeof(data), &cmd[5]);
1601
1602 put_unaligned_be64(key, &data[0]);
1603 put_unaligned_be64(sa_key, &data[8]);
1604 data[20] = flags;
1605
1606 result = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, &data, sizeof(data),
1607 &sshdr, SD_TIMEOUT, SD_MAX_RETRIES, NULL);
1608
1609 if ((driver_byte(result) & DRIVER_SENSE) &&
1610 (scsi_sense_valid(&sshdr))) {
1611 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
1612 scsi_print_sense_hdr(sdev, NULL, &sshdr);
1613 }
1614
1615 return result;
1616 }
1617
sd_pr_register(struct block_device * bdev,u64 old_key,u64 new_key,u32 flags)1618 static int sd_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
1619 u32 flags)
1620 {
1621 if (flags & ~PR_FL_IGNORE_KEY)
1622 return -EOPNOTSUPP;
1623 return sd_pr_command(bdev, (flags & PR_FL_IGNORE_KEY) ? 0x06 : 0x00,
1624 old_key, new_key, 0,
1625 (1 << 0) /* APTPL */ |
1626 (1 << 2) /* ALL_TG_PT */);
1627 }
1628
sd_pr_reserve(struct block_device * bdev,u64 key,enum pr_type type,u32 flags)1629 static int sd_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
1630 u32 flags)
1631 {
1632 if (flags)
1633 return -EOPNOTSUPP;
1634 return sd_pr_command(bdev, 0x01, key, 0, sd_pr_type(type), 0);
1635 }
1636
sd_pr_release(struct block_device * bdev,u64 key,enum pr_type type)1637 static int sd_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1638 {
1639 return sd_pr_command(bdev, 0x02, key, 0, sd_pr_type(type), 0);
1640 }
1641
sd_pr_preempt(struct block_device * bdev,u64 old_key,u64 new_key,enum pr_type type,bool abort)1642 static int sd_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
1643 enum pr_type type, bool abort)
1644 {
1645 return sd_pr_command(bdev, abort ? 0x05 : 0x04, old_key, new_key,
1646 sd_pr_type(type), 0);
1647 }
1648
sd_pr_clear(struct block_device * bdev,u64 key)1649 static int sd_pr_clear(struct block_device *bdev, u64 key)
1650 {
1651 return sd_pr_command(bdev, 0x03, key, 0, 0, 0);
1652 }
1653
1654 static const struct pr_ops sd_pr_ops = {
1655 .pr_register = sd_pr_register,
1656 .pr_reserve = sd_pr_reserve,
1657 .pr_release = sd_pr_release,
1658 .pr_preempt = sd_pr_preempt,
1659 .pr_clear = sd_pr_clear,
1660 };
1661
1662 static const struct block_device_operations sd_fops = {
1663 .owner = THIS_MODULE,
1664 .open = sd_open,
1665 .release = sd_release,
1666 .ioctl = sd_ioctl,
1667 .getgeo = sd_getgeo,
1668 #ifdef CONFIG_COMPAT
1669 .compat_ioctl = sd_compat_ioctl,
1670 #endif
1671 .check_events = sd_check_events,
1672 .revalidate_disk = sd_revalidate_disk,
1673 .unlock_native_capacity = sd_unlock_native_capacity,
1674 .pr_ops = &sd_pr_ops,
1675 };
1676
1677 /**
1678 * sd_eh_action - error handling callback
1679 * @scmd: sd-issued command that has failed
1680 * @eh_disp: The recovery disposition suggested by the midlayer
1681 *
1682 * This function is called by the SCSI midlayer upon completion of an
1683 * error test command (currently TEST UNIT READY). The result of sending
1684 * the eh command is passed in eh_disp. We're looking for devices that
1685 * fail medium access commands but are OK with non access commands like
1686 * test unit ready (so wrongly see the device as having a successful
1687 * recovery)
1688 **/
sd_eh_action(struct scsi_cmnd * scmd,int eh_disp)1689 static int sd_eh_action(struct scsi_cmnd *scmd, int eh_disp)
1690 {
1691 struct scsi_disk *sdkp = scsi_disk(scmd->request->rq_disk);
1692
1693 if (!scsi_device_online(scmd->device) ||
1694 !scsi_medium_access_command(scmd) ||
1695 host_byte(scmd->result) != DID_TIME_OUT ||
1696 eh_disp != SUCCESS)
1697 return eh_disp;
1698
1699 /*
1700 * The device has timed out executing a medium access command.
1701 * However, the TEST UNIT READY command sent during error
1702 * handling completed successfully. Either the device is in the
1703 * process of recovering or has it suffered an internal failure
1704 * that prevents access to the storage medium.
1705 */
1706 sdkp->medium_access_timed_out++;
1707
1708 /*
1709 * If the device keeps failing read/write commands but TEST UNIT
1710 * READY always completes successfully we assume that medium
1711 * access is no longer possible and take the device offline.
1712 */
1713 if (sdkp->medium_access_timed_out >= sdkp->max_medium_access_timeouts) {
1714 scmd_printk(KERN_ERR, scmd,
1715 "Medium access timeout failure. Offlining disk!\n");
1716 scsi_device_set_state(scmd->device, SDEV_OFFLINE);
1717
1718 return FAILED;
1719 }
1720
1721 return eh_disp;
1722 }
1723
sd_completed_bytes(struct scsi_cmnd * scmd)1724 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
1725 {
1726 u64 start_lba = blk_rq_pos(scmd->request);
1727 u64 end_lba = blk_rq_pos(scmd->request) + (scsi_bufflen(scmd) / 512);
1728 u64 factor = scmd->device->sector_size / 512;
1729 u64 bad_lba;
1730 int info_valid;
1731 /*
1732 * resid is optional but mostly filled in. When it's unused,
1733 * its value is zero, so we assume the whole buffer transferred
1734 */
1735 unsigned int transferred = scsi_bufflen(scmd) - scsi_get_resid(scmd);
1736 unsigned int good_bytes;
1737
1738 if (scmd->request->cmd_type != REQ_TYPE_FS)
1739 return 0;
1740
1741 info_valid = scsi_get_sense_info_fld(scmd->sense_buffer,
1742 SCSI_SENSE_BUFFERSIZE,
1743 &bad_lba);
1744 if (!info_valid)
1745 return 0;
1746
1747 if (scsi_bufflen(scmd) <= scmd->device->sector_size)
1748 return 0;
1749
1750 /* be careful ... don't want any overflows */
1751 do_div(start_lba, factor);
1752 do_div(end_lba, factor);
1753
1754 /* The bad lba was reported incorrectly, we have no idea where
1755 * the error is.
1756 */
1757 if (bad_lba < start_lba || bad_lba >= end_lba)
1758 return 0;
1759
1760 /* This computation should always be done in terms of
1761 * the resolution of the device's medium.
1762 */
1763 good_bytes = (bad_lba - start_lba) * scmd->device->sector_size;
1764 return min(good_bytes, transferred);
1765 }
1766
1767 /**
1768 * sd_done - bottom half handler: called when the lower level
1769 * driver has completed (successfully or otherwise) a scsi command.
1770 * @SCpnt: mid-level's per command structure.
1771 *
1772 * Note: potentially run from within an ISR. Must not block.
1773 **/
sd_done(struct scsi_cmnd * SCpnt)1774 static int sd_done(struct scsi_cmnd *SCpnt)
1775 {
1776 int result = SCpnt->result;
1777 unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
1778 struct scsi_sense_hdr sshdr;
1779 struct scsi_disk *sdkp = scsi_disk(SCpnt->request->rq_disk);
1780 struct request *req = SCpnt->request;
1781 int sense_valid = 0;
1782 int sense_deferred = 0;
1783 unsigned char op = SCpnt->cmnd[0];
1784 unsigned char unmap = SCpnt->cmnd[1] & 8;
1785
1786 if (req->cmd_flags & REQ_DISCARD || req->cmd_flags & REQ_WRITE_SAME) {
1787 if (!result) {
1788 good_bytes = blk_rq_bytes(req);
1789 scsi_set_resid(SCpnt, 0);
1790 } else {
1791 good_bytes = 0;
1792 scsi_set_resid(SCpnt, blk_rq_bytes(req));
1793 }
1794 }
1795
1796 if (result) {
1797 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
1798 if (sense_valid)
1799 sense_deferred = scsi_sense_is_deferred(&sshdr);
1800 }
1801 sdkp->medium_access_timed_out = 0;
1802
1803 if (driver_byte(result) != DRIVER_SENSE &&
1804 (!sense_valid || sense_deferred))
1805 goto out;
1806
1807 switch (sshdr.sense_key) {
1808 case HARDWARE_ERROR:
1809 case MEDIUM_ERROR:
1810 good_bytes = sd_completed_bytes(SCpnt);
1811 break;
1812 case RECOVERED_ERROR:
1813 good_bytes = scsi_bufflen(SCpnt);
1814 break;
1815 case NO_SENSE:
1816 /* This indicates a false check condition, so ignore it. An
1817 * unknown amount of data was transferred so treat it as an
1818 * error.
1819 */
1820 SCpnt->result = 0;
1821 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1822 break;
1823 case ABORTED_COMMAND:
1824 if (sshdr.asc == 0x10) /* DIF: Target detected corruption */
1825 good_bytes = sd_completed_bytes(SCpnt);
1826 break;
1827 case ILLEGAL_REQUEST:
1828 if (sshdr.asc == 0x10) /* DIX: Host detected corruption */
1829 good_bytes = sd_completed_bytes(SCpnt);
1830 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
1831 if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
1832 switch (op) {
1833 case UNMAP:
1834 sd_config_discard(sdkp, SD_LBP_DISABLE);
1835 break;
1836 case WRITE_SAME_16:
1837 case WRITE_SAME:
1838 if (unmap)
1839 sd_config_discard(sdkp, SD_LBP_DISABLE);
1840 else {
1841 sdkp->device->no_write_same = 1;
1842 sd_config_write_same(sdkp);
1843
1844 good_bytes = 0;
1845 req->__data_len = blk_rq_bytes(req);
1846 req->cmd_flags |= REQ_QUIET;
1847 }
1848 }
1849 }
1850 break;
1851 default:
1852 break;
1853 }
1854 out:
1855 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
1856 "sd_done: completed %d of %d bytes\n",
1857 good_bytes, scsi_bufflen(SCpnt)));
1858
1859 if (rq_data_dir(SCpnt->request) == READ && scsi_prot_sg_count(SCpnt))
1860 sd_dif_complete(SCpnt, good_bytes);
1861
1862 return good_bytes;
1863 }
1864
1865 /*
1866 * spinup disk - called only in sd_revalidate_disk()
1867 */
1868 static void
sd_spinup_disk(struct scsi_disk * sdkp)1869 sd_spinup_disk(struct scsi_disk *sdkp)
1870 {
1871 unsigned char cmd[10];
1872 unsigned long spintime_expire = 0;
1873 int retries, spintime;
1874 unsigned int the_result;
1875 struct scsi_sense_hdr sshdr;
1876 int sense_valid = 0;
1877
1878 spintime = 0;
1879
1880 /* Spin up drives, as required. Only do this at boot time */
1881 /* Spinup needs to be done for module loads too. */
1882 do {
1883 retries = 0;
1884
1885 do {
1886 cmd[0] = TEST_UNIT_READY;
1887 memset((void *) &cmd[1], 0, 9);
1888
1889 the_result = scsi_execute_req(sdkp->device, cmd,
1890 DMA_NONE, NULL, 0,
1891 &sshdr, SD_TIMEOUT,
1892 SD_MAX_RETRIES, NULL);
1893
1894 /*
1895 * If the drive has indicated to us that it
1896 * doesn't have any media in it, don't bother
1897 * with any more polling.
1898 */
1899 if (media_not_present(sdkp, &sshdr))
1900 return;
1901
1902 if (the_result)
1903 sense_valid = scsi_sense_valid(&sshdr);
1904 retries++;
1905 } while (retries < 3 &&
1906 (!scsi_status_is_good(the_result) ||
1907 ((driver_byte(the_result) & DRIVER_SENSE) &&
1908 sense_valid && sshdr.sense_key == UNIT_ATTENTION)));
1909
1910 if ((driver_byte(the_result) & DRIVER_SENSE) == 0) {
1911 /* no sense, TUR either succeeded or failed
1912 * with a status error */
1913 if(!spintime && !scsi_status_is_good(the_result)) {
1914 sd_print_result(sdkp, "Test Unit Ready failed",
1915 the_result);
1916 }
1917 break;
1918 }
1919
1920 /*
1921 * The device does not want the automatic start to be issued.
1922 */
1923 if (sdkp->device->no_start_on_add)
1924 break;
1925
1926 if (sense_valid && sshdr.sense_key == NOT_READY) {
1927 if (sshdr.asc == 4 && sshdr.ascq == 3)
1928 break; /* manual intervention required */
1929 if (sshdr.asc == 4 && sshdr.ascq == 0xb)
1930 break; /* standby */
1931 if (sshdr.asc == 4 && sshdr.ascq == 0xc)
1932 break; /* unavailable */
1933 if (sshdr.asc == 4 && sshdr.ascq == 0x1b)
1934 break; /* sanitize in progress */
1935 /*
1936 * Issue command to spin up drive when not ready
1937 */
1938 if (!spintime) {
1939 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
1940 cmd[0] = START_STOP;
1941 cmd[1] = 1; /* Return immediately */
1942 memset((void *) &cmd[2], 0, 8);
1943 cmd[4] = 1; /* Start spin cycle */
1944 if (sdkp->device->start_stop_pwr_cond)
1945 cmd[4] |= 1 << 4;
1946 scsi_execute_req(sdkp->device, cmd, DMA_NONE,
1947 NULL, 0, &sshdr,
1948 SD_TIMEOUT, SD_MAX_RETRIES,
1949 NULL);
1950 spintime_expire = jiffies + 100 * HZ;
1951 spintime = 1;
1952 }
1953 /* Wait 1 second for next try */
1954 msleep(1000);
1955 printk(".");
1956
1957 /*
1958 * Wait for USB flash devices with slow firmware.
1959 * Yes, this sense key/ASC combination shouldn't
1960 * occur here. It's characteristic of these devices.
1961 */
1962 } else if (sense_valid &&
1963 sshdr.sense_key == UNIT_ATTENTION &&
1964 sshdr.asc == 0x28) {
1965 if (!spintime) {
1966 spintime_expire = jiffies + 5 * HZ;
1967 spintime = 1;
1968 }
1969 /* Wait 1 second for next try */
1970 msleep(1000);
1971 } else {
1972 /* we don't understand the sense code, so it's
1973 * probably pointless to loop */
1974 if(!spintime) {
1975 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
1976 sd_print_sense_hdr(sdkp, &sshdr);
1977 }
1978 break;
1979 }
1980
1981 } while (spintime && time_before_eq(jiffies, spintime_expire));
1982
1983 if (spintime) {
1984 if (scsi_status_is_good(the_result))
1985 printk("ready\n");
1986 else
1987 printk("not responding...\n");
1988 }
1989 }
1990
1991
1992 /*
1993 * Determine whether disk supports Data Integrity Field.
1994 */
sd_read_protection_type(struct scsi_disk * sdkp,unsigned char * buffer)1995 static int sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
1996 {
1997 struct scsi_device *sdp = sdkp->device;
1998 u8 type;
1999 int ret = 0;
2000
2001 if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0) {
2002 sdkp->protection_type = 0;
2003 return ret;
2004 }
2005
2006 type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
2007
2008 if (type > SD_DIF_TYPE3_PROTECTION)
2009 ret = -ENODEV;
2010 else if (scsi_host_dif_capable(sdp->host, type))
2011 ret = 1;
2012
2013 if (sdkp->first_scan || type != sdkp->protection_type)
2014 switch (ret) {
2015 case -ENODEV:
2016 sd_printk(KERN_ERR, sdkp, "formatted with unsupported" \
2017 " protection type %u. Disabling disk!\n",
2018 type);
2019 break;
2020 case 1:
2021 sd_printk(KERN_NOTICE, sdkp,
2022 "Enabling DIF Type %u protection\n", type);
2023 break;
2024 case 0:
2025 sd_printk(KERN_NOTICE, sdkp,
2026 "Disabling DIF Type %u protection\n", type);
2027 break;
2028 }
2029
2030 sdkp->protection_type = type;
2031
2032 return ret;
2033 }
2034
read_capacity_error(struct scsi_disk * sdkp,struct scsi_device * sdp,struct scsi_sense_hdr * sshdr,int sense_valid,int the_result)2035 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
2036 struct scsi_sense_hdr *sshdr, int sense_valid,
2037 int the_result)
2038 {
2039 if (driver_byte(the_result) & DRIVER_SENSE)
2040 sd_print_sense_hdr(sdkp, sshdr);
2041 else
2042 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
2043
2044 /*
2045 * Set dirty bit for removable devices if not ready -
2046 * sometimes drives will not report this properly.
2047 */
2048 if (sdp->removable &&
2049 sense_valid && sshdr->sense_key == NOT_READY)
2050 set_media_not_present(sdkp);
2051
2052 /*
2053 * We used to set media_present to 0 here to indicate no media
2054 * in the drive, but some drives fail read capacity even with
2055 * media present, so we can't do that.
2056 */
2057 sdkp->capacity = 0; /* unknown mapped to zero - as usual */
2058 }
2059
2060 #define RC16_LEN 32
2061 #if RC16_LEN > SD_BUF_SIZE
2062 #error RC16_LEN must not be more than SD_BUF_SIZE
2063 #endif
2064
2065 #define READ_CAPACITY_RETRIES_ON_RESET 10
2066
2067 /*
2068 * Ensure that we don't overflow sector_t when CONFIG_LBDAF is not set
2069 * and the reported logical block size is bigger than 512 bytes. Note
2070 * that last_sector is a u64 and therefore logical_to_sectors() is not
2071 * applicable.
2072 */
sd_addressable_capacity(u64 lba,unsigned int sector_size)2073 static bool sd_addressable_capacity(u64 lba, unsigned int sector_size)
2074 {
2075 u64 last_sector = (lba + 1ULL) << (ilog2(sector_size) - 9);
2076
2077 if (sizeof(sector_t) == 4 && last_sector > U32_MAX)
2078 return false;
2079
2080 return true;
2081 }
2082
read_capacity_16(struct scsi_disk * sdkp,struct scsi_device * sdp,unsigned char * buffer)2083 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
2084 unsigned char *buffer)
2085 {
2086 unsigned char cmd[16];
2087 struct scsi_sense_hdr sshdr;
2088 int sense_valid = 0;
2089 int the_result;
2090 int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2091 unsigned int alignment;
2092 unsigned long long lba;
2093 unsigned sector_size;
2094
2095 if (sdp->no_read_capacity_16)
2096 return -EINVAL;
2097
2098 do {
2099 memset(cmd, 0, 16);
2100 cmd[0] = SERVICE_ACTION_IN_16;
2101 cmd[1] = SAI_READ_CAPACITY_16;
2102 cmd[13] = RC16_LEN;
2103 memset(buffer, 0, RC16_LEN);
2104
2105 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
2106 buffer, RC16_LEN, &sshdr,
2107 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
2108
2109 if (media_not_present(sdkp, &sshdr))
2110 return -ENODEV;
2111
2112 if (the_result) {
2113 sense_valid = scsi_sense_valid(&sshdr);
2114 if (sense_valid &&
2115 sshdr.sense_key == ILLEGAL_REQUEST &&
2116 (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
2117 sshdr.ascq == 0x00)
2118 /* Invalid Command Operation Code or
2119 * Invalid Field in CDB, just retry
2120 * silently with RC10 */
2121 return -EINVAL;
2122 if (sense_valid &&
2123 sshdr.sense_key == UNIT_ATTENTION &&
2124 sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2125 /* Device reset might occur several times,
2126 * give it one more chance */
2127 if (--reset_retries > 0)
2128 continue;
2129 }
2130 retries--;
2131
2132 } while (the_result && retries);
2133
2134 if (the_result) {
2135 sd_print_result(sdkp, "Read Capacity(16) failed", the_result);
2136 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2137 return -EINVAL;
2138 }
2139
2140 sector_size = get_unaligned_be32(&buffer[8]);
2141 lba = get_unaligned_be64(&buffer[0]);
2142
2143 if (sd_read_protection_type(sdkp, buffer) < 0) {
2144 sdkp->capacity = 0;
2145 return -ENODEV;
2146 }
2147
2148 if (!sd_addressable_capacity(lba, sector_size)) {
2149 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
2150 "kernel compiled with support for large block "
2151 "devices.\n");
2152 sdkp->capacity = 0;
2153 return -EOVERFLOW;
2154 }
2155
2156 /* Logical blocks per physical block exponent */
2157 sdkp->physical_block_size = (1 << (buffer[13] & 0xf)) * sector_size;
2158
2159 /* Lowest aligned logical block */
2160 alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
2161 blk_queue_alignment_offset(sdp->request_queue, alignment);
2162 if (alignment && sdkp->first_scan)
2163 sd_printk(KERN_NOTICE, sdkp,
2164 "physical block alignment offset: %u\n", alignment);
2165
2166 if (buffer[14] & 0x80) { /* LBPME */
2167 sdkp->lbpme = 1;
2168
2169 if (buffer[14] & 0x40) /* LBPRZ */
2170 sdkp->lbprz = 1;
2171
2172 sd_config_discard(sdkp, SD_LBP_WS16);
2173 }
2174
2175 sdkp->capacity = lba + 1;
2176 return sector_size;
2177 }
2178
read_capacity_10(struct scsi_disk * sdkp,struct scsi_device * sdp,unsigned char * buffer)2179 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
2180 unsigned char *buffer)
2181 {
2182 unsigned char cmd[16];
2183 struct scsi_sense_hdr sshdr;
2184 int sense_valid = 0;
2185 int the_result;
2186 int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2187 sector_t lba;
2188 unsigned sector_size;
2189
2190 do {
2191 cmd[0] = READ_CAPACITY;
2192 memset(&cmd[1], 0, 9);
2193 memset(buffer, 0, 8);
2194
2195 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
2196 buffer, 8, &sshdr,
2197 SD_TIMEOUT, SD_MAX_RETRIES, NULL);
2198
2199 if (media_not_present(sdkp, &sshdr))
2200 return -ENODEV;
2201
2202 if (the_result) {
2203 sense_valid = scsi_sense_valid(&sshdr);
2204 if (sense_valid &&
2205 sshdr.sense_key == UNIT_ATTENTION &&
2206 sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2207 /* Device reset might occur several times,
2208 * give it one more chance */
2209 if (--reset_retries > 0)
2210 continue;
2211 }
2212 retries--;
2213
2214 } while (the_result && retries);
2215
2216 if (the_result) {
2217 sd_print_result(sdkp, "Read Capacity(10) failed", the_result);
2218 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2219 return -EINVAL;
2220 }
2221
2222 sector_size = get_unaligned_be32(&buffer[4]);
2223 lba = get_unaligned_be32(&buffer[0]);
2224
2225 if (sdp->no_read_capacity_16 && (lba == 0xffffffff)) {
2226 /* Some buggy (usb cardreader) devices return an lba of
2227 0xffffffff when the want to report a size of 0 (with
2228 which they really mean no media is present) */
2229 sdkp->capacity = 0;
2230 sdkp->physical_block_size = sector_size;
2231 return sector_size;
2232 }
2233
2234 if (!sd_addressable_capacity(lba, sector_size)) {
2235 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
2236 "kernel compiled with support for large block "
2237 "devices.\n");
2238 sdkp->capacity = 0;
2239 return -EOVERFLOW;
2240 }
2241
2242 sdkp->capacity = lba + 1;
2243 sdkp->physical_block_size = sector_size;
2244 return sector_size;
2245 }
2246
sd_try_rc16_first(struct scsi_device * sdp)2247 static int sd_try_rc16_first(struct scsi_device *sdp)
2248 {
2249 if (sdp->host->max_cmd_len < 16)
2250 return 0;
2251 if (sdp->try_rc_10_first)
2252 return 0;
2253 if (sdp->scsi_level > SCSI_SPC_2)
2254 return 1;
2255 if (scsi_device_protection(sdp))
2256 return 1;
2257 return 0;
2258 }
2259
2260 /*
2261 * read disk capacity
2262 */
2263 static void
sd_read_capacity(struct scsi_disk * sdkp,unsigned char * buffer)2264 sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer)
2265 {
2266 int sector_size;
2267 struct scsi_device *sdp = sdkp->device;
2268 sector_t old_capacity = sdkp->capacity;
2269
2270 if (sd_try_rc16_first(sdp)) {
2271 sector_size = read_capacity_16(sdkp, sdp, buffer);
2272 if (sector_size == -EOVERFLOW)
2273 goto got_data;
2274 if (sector_size == -ENODEV)
2275 return;
2276 if (sector_size < 0)
2277 sector_size = read_capacity_10(sdkp, sdp, buffer);
2278 if (sector_size < 0)
2279 return;
2280 } else {
2281 sector_size = read_capacity_10(sdkp, sdp, buffer);
2282 if (sector_size == -EOVERFLOW)
2283 goto got_data;
2284 if (sector_size < 0)
2285 return;
2286 if ((sizeof(sdkp->capacity) > 4) &&
2287 (sdkp->capacity > 0xffffffffULL)) {
2288 int old_sector_size = sector_size;
2289 sd_printk(KERN_NOTICE, sdkp, "Very big device. "
2290 "Trying to use READ CAPACITY(16).\n");
2291 sector_size = read_capacity_16(sdkp, sdp, buffer);
2292 if (sector_size < 0) {
2293 sd_printk(KERN_NOTICE, sdkp,
2294 "Using 0xffffffff as device size\n");
2295 sdkp->capacity = 1 + (sector_t) 0xffffffff;
2296 sector_size = old_sector_size;
2297 goto got_data;
2298 }
2299 }
2300 }
2301
2302 /* Some devices are known to return the total number of blocks,
2303 * not the highest block number. Some devices have versions
2304 * which do this and others which do not. Some devices we might
2305 * suspect of doing this but we don't know for certain.
2306 *
2307 * If we know the reported capacity is wrong, decrement it. If
2308 * we can only guess, then assume the number of blocks is even
2309 * (usually true but not always) and err on the side of lowering
2310 * the capacity.
2311 */
2312 if (sdp->fix_capacity ||
2313 (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
2314 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
2315 "from its reported value: %llu\n",
2316 (unsigned long long) sdkp->capacity);
2317 --sdkp->capacity;
2318 }
2319
2320 got_data:
2321 if (sector_size == 0) {
2322 sector_size = 512;
2323 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
2324 "assuming 512.\n");
2325 }
2326
2327 if (sector_size != 512 &&
2328 sector_size != 1024 &&
2329 sector_size != 2048 &&
2330 sector_size != 4096) {
2331 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
2332 sector_size);
2333 /*
2334 * The user might want to re-format the drive with
2335 * a supported sectorsize. Once this happens, it
2336 * would be relatively trivial to set the thing up.
2337 * For this reason, we leave the thing in the table.
2338 */
2339 sdkp->capacity = 0;
2340 /*
2341 * set a bogus sector size so the normal read/write
2342 * logic in the block layer will eventually refuse any
2343 * request on this device without tripping over power
2344 * of two sector size assumptions
2345 */
2346 sector_size = 512;
2347 }
2348 blk_queue_logical_block_size(sdp->request_queue, sector_size);
2349
2350 {
2351 char cap_str_2[10], cap_str_10[10];
2352
2353 string_get_size(sdkp->capacity, sector_size,
2354 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
2355 string_get_size(sdkp->capacity, sector_size,
2356 STRING_UNITS_10, cap_str_10,
2357 sizeof(cap_str_10));
2358
2359 if (sdkp->first_scan || old_capacity != sdkp->capacity) {
2360 sd_printk(KERN_NOTICE, sdkp,
2361 "%llu %d-byte logical blocks: (%s/%s)\n",
2362 (unsigned long long)sdkp->capacity,
2363 sector_size, cap_str_10, cap_str_2);
2364
2365 if (sdkp->physical_block_size != sector_size)
2366 sd_printk(KERN_NOTICE, sdkp,
2367 "%u-byte physical blocks\n",
2368 sdkp->physical_block_size);
2369 }
2370 }
2371
2372 if (sdkp->capacity > 0xffffffff)
2373 sdp->use_16_for_rw = 1;
2374
2375 blk_queue_physical_block_size(sdp->request_queue,
2376 sdkp->physical_block_size);
2377 sdkp->device->sector_size = sector_size;
2378 }
2379
2380 /* called with buffer of length 512 */
2381 static inline int
sd_do_mode_sense(struct scsi_device * sdp,int dbd,int modepage,unsigned char * buffer,int len,struct scsi_mode_data * data,struct scsi_sense_hdr * sshdr)2382 sd_do_mode_sense(struct scsi_device *sdp, int dbd, int modepage,
2383 unsigned char *buffer, int len, struct scsi_mode_data *data,
2384 struct scsi_sense_hdr *sshdr)
2385 {
2386 return scsi_mode_sense(sdp, dbd, modepage, buffer, len,
2387 SD_TIMEOUT, SD_MAX_RETRIES, data,
2388 sshdr);
2389 }
2390
2391 /*
2392 * read write protect setting, if possible - called only in sd_revalidate_disk()
2393 * called with buffer of length SD_BUF_SIZE
2394 */
2395 static void
sd_read_write_protect_flag(struct scsi_disk * sdkp,unsigned char * buffer)2396 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
2397 {
2398 int res;
2399 struct scsi_device *sdp = sdkp->device;
2400 struct scsi_mode_data data;
2401 int old_wp = sdkp->write_prot;
2402
2403 set_disk_ro(sdkp->disk, 0);
2404 if (sdp->skip_ms_page_3f) {
2405 sd_first_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
2406 return;
2407 }
2408
2409 if (sdp->use_192_bytes_for_3f) {
2410 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 192, &data, NULL);
2411 } else {
2412 /*
2413 * First attempt: ask for all pages (0x3F), but only 4 bytes.
2414 * We have to start carefully: some devices hang if we ask
2415 * for more than is available.
2416 */
2417 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 4, &data, NULL);
2418
2419 /*
2420 * Second attempt: ask for page 0 When only page 0 is
2421 * implemented, a request for page 3F may return Sense Key
2422 * 5: Illegal Request, Sense Code 24: Invalid field in
2423 * CDB.
2424 */
2425 if (!scsi_status_is_good(res))
2426 res = sd_do_mode_sense(sdp, 0, 0, buffer, 4, &data, NULL);
2427
2428 /*
2429 * Third attempt: ask 255 bytes, as we did earlier.
2430 */
2431 if (!scsi_status_is_good(res))
2432 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 255,
2433 &data, NULL);
2434 }
2435
2436 if (!scsi_status_is_good(res)) {
2437 sd_first_printk(KERN_WARNING, sdkp,
2438 "Test WP failed, assume Write Enabled\n");
2439 } else {
2440 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
2441 set_disk_ro(sdkp->disk, sdkp->write_prot);
2442 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
2443 sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
2444 sdkp->write_prot ? "on" : "off");
2445 sd_printk(KERN_DEBUG, sdkp,
2446 "Mode Sense: %02x %02x %02x %02x\n",
2447 buffer[0], buffer[1], buffer[2], buffer[3]);
2448 }
2449 }
2450 }
2451
2452 /*
2453 * sd_read_cache_type - called only from sd_revalidate_disk()
2454 * called with buffer of length SD_BUF_SIZE
2455 */
2456 static void
sd_read_cache_type(struct scsi_disk * sdkp,unsigned char * buffer)2457 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
2458 {
2459 int len = 0, res;
2460 struct scsi_device *sdp = sdkp->device;
2461
2462 int dbd;
2463 int modepage;
2464 int first_len;
2465 struct scsi_mode_data data;
2466 struct scsi_sense_hdr sshdr;
2467 int old_wce = sdkp->WCE;
2468 int old_rcd = sdkp->RCD;
2469 int old_dpofua = sdkp->DPOFUA;
2470
2471
2472 if (sdkp->cache_override)
2473 return;
2474
2475 first_len = 4;
2476 if (sdp->skip_ms_page_8) {
2477 if (sdp->type == TYPE_RBC)
2478 goto defaults;
2479 else {
2480 if (sdp->skip_ms_page_3f)
2481 goto defaults;
2482 modepage = 0x3F;
2483 if (sdp->use_192_bytes_for_3f)
2484 first_len = 192;
2485 dbd = 0;
2486 }
2487 } else if (sdp->type == TYPE_RBC) {
2488 modepage = 6;
2489 dbd = 8;
2490 } else {
2491 modepage = 8;
2492 dbd = 0;
2493 }
2494
2495 /* cautiously ask */
2496 res = sd_do_mode_sense(sdp, dbd, modepage, buffer, first_len,
2497 &data, &sshdr);
2498
2499 if (!scsi_status_is_good(res))
2500 goto bad_sense;
2501
2502 if (!data.header_length) {
2503 modepage = 6;
2504 first_len = 0;
2505 sd_first_printk(KERN_ERR, sdkp,
2506 "Missing header in MODE_SENSE response\n");
2507 }
2508
2509 /* that went OK, now ask for the proper length */
2510 len = data.length;
2511
2512 /*
2513 * We're only interested in the first three bytes, actually.
2514 * But the data cache page is defined for the first 20.
2515 */
2516 if (len < 3)
2517 goto bad_sense;
2518 else if (len > SD_BUF_SIZE) {
2519 sd_first_printk(KERN_NOTICE, sdkp, "Truncating mode parameter "
2520 "data from %d to %d bytes\n", len, SD_BUF_SIZE);
2521 len = SD_BUF_SIZE;
2522 }
2523 if (modepage == 0x3F && sdp->use_192_bytes_for_3f)
2524 len = 192;
2525
2526 /* Get the data */
2527 if (len > first_len)
2528 res = sd_do_mode_sense(sdp, dbd, modepage, buffer, len,
2529 &data, &sshdr);
2530
2531 if (scsi_status_is_good(res)) {
2532 int offset = data.header_length + data.block_descriptor_length;
2533
2534 while (offset < len) {
2535 u8 page_code = buffer[offset] & 0x3F;
2536 u8 spf = buffer[offset] & 0x40;
2537
2538 if (page_code == 8 || page_code == 6) {
2539 /* We're interested only in the first 3 bytes.
2540 */
2541 if (len - offset <= 2) {
2542 sd_first_printk(KERN_ERR, sdkp,
2543 "Incomplete mode parameter "
2544 "data\n");
2545 goto defaults;
2546 } else {
2547 modepage = page_code;
2548 goto Page_found;
2549 }
2550 } else {
2551 /* Go to the next page */
2552 if (spf && len - offset > 3)
2553 offset += 4 + (buffer[offset+2] << 8) +
2554 buffer[offset+3];
2555 else if (!spf && len - offset > 1)
2556 offset += 2 + buffer[offset+1];
2557 else {
2558 sd_first_printk(KERN_ERR, sdkp,
2559 "Incomplete mode "
2560 "parameter data\n");
2561 goto defaults;
2562 }
2563 }
2564 }
2565
2566 sd_first_printk(KERN_ERR, sdkp, "No Caching mode page found\n");
2567 goto defaults;
2568
2569 Page_found:
2570 if (modepage == 8) {
2571 sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
2572 sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
2573 } else {
2574 sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
2575 sdkp->RCD = 0;
2576 }
2577
2578 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
2579 if (sdp->broken_fua) {
2580 sd_first_printk(KERN_NOTICE, sdkp, "Disabling FUA\n");
2581 sdkp->DPOFUA = 0;
2582 } else if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw &&
2583 !sdkp->device->use_16_for_rw) {
2584 sd_first_printk(KERN_NOTICE, sdkp,
2585 "Uses READ/WRITE(6), disabling FUA\n");
2586 sdkp->DPOFUA = 0;
2587 }
2588
2589 /* No cache flush allowed for write protected devices */
2590 if (sdkp->WCE && sdkp->write_prot)
2591 sdkp->WCE = 0;
2592
2593 if (sdkp->first_scan || old_wce != sdkp->WCE ||
2594 old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
2595 sd_printk(KERN_NOTICE, sdkp,
2596 "Write cache: %s, read cache: %s, %s\n",
2597 sdkp->WCE ? "enabled" : "disabled",
2598 sdkp->RCD ? "disabled" : "enabled",
2599 sdkp->DPOFUA ? "supports DPO and FUA"
2600 : "doesn't support DPO or FUA");
2601
2602 return;
2603 }
2604
2605 bad_sense:
2606 if (scsi_sense_valid(&sshdr) &&
2607 sshdr.sense_key == ILLEGAL_REQUEST &&
2608 sshdr.asc == 0x24 && sshdr.ascq == 0x0)
2609 /* Invalid field in CDB */
2610 sd_first_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
2611 else
2612 sd_first_printk(KERN_ERR, sdkp,
2613 "Asking for cache data failed\n");
2614
2615 defaults:
2616 if (sdp->wce_default_on) {
2617 sd_first_printk(KERN_NOTICE, sdkp,
2618 "Assuming drive cache: write back\n");
2619 sdkp->WCE = 1;
2620 } else {
2621 sd_first_printk(KERN_ERR, sdkp,
2622 "Assuming drive cache: write through\n");
2623 sdkp->WCE = 0;
2624 }
2625 sdkp->RCD = 0;
2626 sdkp->DPOFUA = 0;
2627 }
2628
2629 /*
2630 * The ATO bit indicates whether the DIF application tag is available
2631 * for use by the operating system.
2632 */
sd_read_app_tag_own(struct scsi_disk * sdkp,unsigned char * buffer)2633 static void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
2634 {
2635 int res, offset;
2636 struct scsi_device *sdp = sdkp->device;
2637 struct scsi_mode_data data;
2638 struct scsi_sense_hdr sshdr;
2639
2640 if (sdp->type != TYPE_DISK)
2641 return;
2642
2643 if (sdkp->protection_type == 0)
2644 return;
2645
2646 res = scsi_mode_sense(sdp, 1, 0x0a, buffer, 36, SD_TIMEOUT,
2647 SD_MAX_RETRIES, &data, &sshdr);
2648
2649 if (!scsi_status_is_good(res) || !data.header_length ||
2650 data.length < 6) {
2651 sd_first_printk(KERN_WARNING, sdkp,
2652 "getting Control mode page failed, assume no ATO\n");
2653
2654 if (scsi_sense_valid(&sshdr))
2655 sd_print_sense_hdr(sdkp, &sshdr);
2656
2657 return;
2658 }
2659
2660 offset = data.header_length + data.block_descriptor_length;
2661
2662 if ((buffer[offset] & 0x3f) != 0x0a) {
2663 sd_first_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
2664 return;
2665 }
2666
2667 if ((buffer[offset + 5] & 0x80) == 0)
2668 return;
2669
2670 sdkp->ATO = 1;
2671
2672 return;
2673 }
2674
2675 /**
2676 * sd_read_block_limits - Query disk device for preferred I/O sizes.
2677 * @disk: disk to query
2678 */
sd_read_block_limits(struct scsi_disk * sdkp)2679 static void sd_read_block_limits(struct scsi_disk *sdkp)
2680 {
2681 unsigned int sector_sz = sdkp->device->sector_size;
2682 const int vpd_len = 64;
2683 unsigned char *buffer = kmalloc(vpd_len, GFP_KERNEL);
2684
2685 if (!buffer ||
2686 /* Block Limits VPD */
2687 scsi_get_vpd_page(sdkp->device, 0xb0, buffer, vpd_len))
2688 goto out;
2689
2690 blk_queue_io_min(sdkp->disk->queue,
2691 get_unaligned_be16(&buffer[6]) * sector_sz);
2692
2693 sdkp->max_xfer_blocks = get_unaligned_be32(&buffer[8]);
2694 sdkp->opt_xfer_blocks = get_unaligned_be32(&buffer[12]);
2695
2696 if (buffer[3] == 0x3c) {
2697 unsigned int lba_count, desc_count;
2698
2699 sdkp->max_ws_blocks = (u32)get_unaligned_be64(&buffer[36]);
2700
2701 if (!sdkp->lbpme)
2702 goto out;
2703
2704 lba_count = get_unaligned_be32(&buffer[20]);
2705 desc_count = get_unaligned_be32(&buffer[24]);
2706
2707 if (lba_count && desc_count)
2708 sdkp->max_unmap_blocks = lba_count;
2709
2710 sdkp->unmap_granularity = get_unaligned_be32(&buffer[28]);
2711
2712 if (buffer[32] & 0x80)
2713 sdkp->unmap_alignment =
2714 get_unaligned_be32(&buffer[32]) & ~(1 << 31);
2715
2716 if (!sdkp->lbpvpd) { /* LBP VPD page not provided */
2717
2718 if (sdkp->max_unmap_blocks)
2719 sd_config_discard(sdkp, SD_LBP_UNMAP);
2720 else
2721 sd_config_discard(sdkp, SD_LBP_WS16);
2722
2723 } else { /* LBP VPD page tells us what to use */
2724 if (sdkp->lbpu && sdkp->max_unmap_blocks && !sdkp->lbprz)
2725 sd_config_discard(sdkp, SD_LBP_UNMAP);
2726 else if (sdkp->lbpws)
2727 sd_config_discard(sdkp, SD_LBP_WS16);
2728 else if (sdkp->lbpws10)
2729 sd_config_discard(sdkp, SD_LBP_WS10);
2730 else if (sdkp->lbpu && sdkp->max_unmap_blocks)
2731 sd_config_discard(sdkp, SD_LBP_UNMAP);
2732 else
2733 sd_config_discard(sdkp, SD_LBP_DISABLE);
2734 }
2735 }
2736
2737 out:
2738 kfree(buffer);
2739 }
2740
2741 /**
2742 * sd_read_block_characteristics - Query block dev. characteristics
2743 * @disk: disk to query
2744 */
sd_read_block_characteristics(struct scsi_disk * sdkp)2745 static void sd_read_block_characteristics(struct scsi_disk *sdkp)
2746 {
2747 unsigned char *buffer;
2748 u16 rot;
2749 const int vpd_len = 64;
2750
2751 buffer = kmalloc(vpd_len, GFP_KERNEL);
2752
2753 if (!buffer ||
2754 /* Block Device Characteristics VPD */
2755 scsi_get_vpd_page(sdkp->device, 0xb1, buffer, vpd_len))
2756 goto out;
2757
2758 rot = get_unaligned_be16(&buffer[4]);
2759
2760 if (rot == 1) {
2761 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, sdkp->disk->queue);
2762 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, sdkp->disk->queue);
2763 }
2764
2765 out:
2766 kfree(buffer);
2767 }
2768
2769 /**
2770 * sd_read_block_provisioning - Query provisioning VPD page
2771 * @disk: disk to query
2772 */
sd_read_block_provisioning(struct scsi_disk * sdkp)2773 static void sd_read_block_provisioning(struct scsi_disk *sdkp)
2774 {
2775 unsigned char *buffer;
2776 const int vpd_len = 8;
2777
2778 if (sdkp->lbpme == 0)
2779 return;
2780
2781 buffer = kmalloc(vpd_len, GFP_KERNEL);
2782
2783 if (!buffer || scsi_get_vpd_page(sdkp->device, 0xb2, buffer, vpd_len))
2784 goto out;
2785
2786 sdkp->lbpvpd = 1;
2787 sdkp->lbpu = (buffer[5] >> 7) & 1; /* UNMAP */
2788 sdkp->lbpws = (buffer[5] >> 6) & 1; /* WRITE SAME(16) with UNMAP */
2789 sdkp->lbpws10 = (buffer[5] >> 5) & 1; /* WRITE SAME(10) with UNMAP */
2790
2791 out:
2792 kfree(buffer);
2793 }
2794
sd_read_write_same(struct scsi_disk * sdkp,unsigned char * buffer)2795 static void sd_read_write_same(struct scsi_disk *sdkp, unsigned char *buffer)
2796 {
2797 struct scsi_device *sdev = sdkp->device;
2798
2799 if (sdev->host->no_write_same) {
2800 sdev->no_write_same = 1;
2801
2802 return;
2803 }
2804
2805 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, INQUIRY) < 0) {
2806 /* too large values might cause issues with arcmsr */
2807 int vpd_buf_len = 64;
2808
2809 sdev->no_report_opcodes = 1;
2810
2811 /* Disable WRITE SAME if REPORT SUPPORTED OPERATION
2812 * CODES is unsupported and the device has an ATA
2813 * Information VPD page (SAT).
2814 */
2815 if (!scsi_get_vpd_page(sdev, 0x89, buffer, vpd_buf_len))
2816 sdev->no_write_same = 1;
2817 }
2818
2819 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME_16) == 1)
2820 sdkp->ws16 = 1;
2821
2822 if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME) == 1)
2823 sdkp->ws10 = 1;
2824 }
2825
sd_try_extended_inquiry(struct scsi_device * sdp)2826 static int sd_try_extended_inquiry(struct scsi_device *sdp)
2827 {
2828 /* Attempt VPD inquiry if the device blacklist explicitly calls
2829 * for it.
2830 */
2831 if (sdp->try_vpd_pages)
2832 return 1;
2833 /*
2834 * Although VPD inquiries can go to SCSI-2 type devices,
2835 * some USB ones crash on receiving them, and the pages
2836 * we currently ask for are for SPC-3 and beyond
2837 */
2838 if (sdp->scsi_level > SCSI_SPC_2 && !sdp->skip_vpd_pages)
2839 return 1;
2840 return 0;
2841 }
2842
2843 /**
2844 * sd_revalidate_disk - called the first time a new disk is seen,
2845 * performs disk spin up, read_capacity, etc.
2846 * @disk: struct gendisk we care about
2847 **/
sd_revalidate_disk(struct gendisk * disk)2848 static int sd_revalidate_disk(struct gendisk *disk)
2849 {
2850 struct scsi_disk *sdkp = scsi_disk(disk);
2851 struct scsi_device *sdp = sdkp->device;
2852 struct request_queue *q = sdkp->disk->queue;
2853 unsigned char *buffer;
2854 unsigned int dev_max, rw_max;
2855
2856 SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
2857 "sd_revalidate_disk\n"));
2858
2859 /*
2860 * If the device is offline, don't try and read capacity or any
2861 * of the other niceties.
2862 */
2863 if (!scsi_device_online(sdp))
2864 goto out;
2865
2866 buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
2867 if (!buffer) {
2868 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
2869 "allocation failure.\n");
2870 goto out;
2871 }
2872
2873 sd_spinup_disk(sdkp);
2874
2875 /*
2876 * Without media there is no reason to ask; moreover, some devices
2877 * react badly if we do.
2878 */
2879 if (sdkp->media_present) {
2880 sd_read_capacity(sdkp, buffer);
2881
2882 if (sd_try_extended_inquiry(sdp)) {
2883 sd_read_block_provisioning(sdkp);
2884 sd_read_block_limits(sdkp);
2885 sd_read_block_characteristics(sdkp);
2886 }
2887
2888 sd_read_write_protect_flag(sdkp, buffer);
2889 sd_read_cache_type(sdkp, buffer);
2890 sd_read_app_tag_own(sdkp, buffer);
2891 sd_read_write_same(sdkp, buffer);
2892 }
2893
2894 /*
2895 * We now have all cache related info, determine how we deal
2896 * with flush requests.
2897 */
2898 sd_set_flush_flag(sdkp);
2899
2900 /* Initial block count limit based on CDB TRANSFER LENGTH field size. */
2901 dev_max = sdp->use_16_for_rw ? SD_MAX_XFER_BLOCKS : SD_DEF_XFER_BLOCKS;
2902
2903 /* Some devices report a maximum block count for READ/WRITE requests. */
2904 dev_max = min_not_zero(dev_max, sdkp->max_xfer_blocks);
2905 q->limits.max_dev_sectors = logical_to_sectors(sdp, dev_max);
2906
2907 /*
2908 * Determine the device's preferred I/O size for reads and writes
2909 * unless the reported value is unreasonably small, large, or
2910 * garbage.
2911 */
2912 if (sdkp->opt_xfer_blocks &&
2913 sdkp->opt_xfer_blocks <= dev_max &&
2914 sdkp->opt_xfer_blocks <= SD_DEF_XFER_BLOCKS &&
2915 logical_to_bytes(sdp, sdkp->opt_xfer_blocks) >= PAGE_CACHE_SIZE) {
2916 q->limits.io_opt = logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
2917 rw_max = logical_to_sectors(sdp, sdkp->opt_xfer_blocks);
2918 } else {
2919 q->limits.io_opt = 0;
2920 rw_max = min_not_zero(logical_to_sectors(sdp, dev_max),
2921 (sector_t)BLK_DEF_MAX_SECTORS);
2922 }
2923
2924 /* Do not exceed controller limit */
2925 rw_max = min(rw_max, queue_max_hw_sectors(q));
2926
2927 /*
2928 * Only update max_sectors if previously unset or if the current value
2929 * exceeds the capabilities of the hardware.
2930 */
2931 if (sdkp->first_scan ||
2932 q->limits.max_sectors > q->limits.max_dev_sectors ||
2933 q->limits.max_sectors > q->limits.max_hw_sectors)
2934 q->limits.max_sectors = rw_max;
2935
2936 sdkp->first_scan = 0;
2937
2938 set_capacity(disk, logical_to_sectors(sdp, sdkp->capacity));
2939 sd_config_write_same(sdkp);
2940 kfree(buffer);
2941
2942 out:
2943 return 0;
2944 }
2945
2946 /**
2947 * sd_unlock_native_capacity - unlock native capacity
2948 * @disk: struct gendisk to set capacity for
2949 *
2950 * Block layer calls this function if it detects that partitions
2951 * on @disk reach beyond the end of the device. If the SCSI host
2952 * implements ->unlock_native_capacity() method, it's invoked to
2953 * give it a chance to adjust the device capacity.
2954 *
2955 * CONTEXT:
2956 * Defined by block layer. Might sleep.
2957 */
sd_unlock_native_capacity(struct gendisk * disk)2958 static void sd_unlock_native_capacity(struct gendisk *disk)
2959 {
2960 struct scsi_device *sdev = scsi_disk(disk)->device;
2961
2962 if (sdev->host->hostt->unlock_native_capacity)
2963 sdev->host->hostt->unlock_native_capacity(sdev);
2964 }
2965
2966 /**
2967 * sd_format_disk_name - format disk name
2968 * @prefix: name prefix - ie. "sd" for SCSI disks
2969 * @index: index of the disk to format name for
2970 * @buf: output buffer
2971 * @buflen: length of the output buffer
2972 *
2973 * SCSI disk names starts at sda. The 26th device is sdz and the
2974 * 27th is sdaa. The last one for two lettered suffix is sdzz
2975 * which is followed by sdaaa.
2976 *
2977 * This is basically 26 base counting with one extra 'nil' entry
2978 * at the beginning from the second digit on and can be
2979 * determined using similar method as 26 base conversion with the
2980 * index shifted -1 after each digit is computed.
2981 *
2982 * CONTEXT:
2983 * Don't care.
2984 *
2985 * RETURNS:
2986 * 0 on success, -errno on failure.
2987 */
sd_format_disk_name(char * prefix,int index,char * buf,int buflen)2988 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
2989 {
2990 const int base = 'z' - 'a' + 1;
2991 char *begin = buf + strlen(prefix);
2992 char *end = buf + buflen;
2993 char *p;
2994 int unit;
2995
2996 p = end - 1;
2997 *p = '\0';
2998 unit = base;
2999 do {
3000 if (p == begin)
3001 return -EINVAL;
3002 *--p = 'a' + (index % unit);
3003 index = (index / unit) - 1;
3004 } while (index >= 0);
3005
3006 memmove(begin, p, end - p);
3007 memcpy(buf, prefix, strlen(prefix));
3008
3009 return 0;
3010 }
3011
3012 /*
3013 * The asynchronous part of sd_probe
3014 */
sd_probe_async(void * data,async_cookie_t cookie)3015 static void sd_probe_async(void *data, async_cookie_t cookie)
3016 {
3017 struct scsi_disk *sdkp = data;
3018 struct scsi_device *sdp;
3019 struct gendisk *gd;
3020 u32 index;
3021 struct device *dev;
3022
3023 sdp = sdkp->device;
3024 gd = sdkp->disk;
3025 index = sdkp->index;
3026 dev = &sdp->sdev_gendev;
3027
3028 gd->major = sd_major((index & 0xf0) >> 4);
3029 gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
3030 gd->minors = SD_MINORS;
3031
3032 gd->fops = &sd_fops;
3033 gd->private_data = &sdkp->driver;
3034 gd->queue = sdkp->device->request_queue;
3035
3036 /* defaults, until the device tells us otherwise */
3037 sdp->sector_size = 512;
3038 sdkp->capacity = 0;
3039 sdkp->media_present = 1;
3040 sdkp->write_prot = 0;
3041 sdkp->cache_override = 0;
3042 sdkp->WCE = 0;
3043 sdkp->RCD = 0;
3044 sdkp->ATO = 0;
3045 sdkp->first_scan = 1;
3046 sdkp->max_medium_access_timeouts = SD_MAX_MEDIUM_TIMEOUTS;
3047
3048 sd_revalidate_disk(gd);
3049
3050 gd->driverfs_dev = &sdp->sdev_gendev;
3051 gd->flags = GENHD_FL_EXT_DEVT;
3052 if (sdp->removable) {
3053 gd->flags |= GENHD_FL_REMOVABLE;
3054 gd->events |= DISK_EVENT_MEDIA_CHANGE;
3055 }
3056
3057 blk_pm_runtime_init(sdp->request_queue, dev);
3058 add_disk(gd);
3059 if (sdkp->capacity)
3060 sd_dif_config_host(sdkp);
3061
3062 sd_revalidate_disk(gd);
3063
3064 sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
3065 sdp->removable ? "removable " : "");
3066 scsi_autopm_put_device(sdp);
3067 put_device(&sdkp->dev);
3068 }
3069
3070 /**
3071 * sd_probe - called during driver initialization and whenever a
3072 * new scsi device is attached to the system. It is called once
3073 * for each scsi device (not just disks) present.
3074 * @dev: pointer to device object
3075 *
3076 * Returns 0 if successful (or not interested in this scsi device
3077 * (e.g. scanner)); 1 when there is an error.
3078 *
3079 * Note: this function is invoked from the scsi mid-level.
3080 * This function sets up the mapping between a given
3081 * <host,channel,id,lun> (found in sdp) and new device name
3082 * (e.g. /dev/sda). More precisely it is the block device major
3083 * and minor number that is chosen here.
3084 *
3085 * Assume sd_probe is not re-entrant (for time being)
3086 * Also think about sd_probe() and sd_remove() running coincidentally.
3087 **/
sd_probe(struct device * dev)3088 static int sd_probe(struct device *dev)
3089 {
3090 struct scsi_device *sdp = to_scsi_device(dev);
3091 struct scsi_disk *sdkp;
3092 struct gendisk *gd;
3093 int index;
3094 int error;
3095
3096 scsi_autopm_get_device(sdp);
3097 error = -ENODEV;
3098 if (sdp->type != TYPE_DISK && sdp->type != TYPE_MOD && sdp->type != TYPE_RBC)
3099 goto out;
3100
3101 SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
3102 "sd_probe\n"));
3103
3104 error = -ENOMEM;
3105 sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
3106 if (!sdkp)
3107 goto out;
3108
3109 gd = alloc_disk(SD_MINORS);
3110 if (!gd)
3111 goto out_free;
3112
3113 do {
3114 if (!ida_pre_get(&sd_index_ida, GFP_KERNEL))
3115 goto out_put;
3116
3117 spin_lock(&sd_index_lock);
3118 error = ida_get_new(&sd_index_ida, &index);
3119 spin_unlock(&sd_index_lock);
3120 } while (error == -EAGAIN);
3121
3122 if (error) {
3123 sdev_printk(KERN_WARNING, sdp, "sd_probe: memory exhausted.\n");
3124 goto out_put;
3125 }
3126
3127 error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
3128 if (error) {
3129 sdev_printk(KERN_WARNING, sdp, "SCSI disk (sd) name length exceeded.\n");
3130 goto out_free_index;
3131 }
3132
3133 sdkp->device = sdp;
3134 sdkp->driver = &sd_template;
3135 sdkp->disk = gd;
3136 sdkp->index = index;
3137 atomic_set(&sdkp->openers, 0);
3138 atomic_set(&sdkp->device->ioerr_cnt, 0);
3139
3140 if (!sdp->request_queue->rq_timeout) {
3141 if (sdp->type != TYPE_MOD)
3142 blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
3143 else
3144 blk_queue_rq_timeout(sdp->request_queue,
3145 SD_MOD_TIMEOUT);
3146 }
3147
3148 device_initialize(&sdkp->dev);
3149 sdkp->dev.parent = get_device(dev);
3150 sdkp->dev.class = &sd_disk_class;
3151 dev_set_name(&sdkp->dev, "%s", dev_name(dev));
3152
3153 error = device_add(&sdkp->dev);
3154 if (error) {
3155 put_device(&sdkp->dev);
3156 goto out;
3157 }
3158
3159 dev_set_drvdata(dev, sdkp);
3160
3161 get_device(&sdkp->dev); /* prevent release before async_schedule */
3162 async_schedule_domain(sd_probe_async, sdkp, &scsi_sd_probe_domain);
3163
3164 return 0;
3165
3166 out_free_index:
3167 spin_lock(&sd_index_lock);
3168 ida_remove(&sd_index_ida, index);
3169 spin_unlock(&sd_index_lock);
3170 out_put:
3171 put_disk(gd);
3172 out_free:
3173 kfree(sdkp);
3174 out:
3175 scsi_autopm_put_device(sdp);
3176 return error;
3177 }
3178
3179 /**
3180 * sd_remove - called whenever a scsi disk (previously recognized by
3181 * sd_probe) is detached from the system. It is called (potentially
3182 * multiple times) during sd module unload.
3183 * @sdp: pointer to mid level scsi device object
3184 *
3185 * Note: this function is invoked from the scsi mid-level.
3186 * This function potentially frees up a device name (e.g. /dev/sdc)
3187 * that could be re-used by a subsequent sd_probe().
3188 * This function is not called when the built-in sd driver is "exit-ed".
3189 **/
sd_remove(struct device * dev)3190 static int sd_remove(struct device *dev)
3191 {
3192 struct scsi_disk *sdkp;
3193 dev_t devt;
3194
3195 sdkp = dev_get_drvdata(dev);
3196 devt = disk_devt(sdkp->disk);
3197 scsi_autopm_get_device(sdkp->device);
3198
3199 async_synchronize_full_domain(&scsi_sd_pm_domain);
3200 async_synchronize_full_domain(&scsi_sd_probe_domain);
3201 device_del(&sdkp->dev);
3202 del_gendisk(sdkp->disk);
3203 sd_shutdown(dev);
3204
3205 blk_register_region(devt, SD_MINORS, NULL,
3206 sd_default_probe, NULL, NULL);
3207
3208 mutex_lock(&sd_ref_mutex);
3209 dev_set_drvdata(dev, NULL);
3210 put_device(&sdkp->dev);
3211 mutex_unlock(&sd_ref_mutex);
3212
3213 return 0;
3214 }
3215
3216 /**
3217 * scsi_disk_release - Called to free the scsi_disk structure
3218 * @dev: pointer to embedded class device
3219 *
3220 * sd_ref_mutex must be held entering this routine. Because it is
3221 * called on last put, you should always use the scsi_disk_get()
3222 * scsi_disk_put() helpers which manipulate the semaphore directly
3223 * and never do a direct put_device.
3224 **/
scsi_disk_release(struct device * dev)3225 static void scsi_disk_release(struct device *dev)
3226 {
3227 struct scsi_disk *sdkp = to_scsi_disk(dev);
3228 struct gendisk *disk = sdkp->disk;
3229 struct request_queue *q = disk->queue;
3230
3231 spin_lock(&sd_index_lock);
3232 ida_remove(&sd_index_ida, sdkp->index);
3233 spin_unlock(&sd_index_lock);
3234
3235 /*
3236 * Wait until all requests that are in progress have completed.
3237 * This is necessary to avoid that e.g. scsi_end_request() crashes
3238 * due to clearing the disk->private_data pointer. Wait from inside
3239 * scsi_disk_release() instead of from sd_release() to avoid that
3240 * freezing and unfreezing the request queue affects user space I/O
3241 * in case multiple processes open a /dev/sd... node concurrently.
3242 */
3243 blk_mq_freeze_queue(q);
3244 blk_mq_unfreeze_queue(q);
3245
3246 disk->private_data = NULL;
3247 put_disk(disk);
3248 put_device(&sdkp->device->sdev_gendev);
3249
3250 kfree(sdkp);
3251 }
3252
sd_start_stop_device(struct scsi_disk * sdkp,int start)3253 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
3254 {
3255 unsigned char cmd[6] = { START_STOP }; /* START_VALID */
3256 struct scsi_sense_hdr sshdr;
3257 struct scsi_device *sdp = sdkp->device;
3258 int res;
3259
3260 if (start)
3261 cmd[4] |= 1; /* START */
3262
3263 if (sdp->start_stop_pwr_cond)
3264 cmd[4] |= start ? 1 << 4 : 3 << 4; /* Active or Standby */
3265
3266 if (!scsi_device_online(sdp))
3267 return -ENODEV;
3268
3269 res = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
3270 SD_TIMEOUT, SD_MAX_RETRIES, NULL, REQ_PM);
3271 if (res) {
3272 sd_print_result(sdkp, "Start/Stop Unit failed", res);
3273 if (driver_byte(res) & DRIVER_SENSE)
3274 sd_print_sense_hdr(sdkp, &sshdr);
3275 if (scsi_sense_valid(&sshdr) &&
3276 /* 0x3a is medium not present */
3277 sshdr.asc == 0x3a)
3278 res = 0;
3279 }
3280
3281 /* SCSI error codes must not go to the generic layer */
3282 if (res)
3283 return -EIO;
3284
3285 return 0;
3286 }
3287
3288 /*
3289 * Send a SYNCHRONIZE CACHE instruction down to the device through
3290 * the normal SCSI command structure. Wait for the command to
3291 * complete.
3292 */
sd_shutdown(struct device * dev)3293 static void sd_shutdown(struct device *dev)
3294 {
3295 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3296
3297 if (!sdkp)
3298 return; /* this can happen */
3299
3300 if (pm_runtime_suspended(dev))
3301 return;
3302
3303 if (sdkp->WCE && sdkp->media_present) {
3304 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
3305 sd_sync_cache(sdkp);
3306 }
3307
3308 if (system_state != SYSTEM_RESTART && sdkp->device->manage_start_stop) {
3309 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
3310 sd_start_stop_device(sdkp, 0);
3311 }
3312 }
3313
sd_suspend_common(struct device * dev,bool ignore_stop_errors)3314 static int sd_suspend_common(struct device *dev, bool ignore_stop_errors)
3315 {
3316 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3317 int ret = 0;
3318
3319 if (!sdkp) /* E.g.: runtime suspend following sd_remove() */
3320 return 0;
3321
3322 if (sdkp->WCE && sdkp->media_present) {
3323 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
3324 ret = sd_sync_cache(sdkp);
3325 if (ret) {
3326 /* ignore OFFLINE device */
3327 if (ret == -ENODEV)
3328 ret = 0;
3329 goto done;
3330 }
3331 }
3332
3333 if (sdkp->device->manage_start_stop) {
3334 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
3335 /* an error is not worth aborting a system sleep */
3336 ret = sd_start_stop_device(sdkp, 0);
3337 if (ignore_stop_errors)
3338 ret = 0;
3339 }
3340
3341 done:
3342 return ret;
3343 }
3344
sd_suspend_system(struct device * dev)3345 static int sd_suspend_system(struct device *dev)
3346 {
3347 return sd_suspend_common(dev, true);
3348 }
3349
sd_suspend_runtime(struct device * dev)3350 static int sd_suspend_runtime(struct device *dev)
3351 {
3352 return sd_suspend_common(dev, false);
3353 }
3354
sd_resume(struct device * dev)3355 static int sd_resume(struct device *dev)
3356 {
3357 struct scsi_disk *sdkp = dev_get_drvdata(dev);
3358
3359 if (!sdkp) /* E.g.: runtime resume at the start of sd_probe() */
3360 return 0;
3361
3362 if (!sdkp->device->manage_start_stop)
3363 return 0;
3364
3365 sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
3366 return sd_start_stop_device(sdkp, 1);
3367 }
3368
3369 /**
3370 * init_sd - entry point for this driver (both when built in or when
3371 * a module).
3372 *
3373 * Note: this function registers this driver with the scsi mid-level.
3374 **/
init_sd(void)3375 static int __init init_sd(void)
3376 {
3377 int majors = 0, i, err;
3378
3379 SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
3380
3381 for (i = 0; i < SD_MAJORS; i++) {
3382 if (register_blkdev(sd_major(i), "sd") != 0)
3383 continue;
3384 majors++;
3385 blk_register_region(sd_major(i), SD_MINORS, NULL,
3386 sd_default_probe, NULL, NULL);
3387 }
3388
3389 if (!majors)
3390 return -ENODEV;
3391
3392 err = class_register(&sd_disk_class);
3393 if (err)
3394 goto err_out;
3395
3396 sd_cdb_cache = kmem_cache_create("sd_ext_cdb", SD_EXT_CDB_SIZE,
3397 0, 0, NULL);
3398 if (!sd_cdb_cache) {
3399 printk(KERN_ERR "sd: can't init extended cdb cache\n");
3400 err = -ENOMEM;
3401 goto err_out_class;
3402 }
3403
3404 sd_cdb_pool = mempool_create_slab_pool(SD_MEMPOOL_SIZE, sd_cdb_cache);
3405 if (!sd_cdb_pool) {
3406 printk(KERN_ERR "sd: can't init extended cdb pool\n");
3407 err = -ENOMEM;
3408 goto err_out_cache;
3409 }
3410
3411 err = scsi_register_driver(&sd_template.gendrv);
3412 if (err)
3413 goto err_out_driver;
3414
3415 return 0;
3416
3417 err_out_driver:
3418 mempool_destroy(sd_cdb_pool);
3419
3420 err_out_cache:
3421 kmem_cache_destroy(sd_cdb_cache);
3422
3423 err_out_class:
3424 class_unregister(&sd_disk_class);
3425 err_out:
3426 for (i = 0; i < SD_MAJORS; i++)
3427 unregister_blkdev(sd_major(i), "sd");
3428 return err;
3429 }
3430
3431 /**
3432 * exit_sd - exit point for this driver (when it is a module).
3433 *
3434 * Note: this function unregisters this driver from the scsi mid-level.
3435 **/
exit_sd(void)3436 static void __exit exit_sd(void)
3437 {
3438 int i;
3439
3440 SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
3441
3442 scsi_unregister_driver(&sd_template.gendrv);
3443 mempool_destroy(sd_cdb_pool);
3444 kmem_cache_destroy(sd_cdb_cache);
3445
3446 class_unregister(&sd_disk_class);
3447
3448 for (i = 0; i < SD_MAJORS; i++) {
3449 blk_unregister_region(sd_major(i), SD_MINORS);
3450 unregister_blkdev(sd_major(i), "sd");
3451 }
3452 }
3453
3454 module_init(init_sd);
3455 module_exit(exit_sd);
3456
sd_print_sense_hdr(struct scsi_disk * sdkp,struct scsi_sense_hdr * sshdr)3457 static void sd_print_sense_hdr(struct scsi_disk *sdkp,
3458 struct scsi_sense_hdr *sshdr)
3459 {
3460 scsi_print_sense_hdr(sdkp->device,
3461 sdkp->disk ? sdkp->disk->disk_name : NULL, sshdr);
3462 }
3463
sd_print_result(const struct scsi_disk * sdkp,const char * msg,int result)3464 static void sd_print_result(const struct scsi_disk *sdkp, const char *msg,
3465 int result)
3466 {
3467 const char *hb_string = scsi_hostbyte_string(result);
3468 const char *db_string = scsi_driverbyte_string(result);
3469
3470 if (hb_string || db_string)
3471 sd_printk(KERN_INFO, sdkp,
3472 "%s: Result: hostbyte=%s driverbyte=%s\n", msg,
3473 hb_string ? hb_string : "invalid",
3474 db_string ? db_string : "invalid");
3475 else
3476 sd_printk(KERN_INFO, sdkp,
3477 "%s: Result: hostbyte=0x%02x driverbyte=0x%02x\n",
3478 msg, host_byte(result), driver_byte(result));
3479 }
3480
3481