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