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