[SCSI] sd: Detach DIF from block integrity infrastructure
[safe/jmp/linux-2.6] / drivers / scsi / sd.c
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 <asm/uaccess.h>
53 #include <asm/unaligned.h>
54
55 #include <scsi/scsi.h>
56 #include <scsi/scsi_cmnd.h>
57 #include <scsi/scsi_dbg.h>
58 #include <scsi/scsi_device.h>
59 #include <scsi/scsi_driver.h>
60 #include <scsi/scsi_eh.h>
61 #include <scsi/scsi_host.h>
62 #include <scsi/scsi_ioctl.h>
63 #include <scsi/scsicam.h>
64
65 #include "sd.h"
66 #include "scsi_logging.h"
67
68 MODULE_AUTHOR("Eric Youngdale");
69 MODULE_DESCRIPTION("SCSI disk (sd) driver");
70 MODULE_LICENSE("GPL");
71
72 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
73 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
74 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
75 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
76 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
77 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
78 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
79 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
80 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
81 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
82 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
88 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
89 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
90 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
91
92 #if !defined(CONFIG_DEBUG_BLOCK_EXT_DEVT)
93 #define SD_MINORS       16
94 #else
95 #define SD_MINORS       0
96 #endif
97
98 static int  sd_revalidate_disk(struct gendisk *);
99 static int  sd_probe(struct device *);
100 static int  sd_remove(struct device *);
101 static void sd_shutdown(struct device *);
102 static int sd_suspend(struct device *, pm_message_t state);
103 static int sd_resume(struct device *);
104 static void sd_rescan(struct device *);
105 static int sd_done(struct scsi_cmnd *);
106 static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer);
107 static void scsi_disk_release(struct device *cdev);
108 static void sd_print_sense_hdr(struct scsi_disk *, struct scsi_sense_hdr *);
109 static void sd_print_result(struct scsi_disk *, int);
110
111 static DEFINE_SPINLOCK(sd_index_lock);
112 static DEFINE_IDA(sd_index_ida);
113
114 /* This semaphore is used to mediate the 0->1 reference get in the
115  * face of object destruction (i.e. we can't allow a get on an
116  * object after last put) */
117 static DEFINE_MUTEX(sd_ref_mutex);
118
119 static const char *sd_cache_types[] = {
120         "write through", "none", "write back",
121         "write back, no read (daft)"
122 };
123
124 static ssize_t
125 sd_store_cache_type(struct device *dev, struct device_attribute *attr,
126                     const char *buf, size_t count)
127 {
128         int i, ct = -1, rcd, wce, sp;
129         struct scsi_disk *sdkp = to_scsi_disk(dev);
130         struct scsi_device *sdp = sdkp->device;
131         char buffer[64];
132         char *buffer_data;
133         struct scsi_mode_data data;
134         struct scsi_sense_hdr sshdr;
135         int len;
136
137         if (sdp->type != TYPE_DISK)
138                 /* no cache control on RBC devices; theoretically they
139                  * can do it, but there's probably so many exceptions
140                  * it's not worth the risk */
141                 return -EINVAL;
142
143         for (i = 0; i < ARRAY_SIZE(sd_cache_types); i++) {
144                 const int len = strlen(sd_cache_types[i]);
145                 if (strncmp(sd_cache_types[i], buf, len) == 0 &&
146                     buf[len] == '\n') {
147                         ct = i;
148                         break;
149                 }
150         }
151         if (ct < 0)
152                 return -EINVAL;
153         rcd = ct & 0x01 ? 1 : 0;
154         wce = ct & 0x02 ? 1 : 0;
155         if (scsi_mode_sense(sdp, 0x08, 8, buffer, sizeof(buffer), SD_TIMEOUT,
156                             SD_MAX_RETRIES, &data, NULL))
157                 return -EINVAL;
158         len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
159                   data.block_descriptor_length);
160         buffer_data = buffer + data.header_length +
161                 data.block_descriptor_length;
162         buffer_data[2] &= ~0x05;
163         buffer_data[2] |= wce << 2 | rcd;
164         sp = buffer_data[0] & 0x80 ? 1 : 0;
165
166         if (scsi_mode_select(sdp, 1, sp, 8, buffer_data, len, SD_TIMEOUT,
167                              SD_MAX_RETRIES, &data, &sshdr)) {
168                 if (scsi_sense_valid(&sshdr))
169                         sd_print_sense_hdr(sdkp, &sshdr);
170                 return -EINVAL;
171         }
172         revalidate_disk(sdkp->disk);
173         return count;
174 }
175
176 static ssize_t
177 sd_store_manage_start_stop(struct device *dev, struct device_attribute *attr,
178                            const char *buf, size_t count)
179 {
180         struct scsi_disk *sdkp = to_scsi_disk(dev);
181         struct scsi_device *sdp = sdkp->device;
182
183         if (!capable(CAP_SYS_ADMIN))
184                 return -EACCES;
185
186         sdp->manage_start_stop = simple_strtoul(buf, NULL, 10);
187
188         return count;
189 }
190
191 static ssize_t
192 sd_store_allow_restart(struct device *dev, struct device_attribute *attr,
193                        const char *buf, size_t count)
194 {
195         struct scsi_disk *sdkp = to_scsi_disk(dev);
196         struct scsi_device *sdp = sdkp->device;
197
198         if (!capable(CAP_SYS_ADMIN))
199                 return -EACCES;
200
201         if (sdp->type != TYPE_DISK)
202                 return -EINVAL;
203
204         sdp->allow_restart = simple_strtoul(buf, NULL, 10);
205
206         return count;
207 }
208
209 static ssize_t
210 sd_show_cache_type(struct device *dev, struct device_attribute *attr,
211                    char *buf)
212 {
213         struct scsi_disk *sdkp = to_scsi_disk(dev);
214         int ct = sdkp->RCD + 2*sdkp->WCE;
215
216         return snprintf(buf, 40, "%s\n", sd_cache_types[ct]);
217 }
218
219 static ssize_t
220 sd_show_fua(struct device *dev, struct device_attribute *attr, char *buf)
221 {
222         struct scsi_disk *sdkp = to_scsi_disk(dev);
223
224         return snprintf(buf, 20, "%u\n", sdkp->DPOFUA);
225 }
226
227 static ssize_t
228 sd_show_manage_start_stop(struct device *dev, struct device_attribute *attr,
229                           char *buf)
230 {
231         struct scsi_disk *sdkp = to_scsi_disk(dev);
232         struct scsi_device *sdp = sdkp->device;
233
234         return snprintf(buf, 20, "%u\n", sdp->manage_start_stop);
235 }
236
237 static ssize_t
238 sd_show_allow_restart(struct device *dev, struct device_attribute *attr,
239                       char *buf)
240 {
241         struct scsi_disk *sdkp = to_scsi_disk(dev);
242
243         return snprintf(buf, 40, "%d\n", sdkp->device->allow_restart);
244 }
245
246 static ssize_t
247 sd_show_protection_type(struct device *dev, struct device_attribute *attr,
248                         char *buf)
249 {
250         struct scsi_disk *sdkp = to_scsi_disk(dev);
251
252         return snprintf(buf, 20, "%u\n", sdkp->protection_type);
253 }
254
255 static ssize_t
256 sd_show_app_tag_own(struct device *dev, struct device_attribute *attr,
257                     char *buf)
258 {
259         struct scsi_disk *sdkp = to_scsi_disk(dev);
260
261         return snprintf(buf, 20, "%u\n", sdkp->ATO);
262 }
263
264 static struct device_attribute sd_disk_attrs[] = {
265         __ATTR(cache_type, S_IRUGO|S_IWUSR, sd_show_cache_type,
266                sd_store_cache_type),
267         __ATTR(FUA, S_IRUGO, sd_show_fua, NULL),
268         __ATTR(allow_restart, S_IRUGO|S_IWUSR, sd_show_allow_restart,
269                sd_store_allow_restart),
270         __ATTR(manage_start_stop, S_IRUGO|S_IWUSR, sd_show_manage_start_stop,
271                sd_store_manage_start_stop),
272         __ATTR(protection_type, S_IRUGO, sd_show_protection_type, NULL),
273         __ATTR(app_tag_own, S_IRUGO, sd_show_app_tag_own, NULL),
274         __ATTR_NULL,
275 };
276
277 static struct class sd_disk_class = {
278         .name           = "scsi_disk",
279         .owner          = THIS_MODULE,
280         .dev_release    = scsi_disk_release,
281         .dev_attrs      = sd_disk_attrs,
282 };
283
284 static struct scsi_driver sd_template = {
285         .owner                  = THIS_MODULE,
286         .gendrv = {
287                 .name           = "sd",
288                 .probe          = sd_probe,
289                 .remove         = sd_remove,
290                 .suspend        = sd_suspend,
291                 .resume         = sd_resume,
292                 .shutdown       = sd_shutdown,
293         },
294         .rescan                 = sd_rescan,
295         .done                   = sd_done,
296 };
297
298 /*
299  * Device no to disk mapping:
300  * 
301  *       major         disc2     disc  p1
302  *   |............|.............|....|....| <- dev_t
303  *    31        20 19          8 7  4 3  0
304  * 
305  * Inside a major, we have 16k disks, however mapped non-
306  * contiguously. The first 16 disks are for major0, the next
307  * ones with major1, ... Disk 256 is for major0 again, disk 272 
308  * for major1, ... 
309  * As we stay compatible with our numbering scheme, we can reuse 
310  * the well-know SCSI majors 8, 65--71, 136--143.
311  */
312 static int sd_major(int major_idx)
313 {
314         switch (major_idx) {
315         case 0:
316                 return SCSI_DISK0_MAJOR;
317         case 1 ... 7:
318                 return SCSI_DISK1_MAJOR + major_idx - 1;
319         case 8 ... 15:
320                 return SCSI_DISK8_MAJOR + major_idx - 8;
321         default:
322                 BUG();
323                 return 0;       /* shut up gcc */
324         }
325 }
326
327 static struct scsi_disk *__scsi_disk_get(struct gendisk *disk)
328 {
329         struct scsi_disk *sdkp = NULL;
330
331         if (disk->private_data) {
332                 sdkp = scsi_disk(disk);
333                 if (scsi_device_get(sdkp->device) == 0)
334                         get_device(&sdkp->dev);
335                 else
336                         sdkp = NULL;
337         }
338         return sdkp;
339 }
340
341 static struct scsi_disk *scsi_disk_get(struct gendisk *disk)
342 {
343         struct scsi_disk *sdkp;
344
345         mutex_lock(&sd_ref_mutex);
346         sdkp = __scsi_disk_get(disk);
347         mutex_unlock(&sd_ref_mutex);
348         return sdkp;
349 }
350
351 static struct scsi_disk *scsi_disk_get_from_dev(struct device *dev)
352 {
353         struct scsi_disk *sdkp;
354
355         mutex_lock(&sd_ref_mutex);
356         sdkp = dev_get_drvdata(dev);
357         if (sdkp)
358                 sdkp = __scsi_disk_get(sdkp->disk);
359         mutex_unlock(&sd_ref_mutex);
360         return sdkp;
361 }
362
363 static void scsi_disk_put(struct scsi_disk *sdkp)
364 {
365         struct scsi_device *sdev = sdkp->device;
366
367         mutex_lock(&sd_ref_mutex);
368         put_device(&sdkp->dev);
369         scsi_device_put(sdev);
370         mutex_unlock(&sd_ref_mutex);
371 }
372
373 static void sd_prot_op(struct scsi_cmnd *scmd, unsigned int dif)
374 {
375         unsigned int prot_op = SCSI_PROT_NORMAL;
376         unsigned int dix = scsi_prot_sg_count(scmd);
377
378         if (scmd->sc_data_direction == DMA_FROM_DEVICE) {
379                 if (dif && dix)
380                         prot_op = SCSI_PROT_READ_PASS;
381                 else if (dif && !dix)
382                         prot_op = SCSI_PROT_READ_STRIP;
383                 else if (!dif && dix)
384                         prot_op = SCSI_PROT_READ_INSERT;
385         } else {
386                 if (dif && dix)
387                         prot_op = SCSI_PROT_WRITE_PASS;
388                 else if (dif && !dix)
389                         prot_op = SCSI_PROT_WRITE_INSERT;
390                 else if (!dif && dix)
391                         prot_op = SCSI_PROT_WRITE_STRIP;
392         }
393
394         scsi_set_prot_op(scmd, prot_op);
395         scsi_set_prot_type(scmd, dif);
396 }
397
398 /**
399  *      sd_init_command - build a scsi (read or write) command from
400  *      information in the request structure.
401  *      @SCpnt: pointer to mid-level's per scsi command structure that
402  *      contains request and into which the scsi command is written
403  *
404  *      Returns 1 if successful and 0 if error (or cannot be done now).
405  **/
406 static int sd_prep_fn(struct request_queue *q, struct request *rq)
407 {
408         struct scsi_cmnd *SCpnt;
409         struct scsi_device *sdp = q->queuedata;
410         struct gendisk *disk = rq->rq_disk;
411         struct scsi_disk *sdkp;
412         sector_t block = blk_rq_pos(rq);
413         sector_t threshold;
414         unsigned int this_count = blk_rq_sectors(rq);
415         int ret, host_dif;
416
417         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
418                 ret = scsi_setup_blk_pc_cmnd(sdp, rq);
419                 goto out;
420         } else if (rq->cmd_type != REQ_TYPE_FS) {
421                 ret = BLKPREP_KILL;
422                 goto out;
423         }
424         ret = scsi_setup_fs_cmnd(sdp, rq);
425         if (ret != BLKPREP_OK)
426                 goto out;
427         SCpnt = rq->special;
428         sdkp = scsi_disk(disk);
429
430         /* from here on until we're complete, any goto out
431          * is used for a killable error condition */
432         ret = BLKPREP_KILL;
433
434         SCSI_LOG_HLQUEUE(1, scmd_printk(KERN_INFO, SCpnt,
435                                         "sd_init_command: block=%llu, "
436                                         "count=%d\n",
437                                         (unsigned long long)block,
438                                         this_count));
439
440         if (!sdp || !scsi_device_online(sdp) ||
441             block + blk_rq_sectors(rq) > get_capacity(disk)) {
442                 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
443                                                 "Finishing %u sectors\n",
444                                                 blk_rq_sectors(rq)));
445                 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
446                                                 "Retry with 0x%p\n", SCpnt));
447                 goto out;
448         }
449
450         if (sdp->changed) {
451                 /*
452                  * quietly refuse to do anything to a changed disc until 
453                  * the changed bit has been reset
454                  */
455                 /* printk("SCSI disk has been changed. Prohibiting further I/O.\n"); */
456                 goto out;
457         }
458
459         /*
460          * Some SD card readers can't handle multi-sector accesses which touch
461          * the last one or two hardware sectors.  Split accesses as needed.
462          */
463         threshold = get_capacity(disk) - SD_LAST_BUGGY_SECTORS *
464                 (sdp->sector_size / 512);
465
466         if (unlikely(sdp->last_sector_bug && block + this_count > threshold)) {
467                 if (block < threshold) {
468                         /* Access up to the threshold but not beyond */
469                         this_count = threshold - block;
470                 } else {
471                         /* Access only a single hardware sector */
472                         this_count = sdp->sector_size / 512;
473                 }
474         }
475
476         SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt, "block=%llu\n",
477                                         (unsigned long long)block));
478
479         /*
480          * If we have a 1K hardware sectorsize, prevent access to single
481          * 512 byte sectors.  In theory we could handle this - in fact
482          * the scsi cdrom driver must be able to handle this because
483          * we typically use 1K blocksizes, and cdroms typically have
484          * 2K hardware sectorsizes.  Of course, things are simpler
485          * with the cdrom, since it is read-only.  For performance
486          * reasons, the filesystems should be able to handle this
487          * and not force the scsi disk driver to use bounce buffers
488          * for this.
489          */
490         if (sdp->sector_size == 1024) {
491                 if ((block & 1) || (blk_rq_sectors(rq) & 1)) {
492                         scmd_printk(KERN_ERR, SCpnt,
493                                     "Bad block number requested\n");
494                         goto out;
495                 } else {
496                         block = block >> 1;
497                         this_count = this_count >> 1;
498                 }
499         }
500         if (sdp->sector_size == 2048) {
501                 if ((block & 3) || (blk_rq_sectors(rq) & 3)) {
502                         scmd_printk(KERN_ERR, SCpnt,
503                                     "Bad block number requested\n");
504                         goto out;
505                 } else {
506                         block = block >> 2;
507                         this_count = this_count >> 2;
508                 }
509         }
510         if (sdp->sector_size == 4096) {
511                 if ((block & 7) || (blk_rq_sectors(rq) & 7)) {
512                         scmd_printk(KERN_ERR, SCpnt,
513                                     "Bad block number requested\n");
514                         goto out;
515                 } else {
516                         block = block >> 3;
517                         this_count = this_count >> 3;
518                 }
519         }
520         if (rq_data_dir(rq) == WRITE) {
521                 if (!sdp->writeable) {
522                         goto out;
523                 }
524                 SCpnt->cmnd[0] = WRITE_6;
525                 SCpnt->sc_data_direction = DMA_TO_DEVICE;
526
527                 if (blk_integrity_rq(rq) &&
528                     sd_dif_prepare(rq, block, sdp->sector_size) == -EIO)
529                         goto out;
530
531         } else if (rq_data_dir(rq) == READ) {
532                 SCpnt->cmnd[0] = READ_6;
533                 SCpnt->sc_data_direction = DMA_FROM_DEVICE;
534         } else {
535                 scmd_printk(KERN_ERR, SCpnt, "Unknown command %x\n", rq->cmd_flags);
536                 goto out;
537         }
538
539         SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
540                                         "%s %d/%u 512 byte blocks.\n",
541                                         (rq_data_dir(rq) == WRITE) ?
542                                         "writing" : "reading", this_count,
543                                         blk_rq_sectors(rq)));
544
545         /* Set RDPROTECT/WRPROTECT if disk is formatted with DIF */
546         host_dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
547         if (host_dif)
548                 SCpnt->cmnd[1] = 1 << 5;
549         else
550                 SCpnt->cmnd[1] = 0;
551
552         if (block > 0xffffffff) {
553                 SCpnt->cmnd[0] += READ_16 - READ_6;
554                 SCpnt->cmnd[1] |= blk_fua_rq(rq) ? 0x8 : 0;
555                 SCpnt->cmnd[2] = sizeof(block) > 4 ? (unsigned char) (block >> 56) & 0xff : 0;
556                 SCpnt->cmnd[3] = sizeof(block) > 4 ? (unsigned char) (block >> 48) & 0xff : 0;
557                 SCpnt->cmnd[4] = sizeof(block) > 4 ? (unsigned char) (block >> 40) & 0xff : 0;
558                 SCpnt->cmnd[5] = sizeof(block) > 4 ? (unsigned char) (block >> 32) & 0xff : 0;
559                 SCpnt->cmnd[6] = (unsigned char) (block >> 24) & 0xff;
560                 SCpnt->cmnd[7] = (unsigned char) (block >> 16) & 0xff;
561                 SCpnt->cmnd[8] = (unsigned char) (block >> 8) & 0xff;
562                 SCpnt->cmnd[9] = (unsigned char) block & 0xff;
563                 SCpnt->cmnd[10] = (unsigned char) (this_count >> 24) & 0xff;
564                 SCpnt->cmnd[11] = (unsigned char) (this_count >> 16) & 0xff;
565                 SCpnt->cmnd[12] = (unsigned char) (this_count >> 8) & 0xff;
566                 SCpnt->cmnd[13] = (unsigned char) this_count & 0xff;
567                 SCpnt->cmnd[14] = SCpnt->cmnd[15] = 0;
568         } else if ((this_count > 0xff) || (block > 0x1fffff) ||
569                    scsi_device_protection(SCpnt->device) ||
570                    SCpnt->device->use_10_for_rw) {
571                 if (this_count > 0xffff)
572                         this_count = 0xffff;
573
574                 SCpnt->cmnd[0] += READ_10 - READ_6;
575                 SCpnt->cmnd[1] |= blk_fua_rq(rq) ? 0x8 : 0;
576                 SCpnt->cmnd[2] = (unsigned char) (block >> 24) & 0xff;
577                 SCpnt->cmnd[3] = (unsigned char) (block >> 16) & 0xff;
578                 SCpnt->cmnd[4] = (unsigned char) (block >> 8) & 0xff;
579                 SCpnt->cmnd[5] = (unsigned char) block & 0xff;
580                 SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
581                 SCpnt->cmnd[7] = (unsigned char) (this_count >> 8) & 0xff;
582                 SCpnt->cmnd[8] = (unsigned char) this_count & 0xff;
583         } else {
584                 if (unlikely(blk_fua_rq(rq))) {
585                         /*
586                          * This happens only if this drive failed
587                          * 10byte rw command with ILLEGAL_REQUEST
588                          * during operation and thus turned off
589                          * use_10_for_rw.
590                          */
591                         scmd_printk(KERN_ERR, SCpnt,
592                                     "FUA write on READ/WRITE(6) drive\n");
593                         goto out;
594                 }
595
596                 SCpnt->cmnd[1] |= (unsigned char) ((block >> 16) & 0x1f);
597                 SCpnt->cmnd[2] = (unsigned char) ((block >> 8) & 0xff);
598                 SCpnt->cmnd[3] = (unsigned char) block & 0xff;
599                 SCpnt->cmnd[4] = (unsigned char) this_count;
600                 SCpnt->cmnd[5] = 0;
601         }
602         SCpnt->sdb.length = this_count * sdp->sector_size;
603
604         /* If DIF or DIX is enabled, tell HBA how to handle request */
605         if (host_dif || scsi_prot_sg_count(SCpnt))
606                 sd_prot_op(SCpnt, host_dif);
607
608         /*
609          * We shouldn't disconnect in the middle of a sector, so with a dumb
610          * host adapter, it's safe to assume that we can at least transfer
611          * this many bytes between each connect / disconnect.
612          */
613         SCpnt->transfersize = sdp->sector_size;
614         SCpnt->underflow = this_count << 9;
615         SCpnt->allowed = SD_MAX_RETRIES;
616
617         /*
618          * This indicates that the command is ready from our end to be
619          * queued.
620          */
621         ret = BLKPREP_OK;
622  out:
623         return scsi_prep_return(q, rq, ret);
624 }
625
626 /**
627  *      sd_open - open a scsi disk device
628  *      @inode: only i_rdev member may be used
629  *      @filp: only f_mode and f_flags may be used
630  *
631  *      Returns 0 if successful. Returns a negated errno value in case 
632  *      of error.
633  *
634  *      Note: This can be called from a user context (e.g. fsck(1) )
635  *      or from within the kernel (e.g. as a result of a mount(1) ).
636  *      In the latter case @inode and @filp carry an abridged amount
637  *      of information as noted above.
638  **/
639 static int sd_open(struct block_device *bdev, fmode_t mode)
640 {
641         struct scsi_disk *sdkp = scsi_disk_get(bdev->bd_disk);
642         struct scsi_device *sdev;
643         int retval;
644
645         if (!sdkp)
646                 return -ENXIO;
647
648         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
649
650         sdev = sdkp->device;
651
652         /*
653          * If the device is in error recovery, wait until it is done.
654          * If the device is offline, then disallow any access to it.
655          */
656         retval = -ENXIO;
657         if (!scsi_block_when_processing_errors(sdev))
658                 goto error_out;
659
660         if (sdev->removable || sdkp->write_prot)
661                 check_disk_change(bdev);
662
663         /*
664          * If the drive is empty, just let the open fail.
665          */
666         retval = -ENOMEDIUM;
667         if (sdev->removable && !sdkp->media_present && !(mode & FMODE_NDELAY))
668                 goto error_out;
669
670         /*
671          * If the device has the write protect tab set, have the open fail
672          * if the user expects to be able to write to the thing.
673          */
674         retval = -EROFS;
675         if (sdkp->write_prot && (mode & FMODE_WRITE))
676                 goto error_out;
677
678         /*
679          * It is possible that the disk changing stuff resulted in
680          * the device being taken offline.  If this is the case,
681          * report this to the user, and don't pretend that the
682          * open actually succeeded.
683          */
684         retval = -ENXIO;
685         if (!scsi_device_online(sdev))
686                 goto error_out;
687
688         if (!sdkp->openers++ && sdev->removable) {
689                 if (scsi_block_when_processing_errors(sdev))
690                         scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
691         }
692
693         return 0;
694
695 error_out:
696         scsi_disk_put(sdkp);
697         return retval;  
698 }
699
700 /**
701  *      sd_release - invoked when the (last) close(2) is called on this
702  *      scsi disk.
703  *      @inode: only i_rdev member may be used
704  *      @filp: only f_mode and f_flags may be used
705  *
706  *      Returns 0. 
707  *
708  *      Note: may block (uninterruptible) if error recovery is underway
709  *      on this disk.
710  **/
711 static int sd_release(struct gendisk *disk, fmode_t mode)
712 {
713         struct scsi_disk *sdkp = scsi_disk(disk);
714         struct scsi_device *sdev = sdkp->device;
715
716         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
717
718         if (!--sdkp->openers && sdev->removable) {
719                 if (scsi_block_when_processing_errors(sdev))
720                         scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
721         }
722
723         /*
724          * XXX and what if there are packets in flight and this close()
725          * XXX is followed by a "rmmod sd_mod"?
726          */
727         scsi_disk_put(sdkp);
728         return 0;
729 }
730
731 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
732 {
733         struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
734         struct scsi_device *sdp = sdkp->device;
735         struct Scsi_Host *host = sdp->host;
736         int diskinfo[4];
737
738         /* default to most commonly used values */
739         diskinfo[0] = 0x40;     /* 1 << 6 */
740         diskinfo[1] = 0x20;     /* 1 << 5 */
741         diskinfo[2] = sdkp->capacity >> 11;
742         
743         /* override with calculated, extended default, or driver values */
744         if (host->hostt->bios_param)
745                 host->hostt->bios_param(sdp, bdev, sdkp->capacity, diskinfo);
746         else
747                 scsicam_bios_param(bdev, sdkp->capacity, diskinfo);
748
749         geo->heads = diskinfo[0];
750         geo->sectors = diskinfo[1];
751         geo->cylinders = diskinfo[2];
752         return 0;
753 }
754
755 /**
756  *      sd_ioctl - process an ioctl
757  *      @inode: only i_rdev/i_bdev members may be used
758  *      @filp: only f_mode and f_flags may be used
759  *      @cmd: ioctl command number
760  *      @arg: this is third argument given to ioctl(2) system call.
761  *      Often contains a pointer.
762  *
763  *      Returns 0 if successful (some ioctls return postive numbers on
764  *      success as well). Returns a negated errno value in case of error.
765  *
766  *      Note: most ioctls are forward onto the block subsystem or further
767  *      down in the scsi subsystem.
768  **/
769 static int sd_ioctl(struct block_device *bdev, fmode_t mode,
770                     unsigned int cmd, unsigned long arg)
771 {
772         struct gendisk *disk = bdev->bd_disk;
773         struct scsi_device *sdp = scsi_disk(disk)->device;
774         void __user *p = (void __user *)arg;
775         int error;
776     
777         SCSI_LOG_IOCTL(1, printk("sd_ioctl: disk=%s, cmd=0x%x\n",
778                                                 disk->disk_name, cmd));
779
780         /*
781          * If we are in the middle of error recovery, don't let anyone
782          * else try and use this device.  Also, if error recovery fails, it
783          * may try and take the device offline, in which case all further
784          * access to the device is prohibited.
785          */
786         error = scsi_nonblockable_ioctl(sdp, cmd, p,
787                                         (mode & FMODE_NDELAY) != 0);
788         if (!scsi_block_when_processing_errors(sdp) || !error)
789                 return error;
790
791         /*
792          * Send SCSI addressing ioctls directly to mid level, send other
793          * ioctls to block level and then onto mid level if they can't be
794          * resolved.
795          */
796         switch (cmd) {
797                 case SCSI_IOCTL_GET_IDLUN:
798                 case SCSI_IOCTL_GET_BUS_NUMBER:
799                         return scsi_ioctl(sdp, cmd, p);
800                 default:
801                         error = scsi_cmd_ioctl(disk->queue, disk, mode, cmd, p);
802                         if (error != -ENOTTY)
803                                 return error;
804         }
805         return scsi_ioctl(sdp, cmd, p);
806 }
807
808 static void set_media_not_present(struct scsi_disk *sdkp)
809 {
810         sdkp->media_present = 0;
811         sdkp->capacity = 0;
812         sdkp->device->changed = 1;
813 }
814
815 /**
816  *      sd_media_changed - check if our medium changed
817  *      @disk: kernel device descriptor 
818  *
819  *      Returns 0 if not applicable or no change; 1 if change
820  *
821  *      Note: this function is invoked from the block subsystem.
822  **/
823 static int sd_media_changed(struct gendisk *disk)
824 {
825         struct scsi_disk *sdkp = scsi_disk(disk);
826         struct scsi_device *sdp = sdkp->device;
827         struct scsi_sense_hdr *sshdr = NULL;
828         int retval;
829
830         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_media_changed\n"));
831
832         if (!sdp->removable)
833                 return 0;
834
835         /*
836          * If the device is offline, don't send any commands - just pretend as
837          * if the command failed.  If the device ever comes back online, we
838          * can deal with it then.  It is only because of unrecoverable errors
839          * that we would ever take a device offline in the first place.
840          */
841         if (!scsi_device_online(sdp)) {
842                 set_media_not_present(sdkp);
843                 retval = 1;
844                 goto out;
845         }
846
847         /*
848          * Using TEST_UNIT_READY enables differentiation between drive with
849          * no cartridge loaded - NOT READY, drive with changed cartridge -
850          * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
851          *
852          * Drives that auto spin down. eg iomega jaz 1G, will be started
853          * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
854          * sd_revalidate() is called.
855          */
856         retval = -ENODEV;
857
858         if (scsi_block_when_processing_errors(sdp)) {
859                 sshdr  = kzalloc(sizeof(*sshdr), GFP_KERNEL);
860                 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, SD_MAX_RETRIES,
861                                               sshdr);
862         }
863
864         /*
865          * Unable to test, unit probably not ready.   This usually
866          * means there is no disc in the drive.  Mark as changed,
867          * and we will figure it out later once the drive is
868          * available again.
869          */
870         if (retval || (scsi_sense_valid(sshdr) &&
871                        /* 0x3a is medium not present */
872                        sshdr->asc == 0x3a)) {
873                 set_media_not_present(sdkp);
874                 retval = 1;
875                 goto out;
876         }
877
878         /*
879          * For removable scsi disk we have to recognise the presence
880          * of a disk in the drive. This is kept in the struct scsi_disk
881          * struct and tested at open !  Daniel Roche (dan@lectra.fr)
882          */
883         sdkp->media_present = 1;
884
885         retval = sdp->changed;
886         sdp->changed = 0;
887 out:
888         if (retval != sdkp->previous_state)
889                 sdev_evt_send_simple(sdp, SDEV_EVT_MEDIA_CHANGE, GFP_KERNEL);
890         sdkp->previous_state = retval;
891         kfree(sshdr);
892         return retval;
893 }
894
895 static int sd_sync_cache(struct scsi_disk *sdkp)
896 {
897         int retries, res;
898         struct scsi_device *sdp = sdkp->device;
899         struct scsi_sense_hdr sshdr;
900
901         if (!scsi_device_online(sdp))
902                 return -ENODEV;
903
904
905         for (retries = 3; retries > 0; --retries) {
906                 unsigned char cmd[10] = { 0 };
907
908                 cmd[0] = SYNCHRONIZE_CACHE;
909                 /*
910                  * Leave the rest of the command zero to indicate
911                  * flush everything.
912                  */
913                 res = scsi_execute_req(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
914                                        SD_TIMEOUT, SD_MAX_RETRIES, NULL);
915                 if (res == 0)
916                         break;
917         }
918
919         if (res) {
920                 sd_print_result(sdkp, res);
921                 if (driver_byte(res) & DRIVER_SENSE)
922                         sd_print_sense_hdr(sdkp, &sshdr);
923         }
924
925         if (res)
926                 return -EIO;
927         return 0;
928 }
929
930 static void sd_prepare_flush(struct request_queue *q, struct request *rq)
931 {
932         rq->cmd_type = REQ_TYPE_BLOCK_PC;
933         rq->timeout = SD_TIMEOUT;
934         rq->cmd[0] = SYNCHRONIZE_CACHE;
935         rq->cmd_len = 10;
936 }
937
938 static void sd_rescan(struct device *dev)
939 {
940         struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
941
942         if (sdkp) {
943                 revalidate_disk(sdkp->disk);
944                 scsi_disk_put(sdkp);
945         }
946 }
947
948
949 #ifdef CONFIG_COMPAT
950 /* 
951  * This gets directly called from VFS. When the ioctl 
952  * is not recognized we go back to the other translation paths. 
953  */
954 static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode,
955                            unsigned int cmd, unsigned long arg)
956 {
957         struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device;
958
959         /*
960          * If we are in the middle of error recovery, don't let anyone
961          * else try and use this device.  Also, if error recovery fails, it
962          * may try and take the device offline, in which case all further
963          * access to the device is prohibited.
964          */
965         if (!scsi_block_when_processing_errors(sdev))
966                 return -ENODEV;
967                
968         if (sdev->host->hostt->compat_ioctl) {
969                 int ret;
970
971                 ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg);
972
973                 return ret;
974         }
975
976         /* 
977          * Let the static ioctl translation table take care of it.
978          */
979         return -ENOIOCTLCMD; 
980 }
981 #endif
982
983 static const struct block_device_operations sd_fops = {
984         .owner                  = THIS_MODULE,
985         .open                   = sd_open,
986         .release                = sd_release,
987         .locked_ioctl           = sd_ioctl,
988         .getgeo                 = sd_getgeo,
989 #ifdef CONFIG_COMPAT
990         .compat_ioctl           = sd_compat_ioctl,
991 #endif
992         .media_changed          = sd_media_changed,
993         .revalidate_disk        = sd_revalidate_disk,
994 };
995
996 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
997 {
998         u64 start_lba = blk_rq_pos(scmd->request);
999         u64 end_lba = blk_rq_pos(scmd->request) + (scsi_bufflen(scmd) / 512);
1000         u64 bad_lba;
1001         int info_valid;
1002
1003         if (!blk_fs_request(scmd->request))
1004                 return 0;
1005
1006         info_valid = scsi_get_sense_info_fld(scmd->sense_buffer,
1007                                              SCSI_SENSE_BUFFERSIZE,
1008                                              &bad_lba);
1009         if (!info_valid)
1010                 return 0;
1011
1012         if (scsi_bufflen(scmd) <= scmd->device->sector_size)
1013                 return 0;
1014
1015         if (scmd->device->sector_size < 512) {
1016                 /* only legitimate sector_size here is 256 */
1017                 start_lba <<= 1;
1018                 end_lba <<= 1;
1019         } else {
1020                 /* be careful ... don't want any overflows */
1021                 u64 factor = scmd->device->sector_size / 512;
1022                 do_div(start_lba, factor);
1023                 do_div(end_lba, factor);
1024         }
1025
1026         /* The bad lba was reported incorrectly, we have no idea where
1027          * the error is.
1028          */
1029         if (bad_lba < start_lba  || bad_lba >= end_lba)
1030                 return 0;
1031
1032         /* This computation should always be done in terms of
1033          * the resolution of the device's medium.
1034          */
1035         return (bad_lba - start_lba) * scmd->device->sector_size;
1036 }
1037
1038 /**
1039  *      sd_done - bottom half handler: called when the lower level
1040  *      driver has completed (successfully or otherwise) a scsi command.
1041  *      @SCpnt: mid-level's per command structure.
1042  *
1043  *      Note: potentially run from within an ISR. Must not block.
1044  **/
1045 static int sd_done(struct scsi_cmnd *SCpnt)
1046 {
1047         int result = SCpnt->result;
1048         unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
1049         struct scsi_sense_hdr sshdr;
1050         int sense_valid = 0;
1051         int sense_deferred = 0;
1052
1053         if (result) {
1054                 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
1055                 if (sense_valid)
1056                         sense_deferred = scsi_sense_is_deferred(&sshdr);
1057         }
1058 #ifdef CONFIG_SCSI_LOGGING
1059         SCSI_LOG_HLCOMPLETE(1, scsi_print_result(SCpnt));
1060         if (sense_valid) {
1061                 SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
1062                                                    "sd_done: sb[respc,sk,asc,"
1063                                                    "ascq]=%x,%x,%x,%x\n",
1064                                                    sshdr.response_code,
1065                                                    sshdr.sense_key, sshdr.asc,
1066                                                    sshdr.ascq));
1067         }
1068 #endif
1069         if (driver_byte(result) != DRIVER_SENSE &&
1070             (!sense_valid || sense_deferred))
1071                 goto out;
1072
1073         switch (sshdr.sense_key) {
1074         case HARDWARE_ERROR:
1075         case MEDIUM_ERROR:
1076                 good_bytes = sd_completed_bytes(SCpnt);
1077                 break;
1078         case RECOVERED_ERROR:
1079                 good_bytes = scsi_bufflen(SCpnt);
1080                 break;
1081         case NO_SENSE:
1082                 /* This indicates a false check condition, so ignore it.  An
1083                  * unknown amount of data was transferred so treat it as an
1084                  * error.
1085                  */
1086                 scsi_print_sense("sd", SCpnt);
1087                 SCpnt->result = 0;
1088                 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1089                 break;
1090         case ABORTED_COMMAND:
1091                 if (sshdr.asc == 0x10) { /* DIF: Disk detected corruption */
1092                         scsi_print_result(SCpnt);
1093                         scsi_print_sense("sd", SCpnt);
1094                         good_bytes = sd_completed_bytes(SCpnt);
1095                 }
1096                 break;
1097         case ILLEGAL_REQUEST:
1098                 if (sshdr.asc == 0x10) { /* DIX: HBA detected corruption */
1099                         scsi_print_result(SCpnt);
1100                         scsi_print_sense("sd", SCpnt);
1101                         good_bytes = sd_completed_bytes(SCpnt);
1102                 }
1103                 break;
1104         default:
1105                 break;
1106         }
1107  out:
1108         if (rq_data_dir(SCpnt->request) == READ && scsi_prot_sg_count(SCpnt))
1109                 sd_dif_complete(SCpnt, good_bytes);
1110
1111         return good_bytes;
1112 }
1113
1114 static int media_not_present(struct scsi_disk *sdkp,
1115                              struct scsi_sense_hdr *sshdr)
1116 {
1117
1118         if (!scsi_sense_valid(sshdr))
1119                 return 0;
1120         /* not invoked for commands that could return deferred errors */
1121         if (sshdr->sense_key != NOT_READY &&
1122             sshdr->sense_key != UNIT_ATTENTION)
1123                 return 0;
1124         if (sshdr->asc != 0x3A) /* medium not present */
1125                 return 0;
1126
1127         set_media_not_present(sdkp);
1128         return 1;
1129 }
1130
1131 /*
1132  * spinup disk - called only in sd_revalidate_disk()
1133  */
1134 static void
1135 sd_spinup_disk(struct scsi_disk *sdkp)
1136 {
1137         unsigned char cmd[10];
1138         unsigned long spintime_expire = 0;
1139         int retries, spintime;
1140         unsigned int the_result;
1141         struct scsi_sense_hdr sshdr;
1142         int sense_valid = 0;
1143
1144         spintime = 0;
1145
1146         /* Spin up drives, as required.  Only do this at boot time */
1147         /* Spinup needs to be done for module loads too. */
1148         do {
1149                 retries = 0;
1150
1151                 do {
1152                         cmd[0] = TEST_UNIT_READY;
1153                         memset((void *) &cmd[1], 0, 9);
1154
1155                         the_result = scsi_execute_req(sdkp->device, cmd,
1156                                                       DMA_NONE, NULL, 0,
1157                                                       &sshdr, SD_TIMEOUT,
1158                                                       SD_MAX_RETRIES, NULL);
1159
1160                         /*
1161                          * If the drive has indicated to us that it
1162                          * doesn't have any media in it, don't bother
1163                          * with any more polling.
1164                          */
1165                         if (media_not_present(sdkp, &sshdr))
1166                                 return;
1167
1168                         if (the_result)
1169                                 sense_valid = scsi_sense_valid(&sshdr);
1170                         retries++;
1171                 } while (retries < 3 && 
1172                          (!scsi_status_is_good(the_result) ||
1173                           ((driver_byte(the_result) & DRIVER_SENSE) &&
1174                           sense_valid && sshdr.sense_key == UNIT_ATTENTION)));
1175
1176                 if ((driver_byte(the_result) & DRIVER_SENSE) == 0) {
1177                         /* no sense, TUR either succeeded or failed
1178                          * with a status error */
1179                         if(!spintime && !scsi_status_is_good(the_result)) {
1180                                 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
1181                                 sd_print_result(sdkp, the_result);
1182                         }
1183                         break;
1184                 }
1185                                         
1186                 /*
1187                  * The device does not want the automatic start to be issued.
1188                  */
1189                 if (sdkp->device->no_start_on_add)
1190                         break;
1191
1192                 if (sense_valid && sshdr.sense_key == NOT_READY) {
1193                         if (sshdr.asc == 4 && sshdr.ascq == 3)
1194                                 break;  /* manual intervention required */
1195                         if (sshdr.asc == 4 && sshdr.ascq == 0xb)
1196                                 break;  /* standby */
1197                         if (sshdr.asc == 4 && sshdr.ascq == 0xc)
1198                                 break;  /* unavailable */
1199                         /*
1200                          * Issue command to spin up drive when not ready
1201                          */
1202                         if (!spintime) {
1203                                 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
1204                                 cmd[0] = START_STOP;
1205                                 cmd[1] = 1;     /* Return immediately */
1206                                 memset((void *) &cmd[2], 0, 8);
1207                                 cmd[4] = 1;     /* Start spin cycle */
1208                                 if (sdkp->device->start_stop_pwr_cond)
1209                                         cmd[4] |= 1 << 4;
1210                                 scsi_execute_req(sdkp->device, cmd, DMA_NONE,
1211                                                  NULL, 0, &sshdr,
1212                                                  SD_TIMEOUT, SD_MAX_RETRIES,
1213                                                  NULL);
1214                                 spintime_expire = jiffies + 100 * HZ;
1215                                 spintime = 1;
1216                         }
1217                         /* Wait 1 second for next try */
1218                         msleep(1000);
1219                         printk(".");
1220
1221                 /*
1222                  * Wait for USB flash devices with slow firmware.
1223                  * Yes, this sense key/ASC combination shouldn't
1224                  * occur here.  It's characteristic of these devices.
1225                  */
1226                 } else if (sense_valid &&
1227                                 sshdr.sense_key == UNIT_ATTENTION &&
1228                                 sshdr.asc == 0x28) {
1229                         if (!spintime) {
1230                                 spintime_expire = jiffies + 5 * HZ;
1231                                 spintime = 1;
1232                         }
1233                         /* Wait 1 second for next try */
1234                         msleep(1000);
1235                 } else {
1236                         /* we don't understand the sense code, so it's
1237                          * probably pointless to loop */
1238                         if(!spintime) {
1239                                 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
1240                                 sd_print_sense_hdr(sdkp, &sshdr);
1241                         }
1242                         break;
1243                 }
1244                                 
1245         } while (spintime && time_before_eq(jiffies, spintime_expire));
1246
1247         if (spintime) {
1248                 if (scsi_status_is_good(the_result))
1249                         printk("ready\n");
1250                 else
1251                         printk("not responding...\n");
1252         }
1253 }
1254
1255
1256 /*
1257  * Determine whether disk supports Data Integrity Field.
1258  */
1259 void sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
1260 {
1261         struct scsi_device *sdp = sdkp->device;
1262         u8 type;
1263
1264         if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0)
1265                 return;
1266
1267         type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
1268
1269         if (type == sdkp->protection_type || !sdkp->first_scan)
1270                 return;
1271
1272         sdkp->protection_type = type;
1273
1274         switch (type) {
1275         case SD_DIF_TYPE1_PROTECTION:
1276         case SD_DIF_TYPE3_PROTECTION:
1277                 break;
1278
1279         default:
1280                 sd_printk(KERN_ERR, sdkp, "formatted with unsupported " \
1281                           "protection type %u. Disabling disk!\n", type);
1282                 sdkp->capacity = 0;
1283                 return;
1284         }
1285
1286         if (scsi_host_dif_capable(sdp->host, type))
1287                 sd_printk(KERN_NOTICE, sdkp,
1288                           "Enabling DIF Type %u protection\n", type);
1289         else
1290                 sd_printk(KERN_NOTICE, sdkp,
1291                           "Disabling DIF Type %u protection\n", type);
1292 }
1293
1294 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
1295                         struct scsi_sense_hdr *sshdr, int sense_valid,
1296                         int the_result)
1297 {
1298         sd_print_result(sdkp, the_result);
1299         if (driver_byte(the_result) & DRIVER_SENSE)
1300                 sd_print_sense_hdr(sdkp, sshdr);
1301         else
1302                 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
1303
1304         /*
1305          * Set dirty bit for removable devices if not ready -
1306          * sometimes drives will not report this properly.
1307          */
1308         if (sdp->removable &&
1309             sense_valid && sshdr->sense_key == NOT_READY)
1310                 sdp->changed = 1;
1311
1312         /*
1313          * We used to set media_present to 0 here to indicate no media
1314          * in the drive, but some drives fail read capacity even with
1315          * media present, so we can't do that.
1316          */
1317         sdkp->capacity = 0; /* unknown mapped to zero - as usual */
1318 }
1319
1320 #define RC16_LEN 32
1321 #if RC16_LEN > SD_BUF_SIZE
1322 #error RC16_LEN must not be more than SD_BUF_SIZE
1323 #endif
1324
1325 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
1326                                                 unsigned char *buffer)
1327 {
1328         unsigned char cmd[16];
1329         struct scsi_sense_hdr sshdr;
1330         int sense_valid = 0;
1331         int the_result;
1332         int retries = 3;
1333         unsigned int alignment;
1334         unsigned long long lba;
1335         unsigned sector_size;
1336
1337         do {
1338                 memset(cmd, 0, 16);
1339                 cmd[0] = SERVICE_ACTION_IN;
1340                 cmd[1] = SAI_READ_CAPACITY_16;
1341                 cmd[13] = RC16_LEN;
1342                 memset(buffer, 0, RC16_LEN);
1343
1344                 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
1345                                         buffer, RC16_LEN, &sshdr,
1346                                         SD_TIMEOUT, SD_MAX_RETRIES, NULL);
1347
1348                 if (media_not_present(sdkp, &sshdr))
1349                         return -ENODEV;
1350
1351                 if (the_result) {
1352                         sense_valid = scsi_sense_valid(&sshdr);
1353                         if (sense_valid &&
1354                             sshdr.sense_key == ILLEGAL_REQUEST &&
1355                             (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
1356                             sshdr.ascq == 0x00)
1357                                 /* Invalid Command Operation Code or
1358                                  * Invalid Field in CDB, just retry
1359                                  * silently with RC10 */
1360                                 return -EINVAL;
1361                 }
1362                 retries--;
1363
1364         } while (the_result && retries);
1365
1366         if (the_result) {
1367                 sd_printk(KERN_NOTICE, sdkp, "READ CAPACITY(16) failed\n");
1368                 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
1369                 return -EINVAL;
1370         }
1371
1372         sector_size = get_unaligned_be32(&buffer[8]);
1373         lba = get_unaligned_be64(&buffer[0]);
1374
1375         sd_read_protection_type(sdkp, buffer);
1376
1377         if ((sizeof(sdkp->capacity) == 4) && (lba >= 0xffffffffULL)) {
1378                 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
1379                         "kernel compiled with support for large block "
1380                         "devices.\n");
1381                 sdkp->capacity = 0;
1382                 return -EOVERFLOW;
1383         }
1384
1385         /* Logical blocks per physical block exponent */
1386         sdkp->hw_sector_size = (1 << (buffer[13] & 0xf)) * sector_size;
1387
1388         /* Lowest aligned logical block */
1389         alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
1390         blk_queue_alignment_offset(sdp->request_queue, alignment);
1391         if (alignment && sdkp->first_scan)
1392                 sd_printk(KERN_NOTICE, sdkp,
1393                           "physical block alignment offset: %u\n", alignment);
1394
1395         sdkp->capacity = lba + 1;
1396         return sector_size;
1397 }
1398
1399 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
1400                                                 unsigned char *buffer)
1401 {
1402         unsigned char cmd[16];
1403         struct scsi_sense_hdr sshdr;
1404         int sense_valid = 0;
1405         int the_result;
1406         int retries = 3;
1407         sector_t lba;
1408         unsigned sector_size;
1409
1410         do {
1411                 cmd[0] = READ_CAPACITY;
1412                 memset(&cmd[1], 0, 9);
1413                 memset(buffer, 0, 8);
1414
1415                 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
1416                                         buffer, 8, &sshdr,
1417                                         SD_TIMEOUT, SD_MAX_RETRIES, NULL);
1418
1419                 if (media_not_present(sdkp, &sshdr))
1420                         return -ENODEV;
1421
1422                 if (the_result)
1423                         sense_valid = scsi_sense_valid(&sshdr);
1424                 retries--;
1425
1426         } while (the_result && retries);
1427
1428         if (the_result) {
1429                 sd_printk(KERN_NOTICE, sdkp, "READ CAPACITY failed\n");
1430                 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
1431                 return -EINVAL;
1432         }
1433
1434         sector_size = get_unaligned_be32(&buffer[4]);
1435         lba = get_unaligned_be32(&buffer[0]);
1436
1437         if ((sizeof(sdkp->capacity) == 4) && (lba == 0xffffffff)) {
1438                 sd_printk(KERN_ERR, sdkp, "Too big for this kernel. Use a "
1439                         "kernel compiled with support for large block "
1440                         "devices.\n");
1441                 sdkp->capacity = 0;
1442                 return -EOVERFLOW;
1443         }
1444
1445         sdkp->capacity = lba + 1;
1446         sdkp->hw_sector_size = sector_size;
1447         return sector_size;
1448 }
1449
1450 static int sd_try_rc16_first(struct scsi_device *sdp)
1451 {
1452         if (sdp->scsi_level > SCSI_SPC_2)
1453                 return 1;
1454         if (scsi_device_protection(sdp))
1455                 return 1;
1456         return 0;
1457 }
1458
1459 /*
1460  * read disk capacity
1461  */
1462 static void
1463 sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer)
1464 {
1465         int sector_size;
1466         struct scsi_device *sdp = sdkp->device;
1467         sector_t old_capacity = sdkp->capacity;
1468
1469         if (sd_try_rc16_first(sdp)) {
1470                 sector_size = read_capacity_16(sdkp, sdp, buffer);
1471                 if (sector_size == -EOVERFLOW)
1472                         goto got_data;
1473                 if (sector_size == -ENODEV)
1474                         return;
1475                 if (sector_size < 0)
1476                         sector_size = read_capacity_10(sdkp, sdp, buffer);
1477                 if (sector_size < 0)
1478                         return;
1479         } else {
1480                 sector_size = read_capacity_10(sdkp, sdp, buffer);
1481                 if (sector_size == -EOVERFLOW)
1482                         goto got_data;
1483                 if (sector_size < 0)
1484                         return;
1485                 if ((sizeof(sdkp->capacity) > 4) &&
1486                     (sdkp->capacity > 0xffffffffULL)) {
1487                         int old_sector_size = sector_size;
1488                         sd_printk(KERN_NOTICE, sdkp, "Very big device. "
1489                                         "Trying to use READ CAPACITY(16).\n");
1490                         sector_size = read_capacity_16(sdkp, sdp, buffer);
1491                         if (sector_size < 0) {
1492                                 sd_printk(KERN_NOTICE, sdkp,
1493                                         "Using 0xffffffff as device size\n");
1494                                 sdkp->capacity = 1 + (sector_t) 0xffffffff;
1495                                 sector_size = old_sector_size;
1496                                 goto got_data;
1497                         }
1498                 }
1499         }
1500
1501         /* Some devices are known to return the total number of blocks,
1502          * not the highest block number.  Some devices have versions
1503          * which do this and others which do not.  Some devices we might
1504          * suspect of doing this but we don't know for certain.
1505          *
1506          * If we know the reported capacity is wrong, decrement it.  If
1507          * we can only guess, then assume the number of blocks is even
1508          * (usually true but not always) and err on the side of lowering
1509          * the capacity.
1510          */
1511         if (sdp->fix_capacity ||
1512             (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
1513                 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
1514                                 "from its reported value: %llu\n",
1515                                 (unsigned long long) sdkp->capacity);
1516                 --sdkp->capacity;
1517         }
1518
1519 got_data:
1520         if (sector_size == 0) {
1521                 sector_size = 512;
1522                 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
1523                           "assuming 512.\n");
1524         }
1525
1526         if (sector_size != 512 &&
1527             sector_size != 1024 &&
1528             sector_size != 2048 &&
1529             sector_size != 4096 &&
1530             sector_size != 256) {
1531                 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
1532                           sector_size);
1533                 /*
1534                  * The user might want to re-format the drive with
1535                  * a supported sectorsize.  Once this happens, it
1536                  * would be relatively trivial to set the thing up.
1537                  * For this reason, we leave the thing in the table.
1538                  */
1539                 sdkp->capacity = 0;
1540                 /*
1541                  * set a bogus sector size so the normal read/write
1542                  * logic in the block layer will eventually refuse any
1543                  * request on this device without tripping over power
1544                  * of two sector size assumptions
1545                  */
1546                 sector_size = 512;
1547         }
1548         blk_queue_logical_block_size(sdp->request_queue, sector_size);
1549
1550         {
1551                 char cap_str_2[10], cap_str_10[10];
1552                 u64 sz = (u64)sdkp->capacity << ilog2(sector_size);
1553
1554                 string_get_size(sz, STRING_UNITS_2, cap_str_2,
1555                                 sizeof(cap_str_2));
1556                 string_get_size(sz, STRING_UNITS_10, cap_str_10,
1557                                 sizeof(cap_str_10));
1558
1559                 if (sdkp->first_scan || old_capacity != sdkp->capacity) {
1560                         sd_printk(KERN_NOTICE, sdkp,
1561                                   "%llu %d-byte logical blocks: (%s/%s)\n",
1562                                   (unsigned long long)sdkp->capacity,
1563                                   sector_size, cap_str_10, cap_str_2);
1564
1565                         if (sdkp->hw_sector_size != sector_size)
1566                                 sd_printk(KERN_NOTICE, sdkp,
1567                                           "%u-byte physical blocks\n",
1568                                           sdkp->hw_sector_size);
1569                 }
1570         }
1571
1572         /* Rescale capacity to 512-byte units */
1573         if (sector_size == 4096)
1574                 sdkp->capacity <<= 3;
1575         else if (sector_size == 2048)
1576                 sdkp->capacity <<= 2;
1577         else if (sector_size == 1024)
1578                 sdkp->capacity <<= 1;
1579         else if (sector_size == 256)
1580                 sdkp->capacity >>= 1;
1581
1582         blk_queue_physical_block_size(sdp->request_queue, sdkp->hw_sector_size);
1583         sdkp->device->sector_size = sector_size;
1584 }
1585
1586 /* called with buffer of length 512 */
1587 static inline int
1588 sd_do_mode_sense(struct scsi_device *sdp, int dbd, int modepage,
1589                  unsigned char *buffer, int len, struct scsi_mode_data *data,
1590                  struct scsi_sense_hdr *sshdr)
1591 {
1592         return scsi_mode_sense(sdp, dbd, modepage, buffer, len,
1593                                SD_TIMEOUT, SD_MAX_RETRIES, data,
1594                                sshdr);
1595 }
1596
1597 /*
1598  * read write protect setting, if possible - called only in sd_revalidate_disk()
1599  * called with buffer of length SD_BUF_SIZE
1600  */
1601 static void
1602 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
1603 {
1604         int res;
1605         struct scsi_device *sdp = sdkp->device;
1606         struct scsi_mode_data data;
1607         int old_wp = sdkp->write_prot;
1608
1609         set_disk_ro(sdkp->disk, 0);
1610         if (sdp->skip_ms_page_3f) {
1611                 sd_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
1612                 return;
1613         }
1614
1615         if (sdp->use_192_bytes_for_3f) {
1616                 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 192, &data, NULL);
1617         } else {
1618                 /*
1619                  * First attempt: ask for all pages (0x3F), but only 4 bytes.
1620                  * We have to start carefully: some devices hang if we ask
1621                  * for more than is available.
1622                  */
1623                 res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 4, &data, NULL);
1624
1625                 /*
1626                  * Second attempt: ask for page 0 When only page 0 is
1627                  * implemented, a request for page 3F may return Sense Key
1628                  * 5: Illegal Request, Sense Code 24: Invalid field in
1629                  * CDB.
1630                  */
1631                 if (!scsi_status_is_good(res))
1632                         res = sd_do_mode_sense(sdp, 0, 0, buffer, 4, &data, NULL);
1633
1634                 /*
1635                  * Third attempt: ask 255 bytes, as we did earlier.
1636                  */
1637                 if (!scsi_status_is_good(res))
1638                         res = sd_do_mode_sense(sdp, 0, 0x3F, buffer, 255,
1639                                                &data, NULL);
1640         }
1641
1642         if (!scsi_status_is_good(res)) {
1643                 sd_printk(KERN_WARNING, sdkp,
1644                           "Test WP failed, assume Write Enabled\n");
1645         } else {
1646                 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
1647                 set_disk_ro(sdkp->disk, sdkp->write_prot);
1648                 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
1649                         sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
1650                                   sdkp->write_prot ? "on" : "off");
1651                         sd_printk(KERN_DEBUG, sdkp,
1652                                   "Mode Sense: %02x %02x %02x %02x\n",
1653                                   buffer[0], buffer[1], buffer[2], buffer[3]);
1654                 }
1655         }
1656 }
1657
1658 /*
1659  * sd_read_cache_type - called only from sd_revalidate_disk()
1660  * called with buffer of length SD_BUF_SIZE
1661  */
1662 static void
1663 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
1664 {
1665         int len = 0, res;
1666         struct scsi_device *sdp = sdkp->device;
1667
1668         int dbd;
1669         int modepage;
1670         struct scsi_mode_data data;
1671         struct scsi_sense_hdr sshdr;
1672         int old_wce = sdkp->WCE;
1673         int old_rcd = sdkp->RCD;
1674         int old_dpofua = sdkp->DPOFUA;
1675
1676         if (sdp->skip_ms_page_8)
1677                 goto defaults;
1678
1679         if (sdp->type == TYPE_RBC) {
1680                 modepage = 6;
1681                 dbd = 8;
1682         } else {
1683                 modepage = 8;
1684                 dbd = 0;
1685         }
1686
1687         /* cautiously ask */
1688         res = sd_do_mode_sense(sdp, dbd, modepage, buffer, 4, &data, &sshdr);
1689
1690         if (!scsi_status_is_good(res))
1691                 goto bad_sense;
1692
1693         if (!data.header_length) {
1694                 modepage = 6;
1695                 sd_printk(KERN_ERR, sdkp, "Missing header in MODE_SENSE response\n");
1696         }
1697
1698         /* that went OK, now ask for the proper length */
1699         len = data.length;
1700
1701         /*
1702          * We're only interested in the first three bytes, actually.
1703          * But the data cache page is defined for the first 20.
1704          */
1705         if (len < 3)
1706                 goto bad_sense;
1707         if (len > 20)
1708                 len = 20;
1709
1710         /* Take headers and block descriptors into account */
1711         len += data.header_length + data.block_descriptor_length;
1712         if (len > SD_BUF_SIZE)
1713                 goto bad_sense;
1714
1715         /* Get the data */
1716         res = sd_do_mode_sense(sdp, dbd, modepage, buffer, len, &data, &sshdr);
1717
1718         if (scsi_status_is_good(res)) {
1719                 int offset = data.header_length + data.block_descriptor_length;
1720
1721                 if (offset >= SD_BUF_SIZE - 2) {
1722                         sd_printk(KERN_ERR, sdkp, "Malformed MODE SENSE response\n");
1723                         goto defaults;
1724                 }
1725
1726                 if ((buffer[offset] & 0x3f) != modepage) {
1727                         sd_printk(KERN_ERR, sdkp, "Got wrong page\n");
1728                         goto defaults;
1729                 }
1730
1731                 if (modepage == 8) {
1732                         sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
1733                         sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
1734                 } else {
1735                         sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
1736                         sdkp->RCD = 0;
1737                 }
1738
1739                 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
1740                 if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw) {
1741                         sd_printk(KERN_NOTICE, sdkp,
1742                                   "Uses READ/WRITE(6), disabling FUA\n");
1743                         sdkp->DPOFUA = 0;
1744                 }
1745
1746                 if (sdkp->first_scan || old_wce != sdkp->WCE ||
1747                     old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
1748                         sd_printk(KERN_NOTICE, sdkp,
1749                                   "Write cache: %s, read cache: %s, %s\n",
1750                                   sdkp->WCE ? "enabled" : "disabled",
1751                                   sdkp->RCD ? "disabled" : "enabled",
1752                                   sdkp->DPOFUA ? "supports DPO and FUA"
1753                                   : "doesn't support DPO or FUA");
1754
1755                 return;
1756         }
1757
1758 bad_sense:
1759         if (scsi_sense_valid(&sshdr) &&
1760             sshdr.sense_key == ILLEGAL_REQUEST &&
1761             sshdr.asc == 0x24 && sshdr.ascq == 0x0)
1762                 /* Invalid field in CDB */
1763                 sd_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
1764         else
1765                 sd_printk(KERN_ERR, sdkp, "Asking for cache data failed\n");
1766
1767 defaults:
1768         sd_printk(KERN_ERR, sdkp, "Assuming drive cache: write through\n");
1769         sdkp->WCE = 0;
1770         sdkp->RCD = 0;
1771         sdkp->DPOFUA = 0;
1772 }
1773
1774 /*
1775  * The ATO bit indicates whether the DIF application tag is available
1776  * for use by the operating system.
1777  */
1778 void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
1779 {
1780         int res, offset;
1781         struct scsi_device *sdp = sdkp->device;
1782         struct scsi_mode_data data;
1783         struct scsi_sense_hdr sshdr;
1784
1785         if (sdp->type != TYPE_DISK)
1786                 return;
1787
1788         if (sdkp->protection_type == 0)
1789                 return;
1790
1791         res = scsi_mode_sense(sdp, 1, 0x0a, buffer, 36, SD_TIMEOUT,
1792                               SD_MAX_RETRIES, &data, &sshdr);
1793
1794         if (!scsi_status_is_good(res) || !data.header_length ||
1795             data.length < 6) {
1796                 sd_printk(KERN_WARNING, sdkp,
1797                           "getting Control mode page failed, assume no ATO\n");
1798
1799                 if (scsi_sense_valid(&sshdr))
1800                         sd_print_sense_hdr(sdkp, &sshdr);
1801
1802                 return;
1803         }
1804
1805         offset = data.header_length + data.block_descriptor_length;
1806
1807         if ((buffer[offset] & 0x3f) != 0x0a) {
1808                 sd_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
1809                 return;
1810         }
1811
1812         if ((buffer[offset + 5] & 0x80) == 0)
1813                 return;
1814
1815         sdkp->ATO = 1;
1816
1817         return;
1818 }
1819
1820 /**
1821  * sd_read_block_limits - Query disk device for preferred I/O sizes.
1822  * @disk: disk to query
1823  */
1824 static void sd_read_block_limits(struct scsi_disk *sdkp)
1825 {
1826         unsigned int sector_sz = sdkp->device->sector_size;
1827         char *buffer;
1828
1829         /* Block Limits VPD */
1830         buffer = scsi_get_vpd_page(sdkp->device, 0xb0);
1831
1832         if (buffer == NULL)
1833                 return;
1834
1835         blk_queue_io_min(sdkp->disk->queue,
1836                          get_unaligned_be16(&buffer[6]) * sector_sz);
1837         blk_queue_io_opt(sdkp->disk->queue,
1838                          get_unaligned_be32(&buffer[12]) * sector_sz);
1839
1840         kfree(buffer);
1841 }
1842
1843 /**
1844  * sd_read_block_characteristics - Query block dev. characteristics
1845  * @disk: disk to query
1846  */
1847 static void sd_read_block_characteristics(struct scsi_disk *sdkp)
1848 {
1849         char *buffer;
1850         u16 rot;
1851
1852         /* Block Device Characteristics VPD */
1853         buffer = scsi_get_vpd_page(sdkp->device, 0xb1);
1854
1855         if (buffer == NULL)
1856                 return;
1857
1858         rot = get_unaligned_be16(&buffer[4]);
1859
1860         if (rot == 1)
1861                 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, sdkp->disk->queue);
1862
1863         kfree(buffer);
1864 }
1865
1866 static int sd_try_extended_inquiry(struct scsi_device *sdp)
1867 {
1868         /*
1869          * Although VPD inquiries can go to SCSI-2 type devices,
1870          * some USB ones crash on receiving them, and the pages
1871          * we currently ask for are for SPC-3 and beyond
1872          */
1873         if (sdp->scsi_level > SCSI_SPC_2)
1874                 return 1;
1875         return 0;
1876 }
1877
1878 /**
1879  *      sd_revalidate_disk - called the first time a new disk is seen,
1880  *      performs disk spin up, read_capacity, etc.
1881  *      @disk: struct gendisk we care about
1882  **/
1883 static int sd_revalidate_disk(struct gendisk *disk)
1884 {
1885         struct scsi_disk *sdkp = scsi_disk(disk);
1886         struct scsi_device *sdp = sdkp->device;
1887         unsigned char *buffer;
1888         unsigned ordered;
1889
1890         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
1891                                       "sd_revalidate_disk\n"));
1892
1893         /*
1894          * If the device is offline, don't try and read capacity or any
1895          * of the other niceties.
1896          */
1897         if (!scsi_device_online(sdp))
1898                 goto out;
1899
1900         buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
1901         if (!buffer) {
1902                 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
1903                           "allocation failure.\n");
1904                 goto out;
1905         }
1906
1907         sd_spinup_disk(sdkp);
1908
1909         /*
1910          * Without media there is no reason to ask; moreover, some devices
1911          * react badly if we do.
1912          */
1913         if (sdkp->media_present) {
1914                 sd_read_capacity(sdkp, buffer);
1915
1916                 if (sd_try_extended_inquiry(sdp)) {
1917                         sd_read_block_limits(sdkp);
1918                         sd_read_block_characteristics(sdkp);
1919                 }
1920
1921                 sd_read_write_protect_flag(sdkp, buffer);
1922                 sd_read_cache_type(sdkp, buffer);
1923                 sd_read_app_tag_own(sdkp, buffer);
1924         }
1925
1926         sdkp->first_scan = 0;
1927
1928         /*
1929          * We now have all cache related info, determine how we deal
1930          * with ordered requests.  Note that as the current SCSI
1931          * dispatch function can alter request order, we cannot use
1932          * QUEUE_ORDERED_TAG_* even when ordered tag is supported.
1933          */
1934         if (sdkp->WCE)
1935                 ordered = sdkp->DPOFUA
1936                         ? QUEUE_ORDERED_DRAIN_FUA : QUEUE_ORDERED_DRAIN_FLUSH;
1937         else
1938                 ordered = QUEUE_ORDERED_DRAIN;
1939
1940         blk_queue_ordered(sdkp->disk->queue, ordered, sd_prepare_flush);
1941
1942         set_capacity(disk, sdkp->capacity);
1943         kfree(buffer);
1944
1945  out:
1946         return 0;
1947 }
1948
1949 /**
1950  *      sd_format_disk_name - format disk name
1951  *      @prefix: name prefix - ie. "sd" for SCSI disks
1952  *      @index: index of the disk to format name for
1953  *      @buf: output buffer
1954  *      @buflen: length of the output buffer
1955  *
1956  *      SCSI disk names starts at sda.  The 26th device is sdz and the
1957  *      27th is sdaa.  The last one for two lettered suffix is sdzz
1958  *      which is followed by sdaaa.
1959  *
1960  *      This is basically 26 base counting with one extra 'nil' entry
1961  *      at the beggining from the second digit on and can be
1962  *      determined using similar method as 26 base conversion with the
1963  *      index shifted -1 after each digit is computed.
1964  *
1965  *      CONTEXT:
1966  *      Don't care.
1967  *
1968  *      RETURNS:
1969  *      0 on success, -errno on failure.
1970  */
1971 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
1972 {
1973         const int base = 'z' - 'a' + 1;
1974         char *begin = buf + strlen(prefix);
1975         char *end = buf + buflen;
1976         char *p;
1977         int unit;
1978
1979         p = end - 1;
1980         *p = '\0';
1981         unit = base;
1982         do {
1983                 if (p == begin)
1984                         return -EINVAL;
1985                 *--p = 'a' + (index % unit);
1986                 index = (index / unit) - 1;
1987         } while (index >= 0);
1988
1989         memmove(begin, p, end - p);
1990         memcpy(buf, prefix, strlen(prefix));
1991
1992         return 0;
1993 }
1994
1995 /*
1996  * The asynchronous part of sd_probe
1997  */
1998 static void sd_probe_async(void *data, async_cookie_t cookie)
1999 {
2000         struct scsi_disk *sdkp = data;
2001         struct scsi_device *sdp;
2002         struct gendisk *gd;
2003         u32 index;
2004         struct device *dev;
2005
2006         sdp = sdkp->device;
2007         gd = sdkp->disk;
2008         index = sdkp->index;
2009         dev = &sdp->sdev_gendev;
2010
2011         if (index < SD_MAX_DISKS) {
2012                 gd->major = sd_major((index & 0xf0) >> 4);
2013                 gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
2014                 gd->minors = SD_MINORS;
2015         }
2016         gd->fops = &sd_fops;
2017         gd->private_data = &sdkp->driver;
2018         gd->queue = sdkp->device->request_queue;
2019
2020         /* defaults, until the device tells us otherwise */
2021         sdp->sector_size = 512;
2022         sdkp->capacity = 0;
2023         sdkp->media_present = 1;
2024         sdkp->write_prot = 0;
2025         sdkp->WCE = 0;
2026         sdkp->RCD = 0;
2027         sdkp->ATO = 0;
2028         sdkp->first_scan = 1;
2029
2030         sd_revalidate_disk(gd);
2031
2032         blk_queue_prep_rq(sdp->request_queue, sd_prep_fn);
2033
2034         gd->driverfs_dev = &sdp->sdev_gendev;
2035         gd->flags = GENHD_FL_EXT_DEVT | GENHD_FL_DRIVERFS;
2036         if (sdp->removable)
2037                 gd->flags |= GENHD_FL_REMOVABLE;
2038
2039         dev_set_drvdata(dev, sdkp);
2040         add_disk(gd);
2041         sd_dif_config_host(sdkp);
2042
2043         sd_revalidate_disk(gd);
2044
2045         sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
2046                   sdp->removable ? "removable " : "");
2047         put_device(&sdkp->dev);
2048 }
2049
2050 /**
2051  *      sd_probe - called during driver initialization and whenever a
2052  *      new scsi device is attached to the system. It is called once
2053  *      for each scsi device (not just disks) present.
2054  *      @dev: pointer to device object
2055  *
2056  *      Returns 0 if successful (or not interested in this scsi device 
2057  *      (e.g. scanner)); 1 when there is an error.
2058  *
2059  *      Note: this function is invoked from the scsi mid-level.
2060  *      This function sets up the mapping between a given 
2061  *      <host,channel,id,lun> (found in sdp) and new device name 
2062  *      (e.g. /dev/sda). More precisely it is the block device major 
2063  *      and minor number that is chosen here.
2064  *
2065  *      Assume sd_attach is not re-entrant (for time being)
2066  *      Also think about sd_attach() and sd_remove() running coincidentally.
2067  **/
2068 static int sd_probe(struct device *dev)
2069 {
2070         struct scsi_device *sdp = to_scsi_device(dev);
2071         struct scsi_disk *sdkp;
2072         struct gendisk *gd;
2073         u32 index;
2074         int error;
2075
2076         error = -ENODEV;
2077         if (sdp->type != TYPE_DISK && sdp->type != TYPE_MOD && sdp->type != TYPE_RBC)
2078                 goto out;
2079
2080         SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
2081                                         "sd_attach\n"));
2082
2083         error = -ENOMEM;
2084         sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
2085         if (!sdkp)
2086                 goto out;
2087
2088         gd = alloc_disk(SD_MINORS);
2089         if (!gd)
2090                 goto out_free;
2091
2092         do {
2093                 if (!ida_pre_get(&sd_index_ida, GFP_KERNEL))
2094                         goto out_put;
2095
2096                 spin_lock(&sd_index_lock);
2097                 error = ida_get_new(&sd_index_ida, &index);
2098                 spin_unlock(&sd_index_lock);
2099         } while (error == -EAGAIN);
2100
2101         if (error)
2102                 goto out_put;
2103
2104         error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
2105         if (error)
2106                 goto out_free_index;
2107
2108         sdkp->device = sdp;
2109         sdkp->driver = &sd_template;
2110         sdkp->disk = gd;
2111         sdkp->index = index;
2112         sdkp->openers = 0;
2113         sdkp->previous_state = 1;
2114
2115         if (!sdp->request_queue->rq_timeout) {
2116                 if (sdp->type != TYPE_MOD)
2117                         blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
2118                 else
2119                         blk_queue_rq_timeout(sdp->request_queue,
2120                                              SD_MOD_TIMEOUT);
2121         }
2122
2123         device_initialize(&sdkp->dev);
2124         sdkp->dev.parent = &sdp->sdev_gendev;
2125         sdkp->dev.class = &sd_disk_class;
2126         dev_set_name(&sdkp->dev, dev_name(&sdp->sdev_gendev));
2127
2128         if (device_add(&sdkp->dev))
2129                 goto out_free_index;
2130
2131         get_device(&sdp->sdev_gendev);
2132
2133         get_device(&sdkp->dev); /* prevent release before async_schedule */
2134         async_schedule(sd_probe_async, sdkp);
2135
2136         return 0;
2137
2138  out_free_index:
2139         spin_lock(&sd_index_lock);
2140         ida_remove(&sd_index_ida, index);
2141         spin_unlock(&sd_index_lock);
2142  out_put:
2143         put_disk(gd);
2144  out_free:
2145         kfree(sdkp);
2146  out:
2147         return error;
2148 }
2149
2150 /**
2151  *      sd_remove - called whenever a scsi disk (previously recognized by
2152  *      sd_probe) is detached from the system. It is called (potentially
2153  *      multiple times) during sd module unload.
2154  *      @sdp: pointer to mid level scsi device object
2155  *
2156  *      Note: this function is invoked from the scsi mid-level.
2157  *      This function potentially frees up a device name (e.g. /dev/sdc)
2158  *      that could be re-used by a subsequent sd_probe().
2159  *      This function is not called when the built-in sd driver is "exit-ed".
2160  **/
2161 static int sd_remove(struct device *dev)
2162 {
2163         struct scsi_disk *sdkp;
2164
2165         async_synchronize_full();
2166         sdkp = dev_get_drvdata(dev);
2167         blk_queue_prep_rq(sdkp->device->request_queue, scsi_prep_fn);
2168         device_del(&sdkp->dev);
2169         del_gendisk(sdkp->disk);
2170         sd_shutdown(dev);
2171
2172         mutex_lock(&sd_ref_mutex);
2173         dev_set_drvdata(dev, NULL);
2174         put_device(&sdkp->dev);
2175         mutex_unlock(&sd_ref_mutex);
2176
2177         return 0;
2178 }
2179
2180 /**
2181  *      scsi_disk_release - Called to free the scsi_disk structure
2182  *      @dev: pointer to embedded class device
2183  *
2184  *      sd_ref_mutex must be held entering this routine.  Because it is
2185  *      called on last put, you should always use the scsi_disk_get()
2186  *      scsi_disk_put() helpers which manipulate the semaphore directly
2187  *      and never do a direct put_device.
2188  **/
2189 static void scsi_disk_release(struct device *dev)
2190 {
2191         struct scsi_disk *sdkp = to_scsi_disk(dev);
2192         struct gendisk *disk = sdkp->disk;
2193         
2194         spin_lock(&sd_index_lock);
2195         ida_remove(&sd_index_ida, sdkp->index);
2196         spin_unlock(&sd_index_lock);
2197
2198         disk->private_data = NULL;
2199         put_disk(disk);
2200         put_device(&sdkp->device->sdev_gendev);
2201
2202         kfree(sdkp);
2203 }
2204
2205 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
2206 {
2207         unsigned char cmd[6] = { START_STOP };  /* START_VALID */
2208         struct scsi_sense_hdr sshdr;
2209         struct scsi_device *sdp = sdkp->device;
2210         int res;
2211
2212         if (start)
2213                 cmd[4] |= 1;    /* START */
2214
2215         if (sdp->start_stop_pwr_cond)
2216                 cmd[4] |= start ? 1 << 4 : 3 << 4;      /* Active or Standby */
2217
2218         if (!scsi_device_online(sdp))
2219                 return -ENODEV;
2220
2221         res = scsi_execute_req(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
2222                                SD_TIMEOUT, SD_MAX_RETRIES, NULL);
2223         if (res) {
2224                 sd_printk(KERN_WARNING, sdkp, "START_STOP FAILED\n");
2225                 sd_print_result(sdkp, res);
2226                 if (driver_byte(res) & DRIVER_SENSE)
2227                         sd_print_sense_hdr(sdkp, &sshdr);
2228         }
2229
2230         return res;
2231 }
2232
2233 /*
2234  * Send a SYNCHRONIZE CACHE instruction down to the device through
2235  * the normal SCSI command structure.  Wait for the command to
2236  * complete.
2237  */
2238 static void sd_shutdown(struct device *dev)
2239 {
2240         struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
2241
2242         if (!sdkp)
2243                 return;         /* this can happen */
2244
2245         if (sdkp->WCE) {
2246                 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
2247                 sd_sync_cache(sdkp);
2248         }
2249
2250         if (system_state != SYSTEM_RESTART && sdkp->device->manage_start_stop) {
2251                 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
2252                 sd_start_stop_device(sdkp, 0);
2253         }
2254
2255         scsi_disk_put(sdkp);
2256 }
2257
2258 static int sd_suspend(struct device *dev, pm_message_t mesg)
2259 {
2260         struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
2261         int ret = 0;
2262
2263         if (!sdkp)
2264                 return 0;       /* this can happen */
2265
2266         if (sdkp->WCE) {
2267                 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
2268                 ret = sd_sync_cache(sdkp);
2269                 if (ret)
2270                         goto done;
2271         }
2272
2273         if ((mesg.event & PM_EVENT_SLEEP) && sdkp->device->manage_start_stop) {
2274                 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
2275                 ret = sd_start_stop_device(sdkp, 0);
2276         }
2277
2278 done:
2279         scsi_disk_put(sdkp);
2280         return ret;
2281 }
2282
2283 static int sd_resume(struct device *dev)
2284 {
2285         struct scsi_disk *sdkp = scsi_disk_get_from_dev(dev);
2286         int ret = 0;
2287
2288         if (!sdkp->device->manage_start_stop)
2289                 goto done;
2290
2291         sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
2292         ret = sd_start_stop_device(sdkp, 1);
2293
2294 done:
2295         scsi_disk_put(sdkp);
2296         return ret;
2297 }
2298
2299 /**
2300  *      init_sd - entry point for this driver (both when built in or when
2301  *      a module).
2302  *
2303  *      Note: this function registers this driver with the scsi mid-level.
2304  **/
2305 static int __init init_sd(void)
2306 {
2307         int majors = 0, i, err;
2308
2309         SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
2310
2311         for (i = 0; i < SD_MAJORS; i++)
2312                 if (register_blkdev(sd_major(i), "sd") == 0)
2313                         majors++;
2314
2315         if (!majors)
2316                 return -ENODEV;
2317
2318         err = class_register(&sd_disk_class);
2319         if (err)
2320                 goto err_out;
2321
2322         err = scsi_register_driver(&sd_template.gendrv);
2323         if (err)
2324                 goto err_out_class;
2325
2326         return 0;
2327
2328 err_out_class:
2329         class_unregister(&sd_disk_class);
2330 err_out:
2331         for (i = 0; i < SD_MAJORS; i++)
2332                 unregister_blkdev(sd_major(i), "sd");
2333         return err;
2334 }
2335
2336 /**
2337  *      exit_sd - exit point for this driver (when it is a module).
2338  *
2339  *      Note: this function unregisters this driver from the scsi mid-level.
2340  **/
2341 static void __exit exit_sd(void)
2342 {
2343         int i;
2344
2345         SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
2346
2347         scsi_unregister_driver(&sd_template.gendrv);
2348         class_unregister(&sd_disk_class);
2349
2350         for (i = 0; i < SD_MAJORS; i++)
2351                 unregister_blkdev(sd_major(i), "sd");
2352 }
2353
2354 module_init(init_sd);
2355 module_exit(exit_sd);
2356
2357 static void sd_print_sense_hdr(struct scsi_disk *sdkp,
2358                                struct scsi_sense_hdr *sshdr)
2359 {
2360         sd_printk(KERN_INFO, sdkp, "");
2361         scsi_show_sense_hdr(sshdr);
2362         sd_printk(KERN_INFO, sdkp, "");
2363         scsi_show_extd_sense(sshdr->asc, sshdr->ascq);
2364 }
2365
2366 static void sd_print_result(struct scsi_disk *sdkp, int result)
2367 {
2368         sd_printk(KERN_INFO, sdkp, "");
2369         scsi_show_result(result);
2370 }
2371