linux/drivers/ata/libata-scsi.c
<<
>>
Prefs
   1/*
   2 *  libata-scsi.c - helper library for ATA
   3 *
   4 *  Maintained by:  Tejun Heo <tj@kernel.org>
   5 *                  Please ALWAYS copy linux-ide@vger.kernel.org
   6 *                  on emails.
   7 *
   8 *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
   9 *  Copyright 2003-2004 Jeff Garzik
  10 *
  11 *
  12 *  This program is free software; you can redistribute it and/or modify
  13 *  it under the terms of the GNU General Public License as published by
  14 *  the Free Software Foundation; either version 2, or (at your option)
  15 *  any later version.
  16 *
  17 *  This program is distributed in the hope that it will be useful,
  18 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  19 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  20 *  GNU General Public License for more details.
  21 *
  22 *  You should have received a copy of the GNU General Public License
  23 *  along with this program; see the file COPYING.  If not, write to
  24 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  25 *
  26 *
  27 *  libata documentation is available via 'make {ps|pdf}docs',
  28 *  as Documentation/driver-api/libata.rst
  29 *
  30 *  Hardware documentation available from
  31 *  - http://www.t10.org/
  32 *  - http://www.t13.org/
  33 *
  34 */
  35
  36#include <linux/slab.h>
  37#include <linux/kernel.h>
  38#include <linux/blkdev.h>
  39#include <linux/spinlock.h>
  40#include <linux/export.h>
  41#include <scsi/scsi.h>
  42#include <scsi/scsi_host.h>
  43#include <scsi/scsi_cmnd.h>
  44#include <scsi/scsi_eh.h>
  45#include <scsi/scsi_device.h>
  46#include <scsi/scsi_tcq.h>
  47#include <scsi/scsi_transport.h>
  48#include <linux/libata.h>
  49#include <linux/hdreg.h>
  50#include <linux/uaccess.h>
  51#include <linux/suspend.h>
  52#include <asm/unaligned.h>
  53#include <linux/ioprio.h>
  54
  55#include "libata.h"
  56#include "libata-transport.h"
  57
  58#define ATA_SCSI_RBUF_SIZE      4096
  59
  60static DEFINE_SPINLOCK(ata_scsi_rbuf_lock);
  61static u8 ata_scsi_rbuf[ATA_SCSI_RBUF_SIZE];
  62
  63typedef unsigned int (*ata_xlat_func_t)(struct ata_queued_cmd *qc);
  64
  65static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
  66                                        const struct scsi_device *scsidev);
  67static struct ata_device *ata_scsi_find_dev(struct ata_port *ap,
  68                                            const struct scsi_device *scsidev);
  69
  70#define RW_RECOVERY_MPAGE 0x1
  71#define RW_RECOVERY_MPAGE_LEN 12
  72#define CACHE_MPAGE 0x8
  73#define CACHE_MPAGE_LEN 20
  74#define CONTROL_MPAGE 0xa
  75#define CONTROL_MPAGE_LEN 12
  76#define ALL_MPAGES 0x3f
  77#define ALL_SUB_MPAGES 0xff
  78
  79
  80static const u8 def_rw_recovery_mpage[RW_RECOVERY_MPAGE_LEN] = {
  81        RW_RECOVERY_MPAGE,
  82        RW_RECOVERY_MPAGE_LEN - 2,
  83        (1 << 7),       /* AWRE */
  84        0,              /* read retry count */
  85        0, 0, 0, 0,
  86        0,              /* write retry count */
  87        0, 0, 0
  88};
  89
  90static const u8 def_cache_mpage[CACHE_MPAGE_LEN] = {
  91        CACHE_MPAGE,
  92        CACHE_MPAGE_LEN - 2,
  93        0,              /* contains WCE, needs to be 0 for logic */
  94        0, 0, 0, 0, 0, 0, 0, 0, 0,
  95        0,              /* contains DRA, needs to be 0 for logic */
  96        0, 0, 0, 0, 0, 0, 0
  97};
  98
  99static const u8 def_control_mpage[CONTROL_MPAGE_LEN] = {
 100        CONTROL_MPAGE,
 101        CONTROL_MPAGE_LEN - 2,
 102        2,      /* DSENSE=0, GLTSD=1 */
 103        0,      /* [QAM+QERR may be 1, see 05-359r1] */
 104        0, 0, 0, 0, 0xff, 0xff,
 105        0, 30   /* extended self test time, see 05-359r1 */
 106};
 107
 108static const char *ata_lpm_policy_names[] = {
 109        [ATA_LPM_UNKNOWN]               = "max_performance",
 110        [ATA_LPM_MAX_POWER]             = "max_performance",
 111        [ATA_LPM_MED_POWER]             = "medium_power",
 112        [ATA_LPM_MED_POWER_WITH_DIPM]   = "med_power_with_dipm",
 113        [ATA_LPM_MIN_POWER]             = "min_power",
 114};
 115
 116static ssize_t ata_scsi_lpm_store(struct device *device,
 117                                  struct device_attribute *attr,
 118                                  const char *buf, size_t count)
 119{
 120        struct Scsi_Host *shost = class_to_shost(device);
 121        struct ata_port *ap = ata_shost_to_port(shost);
 122        struct ata_link *link;
 123        struct ata_device *dev;
 124        enum ata_lpm_policy policy;
 125        unsigned long flags;
 126
 127        /* UNKNOWN is internal state, iterate from MAX_POWER */
 128        for (policy = ATA_LPM_MAX_POWER;
 129             policy < ARRAY_SIZE(ata_lpm_policy_names); policy++) {
 130                const char *name = ata_lpm_policy_names[policy];
 131
 132                if (strncmp(name, buf, strlen(name)) == 0)
 133                        break;
 134        }
 135        if (policy == ARRAY_SIZE(ata_lpm_policy_names))
 136                return -EINVAL;
 137
 138        spin_lock_irqsave(ap->lock, flags);
 139
 140        ata_for_each_link(link, ap, EDGE) {
 141                ata_for_each_dev(dev, &ap->link, ENABLED) {
 142                        if (dev->horkage & ATA_HORKAGE_NOLPM) {
 143                                count = -EOPNOTSUPP;
 144                                goto out_unlock;
 145                        }
 146                }
 147        }
 148
 149        ap->target_lpm_policy = policy;
 150        ata_port_schedule_eh(ap);
 151out_unlock:
 152        spin_unlock_irqrestore(ap->lock, flags);
 153        return count;
 154}
 155
 156static ssize_t ata_scsi_lpm_show(struct device *dev,
 157                                 struct device_attribute *attr, char *buf)
 158{
 159        struct Scsi_Host *shost = class_to_shost(dev);
 160        struct ata_port *ap = ata_shost_to_port(shost);
 161
 162        if (ap->target_lpm_policy >= ARRAY_SIZE(ata_lpm_policy_names))
 163                return -EINVAL;
 164
 165        return snprintf(buf, PAGE_SIZE, "%s\n",
 166                        ata_lpm_policy_names[ap->target_lpm_policy]);
 167}
 168DEVICE_ATTR(link_power_management_policy, S_IRUGO | S_IWUSR,
 169            ata_scsi_lpm_show, ata_scsi_lpm_store);
 170EXPORT_SYMBOL_GPL(dev_attr_link_power_management_policy);
 171
 172static ssize_t ata_scsi_park_show(struct device *device,
 173                                  struct device_attribute *attr, char *buf)
 174{
 175        struct scsi_device *sdev = to_scsi_device(device);
 176        struct ata_port *ap;
 177        struct ata_link *link;
 178        struct ata_device *dev;
 179        unsigned long now;
 180        unsigned int uninitialized_var(msecs);
 181        int rc = 0;
 182
 183        ap = ata_shost_to_port(sdev->host);
 184
 185        spin_lock_irq(ap->lock);
 186        dev = ata_scsi_find_dev(ap, sdev);
 187        if (!dev) {
 188                rc = -ENODEV;
 189                goto unlock;
 190        }
 191        if (dev->flags & ATA_DFLAG_NO_UNLOAD) {
 192                rc = -EOPNOTSUPP;
 193                goto unlock;
 194        }
 195
 196        link = dev->link;
 197        now = jiffies;
 198        if (ap->pflags & ATA_PFLAG_EH_IN_PROGRESS &&
 199            link->eh_context.unloaded_mask & (1 << dev->devno) &&
 200            time_after(dev->unpark_deadline, now))
 201                msecs = jiffies_to_msecs(dev->unpark_deadline - now);
 202        else
 203                msecs = 0;
 204
 205unlock:
 206        spin_unlock_irq(ap->lock);
 207
 208        return rc ? rc : snprintf(buf, 20, "%u\n", msecs);
 209}
 210
 211static ssize_t ata_scsi_park_store(struct device *device,
 212                                   struct device_attribute *attr,
 213                                   const char *buf, size_t len)
 214{
 215        struct scsi_device *sdev = to_scsi_device(device);
 216        struct ata_port *ap;
 217        struct ata_device *dev;
 218        long int input;
 219        unsigned long flags;
 220        int rc;
 221
 222        rc = kstrtol(buf, 10, &input);
 223        if (rc)
 224                return rc;
 225        if (input < -2)
 226                return -EINVAL;
 227        if (input > ATA_TMOUT_MAX_PARK) {
 228                rc = -EOVERFLOW;
 229                input = ATA_TMOUT_MAX_PARK;
 230        }
 231
 232        ap = ata_shost_to_port(sdev->host);
 233
 234        spin_lock_irqsave(ap->lock, flags);
 235        dev = ata_scsi_find_dev(ap, sdev);
 236        if (unlikely(!dev)) {
 237                rc = -ENODEV;
 238                goto unlock;
 239        }
 240        if (dev->class != ATA_DEV_ATA &&
 241            dev->class != ATA_DEV_ZAC) {
 242                rc = -EOPNOTSUPP;
 243                goto unlock;
 244        }
 245
 246        if (input >= 0) {
 247                if (dev->flags & ATA_DFLAG_NO_UNLOAD) {
 248                        rc = -EOPNOTSUPP;
 249                        goto unlock;
 250                }
 251
 252                dev->unpark_deadline = ata_deadline(jiffies, input);
 253                dev->link->eh_info.dev_action[dev->devno] |= ATA_EH_PARK;
 254                ata_port_schedule_eh(ap);
 255                complete(&ap->park_req_pending);
 256        } else {
 257                switch (input) {
 258                case -1:
 259                        dev->flags &= ~ATA_DFLAG_NO_UNLOAD;
 260                        break;
 261                case -2:
 262                        dev->flags |= ATA_DFLAG_NO_UNLOAD;
 263                        break;
 264                }
 265        }
 266unlock:
 267        spin_unlock_irqrestore(ap->lock, flags);
 268
 269        return rc ? rc : len;
 270}
 271DEVICE_ATTR(unload_heads, S_IRUGO | S_IWUSR,
 272            ata_scsi_park_show, ata_scsi_park_store);
 273EXPORT_SYMBOL_GPL(dev_attr_unload_heads);
 274
 275static ssize_t ata_ncq_prio_enable_show(struct device *device,
 276                                        struct device_attribute *attr,
 277                                        char *buf)
 278{
 279        struct scsi_device *sdev = to_scsi_device(device);
 280        struct ata_port *ap;
 281        struct ata_device *dev;
 282        bool ncq_prio_enable;
 283        int rc = 0;
 284
 285        ap = ata_shost_to_port(sdev->host);
 286
 287        spin_lock_irq(ap->lock);
 288        dev = ata_scsi_find_dev(ap, sdev);
 289        if (!dev) {
 290                rc = -ENODEV;
 291                goto unlock;
 292        }
 293
 294        ncq_prio_enable = dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLE;
 295
 296unlock:
 297        spin_unlock_irq(ap->lock);
 298
 299        return rc ? rc : snprintf(buf, 20, "%u\n", ncq_prio_enable);
 300}
 301
 302static ssize_t ata_ncq_prio_enable_store(struct device *device,
 303                                         struct device_attribute *attr,
 304                                         const char *buf, size_t len)
 305{
 306        struct scsi_device *sdev = to_scsi_device(device);
 307        struct ata_port *ap;
 308        struct ata_device *dev;
 309        long int input;
 310        int rc;
 311
 312        rc = kstrtol(buf, 10, &input);
 313        if (rc)
 314                return rc;
 315        if ((input < 0) || (input > 1))
 316                return -EINVAL;
 317
 318        ap = ata_shost_to_port(sdev->host);
 319        dev = ata_scsi_find_dev(ap, sdev);
 320        if (unlikely(!dev))
 321                return  -ENODEV;
 322
 323        spin_lock_irq(ap->lock);
 324        if (input)
 325                dev->flags |= ATA_DFLAG_NCQ_PRIO_ENABLE;
 326        else
 327                dev->flags &= ~ATA_DFLAG_NCQ_PRIO_ENABLE;
 328
 329        dev->link->eh_info.action |= ATA_EH_REVALIDATE;
 330        dev->link->eh_info.flags |= ATA_EHI_QUIET;
 331        ata_port_schedule_eh(ap);
 332        spin_unlock_irq(ap->lock);
 333
 334        ata_port_wait_eh(ap);
 335
 336        if (input) {
 337                spin_lock_irq(ap->lock);
 338                if (!(dev->flags & ATA_DFLAG_NCQ_PRIO)) {
 339                        dev->flags &= ~ATA_DFLAG_NCQ_PRIO_ENABLE;
 340                        rc = -EIO;
 341                }
 342                spin_unlock_irq(ap->lock);
 343        }
 344
 345        return rc ? rc : len;
 346}
 347
 348DEVICE_ATTR(ncq_prio_enable, S_IRUGO | S_IWUSR,
 349            ata_ncq_prio_enable_show, ata_ncq_prio_enable_store);
 350EXPORT_SYMBOL_GPL(dev_attr_ncq_prio_enable);
 351
 352void ata_scsi_set_sense(struct ata_device *dev, struct scsi_cmnd *cmd,
 353                        u8 sk, u8 asc, u8 ascq)
 354{
 355        bool d_sense = (dev->flags & ATA_DFLAG_D_SENSE);
 356
 357        if (!cmd)
 358                return;
 359
 360        cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
 361
 362        scsi_build_sense_buffer(d_sense, cmd->sense_buffer, sk, asc, ascq);
 363}
 364
 365void ata_scsi_set_sense_information(struct ata_device *dev,
 366                                    struct scsi_cmnd *cmd,
 367                                    const struct ata_taskfile *tf)
 368{
 369        u64 information;
 370
 371        if (!cmd)
 372                return;
 373
 374        information = ata_tf_read_block(tf, dev);
 375        if (information == U64_MAX)
 376                return;
 377
 378        scsi_set_sense_information(cmd->sense_buffer,
 379                                   SCSI_SENSE_BUFFERSIZE, information);
 380}
 381
 382static void ata_scsi_set_invalid_field(struct ata_device *dev,
 383                                       struct scsi_cmnd *cmd, u16 field, u8 bit)
 384{
 385        ata_scsi_set_sense(dev, cmd, ILLEGAL_REQUEST, 0x24, 0x0);
 386        /* "Invalid field in CDB" */
 387        scsi_set_sense_field_pointer(cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE,
 388                                     field, bit, 1);
 389}
 390
 391static void ata_scsi_set_invalid_parameter(struct ata_device *dev,
 392                                           struct scsi_cmnd *cmd, u16 field)
 393{
 394        /* "Invalid field in parameter list" */
 395        ata_scsi_set_sense(dev, cmd, ILLEGAL_REQUEST, 0x26, 0x0);
 396        scsi_set_sense_field_pointer(cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE,
 397                                     field, 0xff, 0);
 398}
 399
 400static ssize_t
 401ata_scsi_em_message_store(struct device *dev, struct device_attribute *attr,
 402                          const char *buf, size_t count)
 403{
 404        struct Scsi_Host *shost = class_to_shost(dev);
 405        struct ata_port *ap = ata_shost_to_port(shost);
 406        if (ap->ops->em_store && (ap->flags & ATA_FLAG_EM))
 407                return ap->ops->em_store(ap, buf, count);
 408        return -EINVAL;
 409}
 410
 411static ssize_t
 412ata_scsi_em_message_show(struct device *dev, struct device_attribute *attr,
 413                         char *buf)
 414{
 415        struct Scsi_Host *shost = class_to_shost(dev);
 416        struct ata_port *ap = ata_shost_to_port(shost);
 417
 418        if (ap->ops->em_show && (ap->flags & ATA_FLAG_EM))
 419                return ap->ops->em_show(ap, buf);
 420        return -EINVAL;
 421}
 422DEVICE_ATTR(em_message, S_IRUGO | S_IWUSR,
 423                ata_scsi_em_message_show, ata_scsi_em_message_store);
 424EXPORT_SYMBOL_GPL(dev_attr_em_message);
 425
 426static ssize_t
 427ata_scsi_em_message_type_show(struct device *dev, struct device_attribute *attr,
 428                              char *buf)
 429{
 430        struct Scsi_Host *shost = class_to_shost(dev);
 431        struct ata_port *ap = ata_shost_to_port(shost);
 432
 433        return snprintf(buf, 23, "%d\n", ap->em_message_type);
 434}
 435DEVICE_ATTR(em_message_type, S_IRUGO,
 436                  ata_scsi_em_message_type_show, NULL);
 437EXPORT_SYMBOL_GPL(dev_attr_em_message_type);
 438
 439static ssize_t
 440ata_scsi_activity_show(struct device *dev, struct device_attribute *attr,
 441                char *buf)
 442{
 443        struct scsi_device *sdev = to_scsi_device(dev);
 444        struct ata_port *ap = ata_shost_to_port(sdev->host);
 445        struct ata_device *atadev = ata_scsi_find_dev(ap, sdev);
 446
 447        if (atadev && ap->ops->sw_activity_show &&
 448            (ap->flags & ATA_FLAG_SW_ACTIVITY))
 449                return ap->ops->sw_activity_show(atadev, buf);
 450        return -EINVAL;
 451}
 452
 453static ssize_t
 454ata_scsi_activity_store(struct device *dev, struct device_attribute *attr,
 455        const char *buf, size_t count)
 456{
 457        struct scsi_device *sdev = to_scsi_device(dev);
 458        struct ata_port *ap = ata_shost_to_port(sdev->host);
 459        struct ata_device *atadev = ata_scsi_find_dev(ap, sdev);
 460        enum sw_activity val;
 461        int rc;
 462
 463        if (atadev && ap->ops->sw_activity_store &&
 464            (ap->flags & ATA_FLAG_SW_ACTIVITY)) {
 465                val = simple_strtoul(buf, NULL, 0);
 466                switch (val) {
 467                case OFF: case BLINK_ON: case BLINK_OFF:
 468                        rc = ap->ops->sw_activity_store(atadev, val);
 469                        if (!rc)
 470                                return count;
 471                        else
 472                                return rc;
 473                }
 474        }
 475        return -EINVAL;
 476}
 477DEVICE_ATTR(sw_activity, S_IWUSR | S_IRUGO, ata_scsi_activity_show,
 478                        ata_scsi_activity_store);
 479EXPORT_SYMBOL_GPL(dev_attr_sw_activity);
 480
 481struct device_attribute *ata_common_sdev_attrs[] = {
 482        &dev_attr_unload_heads,
 483        &dev_attr_ncq_prio_enable,
 484        NULL
 485};
 486EXPORT_SYMBOL_GPL(ata_common_sdev_attrs);
 487
 488/**
 489 *      ata_std_bios_param - generic bios head/sector/cylinder calculator used by sd.
 490 *      @sdev: SCSI device for which BIOS geometry is to be determined
 491 *      @bdev: block device associated with @sdev
 492 *      @capacity: capacity of SCSI device
 493 *      @geom: location to which geometry will be output
 494 *
 495 *      Generic bios head/sector/cylinder calculator
 496 *      used by sd. Most BIOSes nowadays expect a XXX/255/16  (CHS)
 497 *      mapping. Some situations may arise where the disk is not
 498 *      bootable if this is not used.
 499 *
 500 *      LOCKING:
 501 *      Defined by the SCSI layer.  We don't really care.
 502 *
 503 *      RETURNS:
 504 *      Zero.
 505 */
 506int ata_std_bios_param(struct scsi_device *sdev, struct block_device *bdev,
 507                       sector_t capacity, int geom[])
 508{
 509        geom[0] = 255;
 510        geom[1] = 63;
 511        sector_div(capacity, 255*63);
 512        geom[2] = capacity;
 513
 514        return 0;
 515}
 516
 517/**
 518 *      ata_scsi_unlock_native_capacity - unlock native capacity
 519 *      @sdev: SCSI device to adjust device capacity for
 520 *
 521 *      This function is called if a partition on @sdev extends beyond
 522 *      the end of the device.  It requests EH to unlock HPA.
 523 *
 524 *      LOCKING:
 525 *      Defined by the SCSI layer.  Might sleep.
 526 */
 527void ata_scsi_unlock_native_capacity(struct scsi_device *sdev)
 528{
 529        struct ata_port *ap = ata_shost_to_port(sdev->host);
 530        struct ata_device *dev;
 531        unsigned long flags;
 532
 533        spin_lock_irqsave(ap->lock, flags);
 534
 535        dev = ata_scsi_find_dev(ap, sdev);
 536        if (dev && dev->n_sectors < dev->n_native_sectors) {
 537                dev->flags |= ATA_DFLAG_UNLOCK_HPA;
 538                dev->link->eh_info.action |= ATA_EH_RESET;
 539                ata_port_schedule_eh(ap);
 540        }
 541
 542        spin_unlock_irqrestore(ap->lock, flags);
 543        ata_port_wait_eh(ap);
 544}
 545
 546/**
 547 *      ata_get_identity - Handler for HDIO_GET_IDENTITY ioctl
 548 *      @ap: target port
 549 *      @sdev: SCSI device to get identify data for
 550 *      @arg: User buffer area for identify data
 551 *
 552 *      LOCKING:
 553 *      Defined by the SCSI layer.  We don't really care.
 554 *
 555 *      RETURNS:
 556 *      Zero on success, negative errno on error.
 557 */
 558static int ata_get_identity(struct ata_port *ap, struct scsi_device *sdev,
 559                            void __user *arg)
 560{
 561        struct ata_device *dev = ata_scsi_find_dev(ap, sdev);
 562        u16 __user *dst = arg;
 563        char buf[40];
 564
 565        if (!dev)
 566                return -ENOMSG;
 567
 568        if (copy_to_user(dst, dev->id, ATA_ID_WORDS * sizeof(u16)))
 569                return -EFAULT;
 570
 571        ata_id_string(dev->id, buf, ATA_ID_PROD, ATA_ID_PROD_LEN);
 572        if (copy_to_user(dst + ATA_ID_PROD, buf, ATA_ID_PROD_LEN))
 573                return -EFAULT;
 574
 575        ata_id_string(dev->id, buf, ATA_ID_FW_REV, ATA_ID_FW_REV_LEN);
 576        if (copy_to_user(dst + ATA_ID_FW_REV, buf, ATA_ID_FW_REV_LEN))
 577                return -EFAULT;
 578
 579        ata_id_string(dev->id, buf, ATA_ID_SERNO, ATA_ID_SERNO_LEN);
 580        if (copy_to_user(dst + ATA_ID_SERNO, buf, ATA_ID_SERNO_LEN))
 581                return -EFAULT;
 582
 583        return 0;
 584}
 585
 586/**
 587 *      ata_cmd_ioctl - Handler for HDIO_DRIVE_CMD ioctl
 588 *      @scsidev: Device to which we are issuing command
 589 *      @arg: User provided data for issuing command
 590 *
 591 *      LOCKING:
 592 *      Defined by the SCSI layer.  We don't really care.
 593 *
 594 *      RETURNS:
 595 *      Zero on success, negative errno on error.
 596 */
 597int ata_cmd_ioctl(struct scsi_device *scsidev, void __user *arg)
 598{
 599        int rc = 0;
 600        u8 sensebuf[SCSI_SENSE_BUFFERSIZE];
 601        u8 scsi_cmd[MAX_COMMAND_SIZE];
 602        u8 args[4], *argbuf = NULL;
 603        int argsize = 0;
 604        enum dma_data_direction data_dir;
 605        struct scsi_sense_hdr sshdr;
 606        int cmd_result;
 607
 608        if (arg == NULL)
 609                return -EINVAL;
 610
 611        if (copy_from_user(args, arg, sizeof(args)))
 612                return -EFAULT;
 613
 614        memset(sensebuf, 0, sizeof(sensebuf));
 615        memset(scsi_cmd, 0, sizeof(scsi_cmd));
 616
 617        if (args[3]) {
 618                argsize = ATA_SECT_SIZE * args[3];
 619                argbuf = kmalloc(argsize, GFP_KERNEL);
 620                if (argbuf == NULL) {
 621                        rc = -ENOMEM;
 622                        goto error;
 623                }
 624
 625                scsi_cmd[1]  = (4 << 1); /* PIO Data-in */
 626                scsi_cmd[2]  = 0x0e;     /* no off.line or cc, read from dev,
 627                                            block count in sector count field */
 628                data_dir = DMA_FROM_DEVICE;
 629        } else {
 630                scsi_cmd[1]  = (3 << 1); /* Non-data */
 631                scsi_cmd[2]  = 0x20;     /* cc but no off.line or data xfer */
 632                data_dir = DMA_NONE;
 633        }
 634
 635        scsi_cmd[0] = ATA_16;
 636
 637        scsi_cmd[4] = args[2];
 638        if (args[0] == ATA_CMD_SMART) { /* hack -- ide driver does this too */
 639                scsi_cmd[6]  = args[3];
 640                scsi_cmd[8]  = args[1];
 641                scsi_cmd[10] = 0x4f;
 642                scsi_cmd[12] = 0xc2;
 643        } else {
 644                scsi_cmd[6]  = args[1];
 645        }
 646        scsi_cmd[14] = args[0];
 647
 648        /* Good values for timeout and retries?  Values below
 649           from scsi_ioctl_send_command() for default case... */
 650        cmd_result = scsi_execute(scsidev, scsi_cmd, data_dir, argbuf, argsize,
 651                                  sensebuf, &sshdr, (10*HZ), 5, 0, 0, NULL);
 652
 653        if (driver_byte(cmd_result) == DRIVER_SENSE) {/* sense data available */
 654                u8 *desc = sensebuf + 8;
 655                cmd_result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
 656
 657                /* If we set cc then ATA pass-through will cause a
 658                 * check condition even if no error. Filter that. */
 659                if (cmd_result & SAM_STAT_CHECK_CONDITION) {
 660                        if (sshdr.sense_key == RECOVERED_ERROR &&
 661                            sshdr.asc == 0 && sshdr.ascq == 0x1d)
 662                                cmd_result &= ~SAM_STAT_CHECK_CONDITION;
 663                }
 664
 665                /* Send userspace a few ATA registers (same as drivers/ide) */
 666                if (sensebuf[0] == 0x72 &&      /* format is "descriptor" */
 667                    desc[0] == 0x09) {          /* code is "ATA Descriptor" */
 668                        args[0] = desc[13];     /* status */
 669                        args[1] = desc[3];      /* error */
 670                        args[2] = desc[5];      /* sector count (0:7) */
 671                        if (copy_to_user(arg, args, sizeof(args)))
 672                                rc = -EFAULT;
 673                }
 674        }
 675
 676
 677        if (cmd_result) {
 678                rc = -EIO;
 679                goto error;
 680        }
 681
 682        if ((argbuf)
 683         && copy_to_user(arg + sizeof(args), argbuf, argsize))
 684                rc = -EFAULT;
 685error:
 686        kfree(argbuf);
 687        return rc;
 688}
 689
 690/**
 691 *      ata_task_ioctl - Handler for HDIO_DRIVE_TASK ioctl
 692 *      @scsidev: Device to which we are issuing command
 693 *      @arg: User provided data for issuing command
 694 *
 695 *      LOCKING:
 696 *      Defined by the SCSI layer.  We don't really care.
 697 *
 698 *      RETURNS:
 699 *      Zero on success, negative errno on error.
 700 */
 701int ata_task_ioctl(struct scsi_device *scsidev, void __user *arg)
 702{
 703        int rc = 0;
 704        u8 sensebuf[SCSI_SENSE_BUFFERSIZE];
 705        u8 scsi_cmd[MAX_COMMAND_SIZE];
 706        u8 args[7];
 707        struct scsi_sense_hdr sshdr;
 708        int cmd_result;
 709
 710        if (arg == NULL)
 711                return -EINVAL;
 712
 713        if (copy_from_user(args, arg, sizeof(args)))
 714                return -EFAULT;
 715
 716        memset(sensebuf, 0, sizeof(sensebuf));
 717        memset(scsi_cmd, 0, sizeof(scsi_cmd));
 718        scsi_cmd[0]  = ATA_16;
 719        scsi_cmd[1]  = (3 << 1); /* Non-data */
 720        scsi_cmd[2]  = 0x20;     /* cc but no off.line or data xfer */
 721        scsi_cmd[4]  = args[1];
 722        scsi_cmd[6]  = args[2];
 723        scsi_cmd[8]  = args[3];
 724        scsi_cmd[10] = args[4];
 725        scsi_cmd[12] = args[5];
 726        scsi_cmd[13] = args[6] & 0x4f;
 727        scsi_cmd[14] = args[0];
 728
 729        /* Good values for timeout and retries?  Values below
 730           from scsi_ioctl_send_command() for default case... */
 731        cmd_result = scsi_execute(scsidev, scsi_cmd, DMA_NONE, NULL, 0,
 732                                sensebuf, &sshdr, (10*HZ), 5, 0, 0, NULL);
 733
 734        if (driver_byte(cmd_result) == DRIVER_SENSE) {/* sense data available */
 735                u8 *desc = sensebuf + 8;
 736                cmd_result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
 737
 738                /* If we set cc then ATA pass-through will cause a
 739                 * check condition even if no error. Filter that. */
 740                if (cmd_result & SAM_STAT_CHECK_CONDITION) {
 741                        if (sshdr.sense_key == RECOVERED_ERROR &&
 742                            sshdr.asc == 0 && sshdr.ascq == 0x1d)
 743                                cmd_result &= ~SAM_STAT_CHECK_CONDITION;
 744                }
 745
 746                /* Send userspace ATA registers */
 747                if (sensebuf[0] == 0x72 &&      /* format is "descriptor" */
 748                                desc[0] == 0x09) {/* code is "ATA Descriptor" */
 749                        args[0] = desc[13];     /* status */
 750                        args[1] = desc[3];      /* error */
 751                        args[2] = desc[5];      /* sector count (0:7) */
 752                        args[3] = desc[7];      /* lbal */
 753                        args[4] = desc[9];      /* lbam */
 754                        args[5] = desc[11];     /* lbah */
 755                        args[6] = desc[12];     /* select */
 756                        if (copy_to_user(arg, args, sizeof(args)))
 757                                rc = -EFAULT;
 758                }
 759        }
 760
 761        if (cmd_result) {
 762                rc = -EIO;
 763                goto error;
 764        }
 765
 766 error:
 767        return rc;
 768}
 769
 770static int ata_ioc32(struct ata_port *ap)
 771{
 772        if (ap->flags & ATA_FLAG_PIO_DMA)
 773                return 1;
 774        if (ap->pflags & ATA_PFLAG_PIO32)
 775                return 1;
 776        return 0;
 777}
 778
 779int ata_sas_scsi_ioctl(struct ata_port *ap, struct scsi_device *scsidev,
 780                     int cmd, void __user *arg)
 781{
 782        unsigned long val;
 783        int rc = -EINVAL;
 784        unsigned long flags;
 785
 786        switch (cmd) {
 787        case HDIO_GET_32BIT:
 788                spin_lock_irqsave(ap->lock, flags);
 789                val = ata_ioc32(ap);
 790                spin_unlock_irqrestore(ap->lock, flags);
 791                return put_user(val, (unsigned long __user *)arg);
 792
 793        case HDIO_SET_32BIT:
 794                val = (unsigned long) arg;
 795                rc = 0;
 796                spin_lock_irqsave(ap->lock, flags);
 797                if (ap->pflags & ATA_PFLAG_PIO32CHANGE) {
 798                        if (val)
 799                                ap->pflags |= ATA_PFLAG_PIO32;
 800                        else
 801                                ap->pflags &= ~ATA_PFLAG_PIO32;
 802                } else {
 803                        if (val != ata_ioc32(ap))
 804                                rc = -EINVAL;
 805                }
 806                spin_unlock_irqrestore(ap->lock, flags);
 807                return rc;
 808
 809        case HDIO_GET_IDENTITY:
 810                return ata_get_identity(ap, scsidev, arg);
 811
 812        case HDIO_DRIVE_CMD:
 813                if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
 814                        return -EACCES;
 815                return ata_cmd_ioctl(scsidev, arg);
 816
 817        case HDIO_DRIVE_TASK:
 818                if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
 819                        return -EACCES;
 820                return ata_task_ioctl(scsidev, arg);
 821
 822        default:
 823                rc = -ENOTTY;
 824                break;
 825        }
 826
 827        return rc;
 828}
 829EXPORT_SYMBOL_GPL(ata_sas_scsi_ioctl);
 830
 831int ata_scsi_ioctl(struct scsi_device *scsidev, int cmd, void __user *arg)
 832{
 833        return ata_sas_scsi_ioctl(ata_shost_to_port(scsidev->host),
 834                                scsidev, cmd, arg);
 835}
 836EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
 837
 838/**
 839 *      ata_scsi_qc_new - acquire new ata_queued_cmd reference
 840 *      @dev: ATA device to which the new command is attached
 841 *      @cmd: SCSI command that originated this ATA command
 842 *
 843 *      Obtain a reference to an unused ata_queued_cmd structure,
 844 *      which is the basic libata structure representing a single
 845 *      ATA command sent to the hardware.
 846 *
 847 *      If a command was available, fill in the SCSI-specific
 848 *      portions of the structure with information on the
 849 *      current command.
 850 *
 851 *      LOCKING:
 852 *      spin_lock_irqsave(host lock)
 853 *
 854 *      RETURNS:
 855 *      Command allocated, or %NULL if none available.
 856 */
 857static struct ata_queued_cmd *ata_scsi_qc_new(struct ata_device *dev,
 858                                              struct scsi_cmnd *cmd)
 859{
 860        struct ata_queued_cmd *qc;
 861
 862        qc = ata_qc_new_init(dev, cmd->request->tag);
 863        if (qc) {
 864                qc->scsicmd = cmd;
 865                qc->scsidone = cmd->scsi_done;
 866
 867                qc->sg = scsi_sglist(cmd);
 868                qc->n_elem = scsi_sg_count(cmd);
 869
 870                if (cmd->request->rq_flags & RQF_QUIET)
 871                        qc->flags |= ATA_QCFLAG_QUIET;
 872        } else {
 873                cmd->result = (DID_OK << 16) | (QUEUE_FULL << 1);
 874                cmd->scsi_done(cmd);
 875        }
 876
 877        return qc;
 878}
 879
 880static void ata_qc_set_pc_nbytes(struct ata_queued_cmd *qc)
 881{
 882        struct scsi_cmnd *scmd = qc->scsicmd;
 883
 884        qc->extrabytes = scmd->request->extra_len;
 885        qc->nbytes = scsi_bufflen(scmd) + qc->extrabytes;
 886}
 887
 888/**
 889 *      ata_dump_status - user friendly display of error info
 890 *      @id: id of the port in question
 891 *      @tf: ptr to filled out taskfile
 892 *
 893 *      Decode and dump the ATA error/status registers for the user so
 894 *      that they have some idea what really happened at the non
 895 *      make-believe layer.
 896 *
 897 *      LOCKING:
 898 *      inherited from caller
 899 */
 900static void ata_dump_status(unsigned id, struct ata_taskfile *tf)
 901{
 902        u8 stat = tf->command, err = tf->feature;
 903
 904        pr_warn("ata%u: status=0x%02x { ", id, stat);
 905        if (stat & ATA_BUSY) {
 906                pr_cont("Busy }\n");    /* Data is not valid in this case */
 907        } else {
 908                if (stat & ATA_DRDY)    pr_cont("DriveReady ");
 909                if (stat & ATA_DF)      pr_cont("DeviceFault ");
 910                if (stat & ATA_DSC)     pr_cont("SeekComplete ");
 911                if (stat & ATA_DRQ)     pr_cont("DataRequest ");
 912                if (stat & ATA_CORR)    pr_cont("CorrectedError ");
 913                if (stat & ATA_SENSE)   pr_cont("Sense ");
 914                if (stat & ATA_ERR)     pr_cont("Error ");
 915                pr_cont("}\n");
 916
 917                if (err) {
 918                        pr_warn("ata%u: error=0x%02x { ", id, err);
 919                        if (err & ATA_ABORTED)  pr_cont("DriveStatusError ");
 920                        if (err & ATA_ICRC) {
 921                                if (err & ATA_ABORTED)
 922                                                pr_cont("BadCRC ");
 923                                else            pr_cont("Sector ");
 924                        }
 925                        if (err & ATA_UNC)      pr_cont("UncorrectableError ");
 926                        if (err & ATA_IDNF)     pr_cont("SectorIdNotFound ");
 927                        if (err & ATA_TRK0NF)   pr_cont("TrackZeroNotFound ");
 928                        if (err & ATA_AMNF)     pr_cont("AddrMarkNotFound ");
 929                        pr_cont("}\n");
 930                }
 931        }
 932}
 933
 934/**
 935 *      ata_to_sense_error - convert ATA error to SCSI error
 936 *      @id: ATA device number
 937 *      @drv_stat: value contained in ATA status register
 938 *      @drv_err: value contained in ATA error register
 939 *      @sk: the sense key we'll fill out
 940 *      @asc: the additional sense code we'll fill out
 941 *      @ascq: the additional sense code qualifier we'll fill out
 942 *      @verbose: be verbose
 943 *
 944 *      Converts an ATA error into a SCSI error.  Fill out pointers to
 945 *      SK, ASC, and ASCQ bytes for later use in fixed or descriptor
 946 *      format sense blocks.
 947 *
 948 *      LOCKING:
 949 *      spin_lock_irqsave(host lock)
 950 */
 951static void ata_to_sense_error(unsigned id, u8 drv_stat, u8 drv_err, u8 *sk,
 952                               u8 *asc, u8 *ascq, int verbose)
 953{
 954        int i;
 955
 956        /* Based on the 3ware driver translation table */
 957        static const unsigned char sense_table[][4] = {
 958                /* BBD|ECC|ID|MAR */
 959                {0xd1,          ABORTED_COMMAND, 0x00, 0x00},
 960                        // Device busy                  Aborted command
 961                /* BBD|ECC|ID */
 962                {0xd0,          ABORTED_COMMAND, 0x00, 0x00},
 963                        // Device busy                  Aborted command
 964                /* ECC|MC|MARK */
 965                {0x61,          HARDWARE_ERROR, 0x00, 0x00},
 966                        // Device fault                 Hardware error
 967                /* ICRC|ABRT */         /* NB: ICRC & !ABRT is BBD */
 968                {0x84,          ABORTED_COMMAND, 0x47, 0x00},
 969                        // Data CRC error               SCSI parity error
 970                /* MC|ID|ABRT|TRK0|MARK */
 971                {0x37,          NOT_READY, 0x04, 0x00},
 972                        // Unit offline                 Not ready
 973                /* MCR|MARK */
 974                {0x09,          NOT_READY, 0x04, 0x00},
 975                        // Unrecovered disk error       Not ready
 976                /*  Bad address mark */
 977                {0x01,          MEDIUM_ERROR, 0x13, 0x00},
 978                        // Address mark not found for data field
 979                /* TRK0 - Track 0 not found */
 980                {0x02,          HARDWARE_ERROR, 0x00, 0x00},
 981                        // Hardware error
 982                /* Abort: 0x04 is not translated here, see below */
 983                /* Media change request */
 984                {0x08,          NOT_READY, 0x04, 0x00},
 985                        // FIXME: faking offline
 986                /* SRV/IDNF - ID not found */
 987                {0x10,          ILLEGAL_REQUEST, 0x21, 0x00},
 988                        // Logical address out of range
 989                /* MC - Media Changed */
 990                {0x20,          UNIT_ATTENTION, 0x28, 0x00},
 991                        // Not ready to ready change, medium may have changed
 992                /* ECC - Uncorrectable ECC error */
 993                {0x40,          MEDIUM_ERROR, 0x11, 0x04},
 994                        // Unrecovered read error
 995                /* BBD - block marked bad */
 996                {0x80,          MEDIUM_ERROR, 0x11, 0x04},
 997                        // Block marked bad     Medium error, unrecovered read error
 998                {0xFF, 0xFF, 0xFF, 0xFF}, // END mark
 999        };
1000        static const unsigned char stat_table[][4] = {
1001                /* Must be first because BUSY means no other bits valid */
1002                {0x80,          ABORTED_COMMAND, 0x47, 0x00},
1003                // Busy, fake parity for now
1004                {0x40,          ILLEGAL_REQUEST, 0x21, 0x04},
1005                // Device ready, unaligned write command
1006                {0x20,          HARDWARE_ERROR,  0x44, 0x00},
1007                // Device fault, internal target failure
1008                {0x08,          ABORTED_COMMAND, 0x47, 0x00},
1009                // Timed out in xfer, fake parity for now
1010                {0x04,          RECOVERED_ERROR, 0x11, 0x00},
1011                // Recovered ECC error    Medium error, recovered
1012                {0xFF, 0xFF, 0xFF, 0xFF}, // END mark
1013        };
1014
1015        /*
1016         *      Is this an error we can process/parse
1017         */
1018        if (drv_stat & ATA_BUSY) {
1019                drv_err = 0;    /* Ignore the err bits, they're invalid */
1020        }
1021
1022        if (drv_err) {
1023                /* Look for drv_err */
1024                for (i = 0; sense_table[i][0] != 0xFF; i++) {
1025                        /* Look for best matches first */
1026                        if ((sense_table[i][0] & drv_err) ==
1027                            sense_table[i][0]) {
1028                                *sk = sense_table[i][1];
1029                                *asc = sense_table[i][2];
1030                                *ascq = sense_table[i][3];
1031                                goto translate_done;
1032                        }
1033                }
1034        }
1035
1036        /*
1037         * Fall back to interpreting status bits.  Note that if the drv_err
1038         * has only the ABRT bit set, we decode drv_stat.  ABRT by itself
1039         * is not descriptive enough.
1040         */
1041        for (i = 0; stat_table[i][0] != 0xFF; i++) {
1042                if (stat_table[i][0] & drv_stat) {
1043                        *sk = stat_table[i][1];
1044                        *asc = stat_table[i][2];
1045                        *ascq = stat_table[i][3];
1046                        goto translate_done;
1047                }
1048        }
1049
1050        /*
1051         * We need a sensible error return here, which is tricky, and one
1052         * that won't cause people to do things like return a disk wrongly.
1053         */
1054        *sk = ABORTED_COMMAND;
1055        *asc = 0x00;
1056        *ascq = 0x00;
1057
1058 translate_done:
1059        if (verbose)
1060                pr_err("ata%u: translated ATA stat/err 0x%02x/%02x to SCSI SK/ASC/ASCQ 0x%x/%02x/%02x\n",
1061                       id, drv_stat, drv_err, *sk, *asc, *ascq);
1062        return;
1063}
1064
1065/*
1066 *      ata_gen_passthru_sense - Generate check condition sense block.
1067 *      @qc: Command that completed.
1068 *
1069 *      This function is specific to the ATA descriptor format sense
1070 *      block specified for the ATA pass through commands.  Regardless
1071 *      of whether the command errored or not, return a sense
1072 *      block. Copy all controller registers into the sense
1073 *      block. If there was no error, we get the request from an ATA
1074 *      passthrough command, so we use the following sense data:
1075 *      sk = RECOVERED ERROR
1076 *      asc,ascq = ATA PASS-THROUGH INFORMATION AVAILABLE
1077 *      
1078 *
1079 *      LOCKING:
1080 *      None.
1081 */
1082static void ata_gen_passthru_sense(struct ata_queued_cmd *qc)
1083{
1084        struct scsi_cmnd *cmd = qc->scsicmd;
1085        struct ata_taskfile *tf = &qc->result_tf;
1086        unsigned char *sb = cmd->sense_buffer;
1087        unsigned char *desc = sb + 8;
1088        int verbose = qc->ap->ops->error_handler == NULL;
1089        u8 sense_key, asc, ascq;
1090
1091        memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
1092
1093        cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
1094
1095        /*
1096         * Use ata_to_sense_error() to map status register bits
1097         * onto sense key, asc & ascq.
1098         */
1099        if (qc->err_mask ||
1100            tf->command & (ATA_BUSY | ATA_DF | ATA_ERR | ATA_DRQ)) {
1101                ata_to_sense_error(qc->ap->print_id, tf->command, tf->feature,
1102                                   &sense_key, &asc, &ascq, verbose);
1103                ata_scsi_set_sense(qc->dev, cmd, sense_key, asc, ascq);
1104        } else {
1105                /*
1106                 * ATA PASS-THROUGH INFORMATION AVAILABLE
1107                 * Always in descriptor format sense.
1108                 */
1109                scsi_build_sense_buffer(1, cmd->sense_buffer,
1110                                        RECOVERED_ERROR, 0, 0x1D);
1111        }
1112
1113        if ((cmd->sense_buffer[0] & 0x7f) >= 0x72) {
1114                u8 len;
1115
1116                /* descriptor format */
1117                len = sb[7];
1118                desc = (char *)scsi_sense_desc_find(sb, len + 8, 9);
1119                if (!desc) {
1120                        if (SCSI_SENSE_BUFFERSIZE < len + 14)
1121                                return;
1122                        sb[7] = len + 14;
1123                        desc = sb + 8 + len;
1124                }
1125                desc[0] = 9;
1126                desc[1] = 12;
1127                /*
1128                 * Copy registers into sense buffer.
1129                 */
1130                desc[2] = 0x00;
1131                desc[3] = tf->feature;  /* == error reg */
1132                desc[5] = tf->nsect;
1133                desc[7] = tf->lbal;
1134                desc[9] = tf->lbam;
1135                desc[11] = tf->lbah;
1136                desc[12] = tf->device;
1137                desc[13] = tf->command; /* == status reg */
1138
1139                /*
1140                 * Fill in Extend bit, and the high order bytes
1141                 * if applicable.
1142                 */
1143                if (tf->flags & ATA_TFLAG_LBA48) {
1144                        desc[2] |= 0x01;
1145                        desc[4] = tf->hob_nsect;
1146                        desc[6] = tf->hob_lbal;
1147                        desc[8] = tf->hob_lbam;
1148                        desc[10] = tf->hob_lbah;
1149                }
1150        } else {
1151                /* Fixed sense format */
1152                desc[0] = tf->feature;
1153                desc[1] = tf->command; /* status */
1154                desc[2] = tf->device;
1155                desc[3] = tf->nsect;
1156                desc[7] = 0;
1157                if (tf->flags & ATA_TFLAG_LBA48)  {
1158                        desc[8] |= 0x80;
1159                        if (tf->hob_nsect)
1160                                desc[8] |= 0x40;
1161                        if (tf->hob_lbal || tf->hob_lbam || tf->hob_lbah)
1162                                desc[8] |= 0x20;
1163                }
1164                desc[9] = tf->lbal;
1165                desc[10] = tf->lbam;
1166                desc[11] = tf->lbah;
1167        }
1168}
1169
1170/**
1171 *      ata_gen_ata_sense - generate a SCSI fixed sense block
1172 *      @qc: Command that we are erroring out
1173 *
1174 *      Generate sense block for a failed ATA command @qc.  Descriptor
1175 *      format is used to accommodate LBA48 block address.
1176 *
1177 *      LOCKING:
1178 *      None.
1179 */
1180static void ata_gen_ata_sense(struct ata_queued_cmd *qc)
1181{
1182        struct ata_device *dev = qc->dev;
1183        struct scsi_cmnd *cmd = qc->scsicmd;
1184        struct ata_taskfile *tf = &qc->result_tf;
1185        unsigned char *sb = cmd->sense_buffer;
1186        int verbose = qc->ap->ops->error_handler == NULL;
1187        u64 block;
1188        u8 sense_key, asc, ascq;
1189
1190        memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
1191
1192        cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
1193
1194        if (ata_dev_disabled(dev)) {
1195                /* Device disabled after error recovery */
1196                /* LOGICAL UNIT NOT READY, HARD RESET REQUIRED */
1197                ata_scsi_set_sense(dev, cmd, NOT_READY, 0x04, 0x21);
1198                return;
1199        }
1200        /* Use ata_to_sense_error() to map status register bits
1201         * onto sense key, asc & ascq.
1202         */
1203        if (qc->err_mask ||
1204            tf->command & (ATA_BUSY | ATA_DF | ATA_ERR | ATA_DRQ)) {
1205                ata_to_sense_error(qc->ap->print_id, tf->command, tf->feature,
1206                                   &sense_key, &asc, &ascq, verbose);
1207                ata_scsi_set_sense(dev, cmd, sense_key, asc, ascq);
1208        } else {
1209                /* Could not decode error */
1210                ata_dev_warn(dev, "could not decode error status 0x%x err_mask 0x%x\n",
1211                             tf->command, qc->err_mask);
1212                ata_scsi_set_sense(dev, cmd, ABORTED_COMMAND, 0, 0);
1213                return;
1214        }
1215
1216        block = ata_tf_read_block(&qc->result_tf, dev);
1217        if (block == U64_MAX)
1218                return;
1219
1220        scsi_set_sense_information(sb, SCSI_SENSE_BUFFERSIZE, block);
1221}
1222
1223static void ata_scsi_sdev_config(struct scsi_device *sdev)
1224{
1225        sdev->use_10_for_rw = 1;
1226        sdev->use_10_for_ms = 1;
1227        sdev->no_write_same = 1;
1228
1229        /* Schedule policy is determined by ->qc_defer() callback and
1230         * it needs to see every deferred qc.  Set dev_blocked to 1 to
1231         * prevent SCSI midlayer from automatically deferring
1232         * requests.
1233         */
1234        sdev->max_device_blocked = 1;
1235}
1236
1237/**
1238 *      atapi_drain_needed - Check whether data transfer may overflow
1239 *      @rq: request to be checked
1240 *
1241 *      ATAPI commands which transfer variable length data to host
1242 *      might overflow due to application error or hardware bug.  This
1243 *      function checks whether overflow should be drained and ignored
1244 *      for @request.
1245 *
1246 *      LOCKING:
1247 *      None.
1248 *
1249 *      RETURNS:
1250 *      1 if ; otherwise, 0.
1251 */
1252static int atapi_drain_needed(struct request *rq)
1253{
1254        if (likely(!blk_rq_is_passthrough(rq)))
1255                return 0;
1256
1257        if (!blk_rq_bytes(rq) || op_is_write(req_op(rq)))
1258                return 0;
1259
1260        return atapi_cmd_type(scsi_req(rq)->cmd[0]) == ATAPI_MISC;
1261}
1262
1263static int ata_scsi_dev_config(struct scsi_device *sdev,
1264                               struct ata_device *dev)
1265{
1266        struct request_queue *q = sdev->request_queue;
1267
1268        if (!ata_id_has_unload(dev->id))
1269                dev->flags |= ATA_DFLAG_NO_UNLOAD;
1270
1271        /* configure max sectors */
1272        blk_queue_max_hw_sectors(q, dev->max_sectors);
1273
1274        if (dev->class == ATA_DEV_ATAPI) {
1275                void *buf;
1276
1277                sdev->sector_size = ATA_SECT_SIZE;
1278
1279                /* set DMA padding */
1280                blk_queue_update_dma_pad(q, ATA_DMA_PAD_SZ - 1);
1281
1282                /* configure draining */
1283                buf = kmalloc(ATAPI_MAX_DRAIN, q->bounce_gfp | GFP_KERNEL);
1284                if (!buf) {
1285                        ata_dev_err(dev, "drain buffer allocation failed\n");
1286                        return -ENOMEM;
1287                }
1288
1289                blk_queue_dma_drain(q, atapi_drain_needed, buf, ATAPI_MAX_DRAIN);
1290        } else {
1291                sdev->sector_size = ata_id_logical_sector_size(dev->id);
1292                sdev->manage_start_stop = 1;
1293        }
1294
1295        /*
1296         * ata_pio_sectors() expects buffer for each sector to not cross
1297         * page boundary.  Enforce it by requiring buffers to be sector
1298         * aligned, which works iff sector_size is not larger than
1299         * PAGE_SIZE.  ATAPI devices also need the alignment as
1300         * IDENTIFY_PACKET is executed as ATA_PROT_PIO.
1301         */
1302        if (sdev->sector_size > PAGE_SIZE)
1303                ata_dev_warn(dev,
1304                        "sector_size=%u > PAGE_SIZE, PIO may malfunction\n",
1305                        sdev->sector_size);
1306
1307        blk_queue_update_dma_alignment(q, sdev->sector_size - 1);
1308
1309        if (dev->flags & ATA_DFLAG_AN)
1310                set_bit(SDEV_EVT_MEDIA_CHANGE, sdev->supported_events);
1311
1312        if (dev->flags & ATA_DFLAG_NCQ) {
1313                int depth;
1314
1315                depth = min(sdev->host->can_queue, ata_id_queue_depth(dev->id));
1316                depth = min(ATA_MAX_QUEUE, depth);
1317                scsi_change_queue_depth(sdev, depth);
1318        }
1319
1320        if (dev->flags & ATA_DFLAG_TRUSTED)
1321                sdev->security_supported = 1;
1322
1323        dev->sdev = sdev;
1324        return 0;
1325}
1326
1327/**
1328 *      ata_scsi_slave_config - Set SCSI device attributes
1329 *      @sdev: SCSI device to examine
1330 *
1331 *      This is called before we actually start reading
1332 *      and writing to the device, to configure certain
1333 *      SCSI mid-layer behaviors.
1334 *
1335 *      LOCKING:
1336 *      Defined by SCSI layer.  We don't really care.
1337 */
1338
1339int ata_scsi_slave_config(struct scsi_device *sdev)
1340{
1341        struct ata_port *ap = ata_shost_to_port(sdev->host);
1342        struct ata_device *dev = __ata_scsi_find_dev(ap, sdev);
1343        int rc = 0;
1344
1345        ata_scsi_sdev_config(sdev);
1346
1347        if (dev)
1348                rc = ata_scsi_dev_config(sdev, dev);
1349
1350        return rc;
1351}
1352
1353/**
1354 *      ata_scsi_slave_destroy - SCSI device is about to be destroyed
1355 *      @sdev: SCSI device to be destroyed
1356 *
1357 *      @sdev is about to be destroyed for hot/warm unplugging.  If
1358 *      this unplugging was initiated by libata as indicated by NULL
1359 *      dev->sdev, this function doesn't have to do anything.
1360 *      Otherwise, SCSI layer initiated warm-unplug is in progress.
1361 *      Clear dev->sdev, schedule the device for ATA detach and invoke
1362 *      EH.
1363 *
1364 *      LOCKING:
1365 *      Defined by SCSI layer.  We don't really care.
1366 */
1367void ata_scsi_slave_destroy(struct scsi_device *sdev)
1368{
1369        struct ata_port *ap = ata_shost_to_port(sdev->host);
1370        struct request_queue *q = sdev->request_queue;
1371        unsigned long flags;
1372        struct ata_device *dev;
1373
1374        if (!ap->ops->error_handler)
1375                return;
1376
1377        spin_lock_irqsave(ap->lock, flags);
1378        dev = __ata_scsi_find_dev(ap, sdev);
1379        if (dev && dev->sdev) {
1380                /* SCSI device already in CANCEL state, no need to offline it */
1381                dev->sdev = NULL;
1382                dev->flags |= ATA_DFLAG_DETACH;
1383                ata_port_schedule_eh(ap);
1384        }
1385        spin_unlock_irqrestore(ap->lock, flags);
1386
1387        kfree(q->dma_drain_buffer);
1388        q->dma_drain_buffer = NULL;
1389        q->dma_drain_size = 0;
1390}
1391
1392/**
1393 *      __ata_change_queue_depth - helper for ata_scsi_change_queue_depth
1394 *      @ap: ATA port to which the device change the queue depth
1395 *      @sdev: SCSI device to configure queue depth for
1396 *      @queue_depth: new queue depth
1397 *
1398 *      libsas and libata have different approaches for associating a sdev to
1399 *      its ata_port.
1400 *
1401 */
1402int __ata_change_queue_depth(struct ata_port *ap, struct scsi_device *sdev,
1403                             int queue_depth)
1404{
1405        struct ata_device *dev;
1406        unsigned long flags;
1407
1408        if (queue_depth < 1 || queue_depth == sdev->queue_depth)
1409                return sdev->queue_depth;
1410
1411        dev = ata_scsi_find_dev(ap, sdev);
1412        if (!dev || !ata_dev_enabled(dev))
1413                return sdev->queue_depth;
1414
1415        /* NCQ enabled? */
1416        spin_lock_irqsave(ap->lock, flags);
1417        dev->flags &= ~ATA_DFLAG_NCQ_OFF;
1418        if (queue_depth == 1 || !ata_ncq_enabled(dev)) {
1419                dev->flags |= ATA_DFLAG_NCQ_OFF;
1420                queue_depth = 1;
1421        }
1422        spin_unlock_irqrestore(ap->lock, flags);
1423
1424        /* limit and apply queue depth */
1425        queue_depth = min(queue_depth, sdev->host->can_queue);
1426        queue_depth = min(queue_depth, ata_id_queue_depth(dev->id));
1427        queue_depth = min(queue_depth, ATA_MAX_QUEUE);
1428
1429        if (sdev->queue_depth == queue_depth)
1430                return -EINVAL;
1431
1432        return scsi_change_queue_depth(sdev, queue_depth);
1433}
1434
1435/**
1436 *      ata_scsi_change_queue_depth - SCSI callback for queue depth config
1437 *      @sdev: SCSI device to configure queue depth for
1438 *      @queue_depth: new queue depth
1439 *
1440 *      This is libata standard hostt->change_queue_depth callback.
1441 *      SCSI will call into this callback when user tries to set queue
1442 *      depth via sysfs.
1443 *
1444 *      LOCKING:
1445 *      SCSI layer (we don't care)
1446 *
1447 *      RETURNS:
1448 *      Newly configured queue depth.
1449 */
1450int ata_scsi_change_queue_depth(struct scsi_device *sdev, int queue_depth)
1451{
1452        struct ata_port *ap = ata_shost_to_port(sdev->host);
1453
1454        return __ata_change_queue_depth(ap, sdev, queue_depth);
1455}
1456
1457/**
1458 *      ata_scsi_start_stop_xlat - Translate SCSI START STOP UNIT command
1459 *      @qc: Storage for translated ATA taskfile
1460 *
1461 *      Sets up an ATA taskfile to issue STANDBY (to stop) or READ VERIFY
1462 *      (to start). Perhaps these commands should be preceded by
1463 *      CHECK POWER MODE to see what power mode the device is already in.
1464 *      [See SAT revision 5 at www.t10.org]
1465 *
1466 *      LOCKING:
1467 *      spin_lock_irqsave(host lock)
1468 *
1469 *      RETURNS:
1470 *      Zero on success, non-zero on error.
1471 */
1472static unsigned int ata_scsi_start_stop_xlat(struct ata_queued_cmd *qc)
1473{
1474        struct scsi_cmnd *scmd = qc->scsicmd;
1475        struct ata_taskfile *tf = &qc->tf;
1476        const u8 *cdb = scmd->cmnd;
1477        u16 fp;
1478        u8 bp = 0xff;
1479
1480        if (scmd->cmd_len < 5) {
1481                fp = 4;
1482                goto invalid_fld;
1483        }
1484
1485        tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1486        tf->protocol = ATA_PROT_NODATA;
1487        if (cdb[1] & 0x1) {
1488                ;       /* ignore IMMED bit, violates sat-r05 */
1489        }
1490        if (cdb[4] & 0x2) {
1491                fp = 4;
1492                bp = 1;
1493                goto invalid_fld;       /* LOEJ bit set not supported */
1494        }
1495        if (((cdb[4] >> 4) & 0xf) != 0) {
1496                fp = 4;
1497                bp = 3;
1498                goto invalid_fld;       /* power conditions not supported */
1499        }
1500
1501        if (cdb[4] & 0x1) {
1502                tf->nsect = 1;  /* 1 sector, lba=0 */
1503
1504                if (qc->dev->flags & ATA_DFLAG_LBA) {
1505                        tf->flags |= ATA_TFLAG_LBA;
1506
1507                        tf->lbah = 0x0;
1508                        tf->lbam = 0x0;
1509                        tf->lbal = 0x0;
1510                        tf->device |= ATA_LBA;
1511                } else {
1512                        /* CHS */
1513                        tf->lbal = 0x1; /* sect */
1514                        tf->lbam = 0x0; /* cyl low */
1515                        tf->lbah = 0x0; /* cyl high */
1516                }
1517
1518                tf->command = ATA_CMD_VERIFY;   /* READ VERIFY */
1519        } else {
1520                /* Some odd clown BIOSen issue spindown on power off (ACPI S4
1521                 * or S5) causing some drives to spin up and down again.
1522                 */
1523                if ((qc->ap->flags & ATA_FLAG_NO_POWEROFF_SPINDOWN) &&
1524                    system_state == SYSTEM_POWER_OFF)
1525                        goto skip;
1526
1527                if ((qc->ap->flags & ATA_FLAG_NO_HIBERNATE_SPINDOWN) &&
1528                     system_entering_hibernation())
1529                        goto skip;
1530
1531                /* Issue ATA STANDBY IMMEDIATE command */
1532                tf->command = ATA_CMD_STANDBYNOW1;
1533        }
1534
1535        /*
1536         * Standby and Idle condition timers could be implemented but that
1537         * would require libata to implement the Power condition mode page
1538         * and allow the user to change it. Changing mode pages requires
1539         * MODE SELECT to be implemented.
1540         */
1541
1542        return 0;
1543
1544 invalid_fld:
1545        ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
1546        return 1;
1547 skip:
1548        scmd->result = SAM_STAT_GOOD;
1549        return 1;
1550}
1551
1552
1553/**
1554 *      ata_scsi_flush_xlat - Translate SCSI SYNCHRONIZE CACHE command
1555 *      @qc: Storage for translated ATA taskfile
1556 *
1557 *      Sets up an ATA taskfile to issue FLUSH CACHE or
1558 *      FLUSH CACHE EXT.
1559 *
1560 *      LOCKING:
1561 *      spin_lock_irqsave(host lock)
1562 *
1563 *      RETURNS:
1564 *      Zero on success, non-zero on error.
1565 */
1566static unsigned int ata_scsi_flush_xlat(struct ata_queued_cmd *qc)
1567{
1568        struct ata_taskfile *tf = &qc->tf;
1569
1570        tf->flags |= ATA_TFLAG_DEVICE;
1571        tf->protocol = ATA_PROT_NODATA;
1572
1573        if (qc->dev->flags & ATA_DFLAG_FLUSH_EXT)
1574                tf->command = ATA_CMD_FLUSH_EXT;
1575        else
1576                tf->command = ATA_CMD_FLUSH;
1577
1578        /* flush is critical for IO integrity, consider it an IO command */
1579        qc->flags |= ATA_QCFLAG_IO;
1580
1581        return 0;
1582}
1583
1584/**
1585 *      scsi_6_lba_len - Get LBA and transfer length
1586 *      @cdb: SCSI command to translate
1587 *
1588 *      Calculate LBA and transfer length for 6-byte commands.
1589 *
1590 *      RETURNS:
1591 *      @plba: the LBA
1592 *      @plen: the transfer length
1593 */
1594static void scsi_6_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
1595{
1596        u64 lba = 0;
1597        u32 len;
1598
1599        VPRINTK("six-byte command\n");
1600
1601        lba |= ((u64)(cdb[1] & 0x1f)) << 16;
1602        lba |= ((u64)cdb[2]) << 8;
1603        lba |= ((u64)cdb[3]);
1604
1605        len = cdb[4];
1606
1607        *plba = lba;
1608        *plen = len;
1609}
1610
1611/**
1612 *      scsi_10_lba_len - Get LBA and transfer length
1613 *      @cdb: SCSI command to translate
1614 *
1615 *      Calculate LBA and transfer length for 10-byte commands.
1616 *
1617 *      RETURNS:
1618 *      @plba: the LBA
1619 *      @plen: the transfer length
1620 */
1621static void scsi_10_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
1622{
1623        u64 lba = 0;
1624        u32 len = 0;
1625
1626        VPRINTK("ten-byte command\n");
1627
1628        lba |= ((u64)cdb[2]) << 24;
1629        lba |= ((u64)cdb[3]) << 16;
1630        lba |= ((u64)cdb[4]) << 8;
1631        lba |= ((u64)cdb[5]);
1632
1633        len |= ((u32)cdb[7]) << 8;
1634        len |= ((u32)cdb[8]);
1635
1636        *plba = lba;
1637        *plen = len;
1638}
1639
1640/**
1641 *      scsi_16_lba_len - Get LBA and transfer length
1642 *      @cdb: SCSI command to translate
1643 *
1644 *      Calculate LBA and transfer length for 16-byte commands.
1645 *
1646 *      RETURNS:
1647 *      @plba: the LBA
1648 *      @plen: the transfer length
1649 */
1650static void scsi_16_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
1651{
1652        u64 lba = 0;
1653        u32 len = 0;
1654
1655        VPRINTK("sixteen-byte command\n");
1656
1657        lba |= ((u64)cdb[2]) << 56;
1658        lba |= ((u64)cdb[3]) << 48;
1659        lba |= ((u64)cdb[4]) << 40;
1660        lba |= ((u64)cdb[5]) << 32;
1661        lba |= ((u64)cdb[6]) << 24;
1662        lba |= ((u64)cdb[7]) << 16;
1663        lba |= ((u64)cdb[8]) << 8;
1664        lba |= ((u64)cdb[9]);
1665
1666        len |= ((u32)cdb[10]) << 24;
1667        len |= ((u32)cdb[11]) << 16;
1668        len |= ((u32)cdb[12]) << 8;
1669        len |= ((u32)cdb[13]);
1670
1671        *plba = lba;
1672        *plen = len;
1673}
1674
1675/**
1676 *      ata_scsi_verify_xlat - Translate SCSI VERIFY command into an ATA one
1677 *      @qc: Storage for translated ATA taskfile
1678 *
1679 *      Converts SCSI VERIFY command to an ATA READ VERIFY command.
1680 *
1681 *      LOCKING:
1682 *      spin_lock_irqsave(host lock)
1683 *
1684 *      RETURNS:
1685 *      Zero on success, non-zero on error.
1686 */
1687static unsigned int ata_scsi_verify_xlat(struct ata_queued_cmd *qc)
1688{
1689        struct scsi_cmnd *scmd = qc->scsicmd;
1690        struct ata_taskfile *tf = &qc->tf;
1691        struct ata_device *dev = qc->dev;
1692        u64 dev_sectors = qc->dev->n_sectors;
1693        const u8 *cdb = scmd->cmnd;
1694        u64 block;
1695        u32 n_block;
1696        u16 fp;
1697
1698        tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1699        tf->protocol = ATA_PROT_NODATA;
1700
1701        if (cdb[0] == VERIFY) {
1702                if (scmd->cmd_len < 10) {
1703                        fp = 9;
1704                        goto invalid_fld;
1705                }
1706                scsi_10_lba_len(cdb, &block, &n_block);
1707        } else if (cdb[0] == VERIFY_16) {
1708                if (scmd->cmd_len < 16) {
1709                        fp = 15;
1710                        goto invalid_fld;
1711                }
1712                scsi_16_lba_len(cdb, &block, &n_block);
1713        } else {
1714                fp = 0;
1715                goto invalid_fld;
1716        }
1717
1718        if (!n_block)
1719                goto nothing_to_do;
1720        if (block >= dev_sectors)
1721                goto out_of_range;
1722        if ((block + n_block) > dev_sectors)
1723                goto out_of_range;
1724
1725        if (dev->flags & ATA_DFLAG_LBA) {
1726                tf->flags |= ATA_TFLAG_LBA;
1727
1728                if (lba_28_ok(block, n_block)) {
1729                        /* use LBA28 */
1730                        tf->command = ATA_CMD_VERIFY;
1731                        tf->device |= (block >> 24) & 0xf;
1732                } else if (lba_48_ok(block, n_block)) {
1733                        if (!(dev->flags & ATA_DFLAG_LBA48))
1734                                goto out_of_range;
1735
1736                        /* use LBA48 */
1737                        tf->flags |= ATA_TFLAG_LBA48;
1738                        tf->command = ATA_CMD_VERIFY_EXT;
1739
1740                        tf->hob_nsect = (n_block >> 8) & 0xff;
1741
1742                        tf->hob_lbah = (block >> 40) & 0xff;
1743                        tf->hob_lbam = (block >> 32) & 0xff;
1744                        tf->hob_lbal = (block >> 24) & 0xff;
1745                } else
1746                        /* request too large even for LBA48 */
1747                        goto out_of_range;
1748
1749                tf->nsect = n_block & 0xff;
1750
1751                tf->lbah = (block >> 16) & 0xff;
1752                tf->lbam = (block >> 8) & 0xff;
1753                tf->lbal = block & 0xff;
1754
1755                tf->device |= ATA_LBA;
1756        } else {
1757                /* CHS */
1758                u32 sect, head, cyl, track;
1759
1760                if (!lba_28_ok(block, n_block))
1761                        goto out_of_range;
1762
1763                /* Convert LBA to CHS */
1764                track = (u32)block / dev->sectors;
1765                cyl   = track / dev->heads;
1766                head  = track % dev->heads;
1767                sect  = (u32)block % dev->sectors + 1;
1768
1769                DPRINTK("block %u track %u cyl %u head %u sect %u\n",
1770                        (u32)block, track, cyl, head, sect);
1771
1772                /* Check whether the converted CHS can fit.
1773                   Cylinder: 0-65535
1774                   Head: 0-15
1775                   Sector: 1-255*/
1776                if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
1777                        goto out_of_range;
1778
1779                tf->command = ATA_CMD_VERIFY;
1780                tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
1781                tf->lbal = sect;
1782                tf->lbam = cyl;
1783                tf->lbah = cyl >> 8;
1784                tf->device |= head;
1785        }
1786
1787        return 0;
1788
1789invalid_fld:
1790        ata_scsi_set_invalid_field(qc->dev, scmd, fp, 0xff);
1791        return 1;
1792
1793out_of_range:
1794        ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x21, 0x0);
1795        /* "Logical Block Address out of range" */
1796        return 1;
1797
1798nothing_to_do:
1799        scmd->result = SAM_STAT_GOOD;
1800        return 1;
1801}
1802
1803/**
1804 *      ata_scsi_rw_xlat - Translate SCSI r/w command into an ATA one
1805 *      @qc: Storage for translated ATA taskfile
1806 *
1807 *      Converts any of six SCSI read/write commands into the
1808 *      ATA counterpart, including starting sector (LBA),
1809 *      sector count, and taking into account the device's LBA48
1810 *      support.
1811 *
1812 *      Commands %READ_6, %READ_10, %READ_16, %WRITE_6, %WRITE_10, and
1813 *      %WRITE_16 are currently supported.
1814 *
1815 *      LOCKING:
1816 *      spin_lock_irqsave(host lock)
1817 *
1818 *      RETURNS:
1819 *      Zero on success, non-zero on error.
1820 */
1821static unsigned int ata_scsi_rw_xlat(struct ata_queued_cmd *qc)
1822{
1823        struct scsi_cmnd *scmd = qc->scsicmd;
1824        const u8 *cdb = scmd->cmnd;
1825        struct request *rq = scmd->request;
1826        int class = IOPRIO_PRIO_CLASS(req_get_ioprio(rq));
1827        unsigned int tf_flags = 0;
1828        u64 block;
1829        u32 n_block;
1830        int rc;
1831        u16 fp = 0;
1832
1833        if (cdb[0] == WRITE_10 || cdb[0] == WRITE_6 || cdb[0] == WRITE_16)
1834                tf_flags |= ATA_TFLAG_WRITE;
1835
1836        /* Calculate the SCSI LBA, transfer length and FUA. */
1837        switch (cdb[0]) {
1838        case READ_10:
1839        case WRITE_10:
1840                if (unlikely(scmd->cmd_len < 10)) {
1841                        fp = 9;
1842                        goto invalid_fld;
1843                }
1844                scsi_10_lba_len(cdb, &block, &n_block);
1845                if (cdb[1] & (1 << 3))
1846                        tf_flags |= ATA_TFLAG_FUA;
1847                break;
1848        case READ_6:
1849        case WRITE_6:
1850                if (unlikely(scmd->cmd_len < 6)) {
1851                        fp = 5;
1852                        goto invalid_fld;
1853                }
1854                scsi_6_lba_len(cdb, &block, &n_block);
1855
1856                /* for 6-byte r/w commands, transfer length 0
1857                 * means 256 blocks of data, not 0 block.
1858                 */
1859                if (!n_block)
1860                        n_block = 256;
1861                break;
1862        case READ_16:
1863        case WRITE_16:
1864                if (unlikely(scmd->cmd_len < 16)) {
1865                        fp = 15;
1866                        goto invalid_fld;
1867                }
1868                scsi_16_lba_len(cdb, &block, &n_block);
1869                if (cdb[1] & (1 << 3))
1870                        tf_flags |= ATA_TFLAG_FUA;
1871                break;
1872        default:
1873                DPRINTK("no-byte command\n");
1874                fp = 0;
1875                goto invalid_fld;
1876        }
1877
1878        /* Check and compose ATA command */
1879        if (!n_block)
1880                /* For 10-byte and 16-byte SCSI R/W commands, transfer
1881                 * length 0 means transfer 0 block of data.
1882                 * However, for ATA R/W commands, sector count 0 means
1883                 * 256 or 65536 sectors, not 0 sectors as in SCSI.
1884                 *
1885                 * WARNING: one or two older ATA drives treat 0 as 0...
1886                 */
1887                goto nothing_to_do;
1888
1889        qc->flags |= ATA_QCFLAG_IO;
1890        qc->nbytes = n_block * scmd->device->sector_size;
1891
1892        rc = ata_build_rw_tf(&qc->tf, qc->dev, block, n_block, tf_flags,
1893                             qc->hw_tag, class);
1894
1895        if (likely(rc == 0))
1896                return 0;
1897
1898        if (rc == -ERANGE)
1899                goto out_of_range;
1900        /* treat all other errors as -EINVAL, fall through */
1901invalid_fld:
1902        ata_scsi_set_invalid_field(qc->dev, scmd, fp, 0xff);
1903        return 1;
1904
1905out_of_range:
1906        ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x21, 0x0);
1907        /* "Logical Block Address out of range" */
1908        return 1;
1909
1910nothing_to_do:
1911        scmd->result = SAM_STAT_GOOD;
1912        return 1;
1913}
1914
1915static void ata_qc_done(struct ata_queued_cmd *qc)
1916{
1917        struct scsi_cmnd *cmd = qc->scsicmd;
1918        void (*done)(struct scsi_cmnd *) = qc->scsidone;
1919
1920        ata_qc_free(qc);
1921        done(cmd);
1922}
1923
1924static void ata_scsi_qc_complete(struct ata_queued_cmd *qc)
1925{
1926        struct ata_port *ap = qc->ap;
1927        struct scsi_cmnd *cmd = qc->scsicmd;
1928        u8 *cdb = cmd->cmnd;
1929        int need_sense = (qc->err_mask != 0);
1930
1931        /* For ATA pass thru (SAT) commands, generate a sense block if
1932         * user mandated it or if there's an error.  Note that if we
1933         * generate because the user forced us to [CK_COND =1], a check
1934         * condition is generated and the ATA register values are returned
1935         * whether the command completed successfully or not. If there
1936         * was no error, we use the following sense data:
1937         * sk = RECOVERED ERROR
1938         * asc,ascq = ATA PASS-THROUGH INFORMATION AVAILABLE
1939         */
1940        if (((cdb[0] == ATA_16) || (cdb[0] == ATA_12)) &&
1941            ((cdb[2] & 0x20) || need_sense))
1942                ata_gen_passthru_sense(qc);
1943        else if (qc->flags & ATA_QCFLAG_SENSE_VALID)
1944                cmd->result = SAM_STAT_CHECK_CONDITION;
1945        else if (need_sense)
1946                ata_gen_ata_sense(qc);
1947        else
1948                cmd->result = SAM_STAT_GOOD;
1949
1950        if (need_sense && !ap->ops->error_handler)
1951                ata_dump_status(ap->print_id, &qc->result_tf);
1952
1953        ata_qc_done(qc);
1954}
1955
1956/**
1957 *      ata_scsi_translate - Translate then issue SCSI command to ATA device
1958 *      @dev: ATA device to which the command is addressed
1959 *      @cmd: SCSI command to execute
1960 *      @xlat_func: Actor which translates @cmd to an ATA taskfile
1961 *
1962 *      Our ->queuecommand() function has decided that the SCSI
1963 *      command issued can be directly translated into an ATA
1964 *      command, rather than handled internally.
1965 *
1966 *      This function sets up an ata_queued_cmd structure for the
1967 *      SCSI command, and sends that ata_queued_cmd to the hardware.
1968 *
1969 *      The xlat_func argument (actor) returns 0 if ready to execute
1970 *      ATA command, else 1 to finish translation. If 1 is returned
1971 *      then cmd->result (and possibly cmd->sense_buffer) are assumed
1972 *      to be set reflecting an error condition or clean (early)
1973 *      termination.
1974 *
1975 *      LOCKING:
1976 *      spin_lock_irqsave(host lock)
1977 *
1978 *      RETURNS:
1979 *      0 on success, SCSI_ML_QUEUE_DEVICE_BUSY if the command
1980 *      needs to be deferred.
1981 */
1982static int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd,
1983                              ata_xlat_func_t xlat_func)
1984{
1985        struct ata_port *ap = dev->link->ap;
1986        struct ata_queued_cmd *qc;
1987        int rc;
1988
1989        VPRINTK("ENTER\n");
1990
1991        qc = ata_scsi_qc_new(dev, cmd);
1992        if (!qc)
1993                goto err_mem;
1994
1995        /* data is present; dma-map it */
1996        if (cmd->sc_data_direction == DMA_FROM_DEVICE ||
1997            cmd->sc_data_direction == DMA_TO_DEVICE) {
1998                if (unlikely(scsi_bufflen(cmd) < 1)) {
1999                        ata_dev_warn(dev, "WARNING: zero len r/w req\n");
2000                        goto err_did;
2001                }
2002
2003                ata_sg_init(qc, scsi_sglist(cmd), scsi_sg_count(cmd));
2004
2005                qc->dma_dir = cmd->sc_data_direction;
2006        }
2007
2008        qc->complete_fn = ata_scsi_qc_complete;
2009
2010        if (xlat_func(qc))
2011                goto early_finish;
2012
2013        if (ap->ops->qc_defer) {
2014                if ((rc = ap->ops->qc_defer(qc)))
2015                        goto defer;
2016        }
2017
2018        /* select device, send command to hardware */
2019        ata_qc_issue(qc);
2020
2021        VPRINTK("EXIT\n");
2022        return 0;
2023
2024early_finish:
2025        ata_qc_free(qc);
2026        cmd->scsi_done(cmd);
2027        DPRINTK("EXIT - early finish (good or error)\n");
2028        return 0;
2029
2030err_did:
2031        ata_qc_free(qc);
2032        cmd->result = (DID_ERROR << 16);
2033        cmd->scsi_done(cmd);
2034err_mem:
2035        DPRINTK("EXIT - internal\n");
2036        return 0;
2037
2038defer:
2039        ata_qc_free(qc);
2040        DPRINTK("EXIT - defer\n");
2041        if (rc == ATA_DEFER_LINK)
2042                return SCSI_MLQUEUE_DEVICE_BUSY;
2043        else
2044                return SCSI_MLQUEUE_HOST_BUSY;
2045}
2046
2047struct ata_scsi_args {
2048        struct ata_device       *dev;
2049        u16                     *id;
2050        struct scsi_cmnd        *cmd;
2051};
2052
2053/**
2054 *      ata_scsi_rbuf_get - Map response buffer.
2055 *      @cmd: SCSI command containing buffer to be mapped.
2056 *      @flags: unsigned long variable to store irq enable status
2057 *      @copy_in: copy in from user buffer
2058 *
2059 *      Prepare buffer for simulated SCSI commands.
2060 *
2061 *      LOCKING:
2062 *      spin_lock_irqsave(ata_scsi_rbuf_lock) on success
2063 *
2064 *      RETURNS:
2065 *      Pointer to response buffer.
2066 */
2067static void *ata_scsi_rbuf_get(struct scsi_cmnd *cmd, bool copy_in,
2068                               unsigned long *flags)
2069{
2070        spin_lock_irqsave(&ata_scsi_rbuf_lock, *flags);
2071
2072        memset(ata_scsi_rbuf, 0, ATA_SCSI_RBUF_SIZE);
2073        if (copy_in)
2074                sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
2075                                  ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
2076        return ata_scsi_rbuf;
2077}
2078
2079/**
2080 *      ata_scsi_rbuf_put - Unmap response buffer.
2081 *      @cmd: SCSI command containing buffer to be unmapped.
2082 *      @copy_out: copy out result
2083 *      @flags: @flags passed to ata_scsi_rbuf_get()
2084 *
2085 *      Returns rbuf buffer.  The result is copied to @cmd's buffer if
2086 *      @copy_back is true.
2087 *
2088 *      LOCKING:
2089 *      Unlocks ata_scsi_rbuf_lock.
2090 */
2091static inline void ata_scsi_rbuf_put(struct scsi_cmnd *cmd, bool copy_out,
2092                                     unsigned long *flags)
2093{
2094        if (copy_out)
2095                sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
2096                                    ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
2097        spin_unlock_irqrestore(&ata_scsi_rbuf_lock, *flags);
2098}
2099
2100/**
2101 *      ata_scsi_rbuf_fill - wrapper for SCSI command simulators
2102 *      @args: device IDENTIFY data / SCSI command of interest.
2103 *      @actor: Callback hook for desired SCSI command simulator
2104 *
2105 *      Takes care of the hard work of simulating a SCSI command...
2106 *      Mapping the response buffer, calling the command's handler,
2107 *      and handling the handler's return value.  This return value
2108 *      indicates whether the handler wishes the SCSI command to be
2109 *      completed successfully (0), or not (in which case cmd->result
2110 *      and sense buffer are assumed to be set).
2111 *
2112 *      LOCKING:
2113 *      spin_lock_irqsave(host lock)
2114 */
2115static void ata_scsi_rbuf_fill(struct ata_scsi_args *args,
2116                unsigned int (*actor)(struct ata_scsi_args *args, u8 *rbuf))
2117{
2118        u8 *rbuf;
2119        unsigned int rc;
2120        struct scsi_cmnd *cmd = args->cmd;
2121        unsigned long flags;
2122
2123        rbuf = ata_scsi_rbuf_get(cmd, false, &flags);
2124        rc = actor(args, rbuf);
2125        ata_scsi_rbuf_put(cmd, rc == 0, &flags);
2126
2127        if (rc == 0)
2128                cmd->result = SAM_STAT_GOOD;
2129}
2130
2131/**
2132 *      ata_scsiop_inq_std - Simulate INQUIRY command
2133 *      @args: device IDENTIFY data / SCSI command of interest.
2134 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2135 *
2136 *      Returns standard device identification data associated
2137 *      with non-VPD INQUIRY command output.
2138 *
2139 *      LOCKING:
2140 *      spin_lock_irqsave(host lock)
2141 */
2142static unsigned int ata_scsiop_inq_std(struct ata_scsi_args *args, u8 *rbuf)
2143{
2144        static const u8 versions[] = {
2145                0x00,
2146                0x60,   /* SAM-3 (no version claimed) */
2147
2148                0x03,
2149                0x20,   /* SBC-2 (no version claimed) */
2150
2151                0x03,
2152                0x00    /* SPC-3 (no version claimed) */
2153        };
2154        static const u8 versions_zbc[] = {
2155                0x00,
2156                0xA0,   /* SAM-5 (no version claimed) */
2157
2158                0x06,
2159                0x00,   /* SBC-4 (no version claimed) */
2160
2161                0x05,
2162                0xC0,   /* SPC-5 (no version claimed) */
2163
2164                0x60,
2165                0x24,   /* ZBC r05 */
2166        };
2167
2168        u8 hdr[] = {
2169                TYPE_DISK,
2170                0,
2171                0x5,    /* claim SPC-3 version compatibility */
2172                2,
2173                95 - 4,
2174                0,
2175                0,
2176                2
2177        };
2178
2179        VPRINTK("ENTER\n");
2180
2181        /* set scsi removable (RMB) bit per ata bit, or if the
2182         * AHCI port says it's external (Hotplug-capable, eSATA).
2183         */
2184        if (ata_id_removable(args->id) ||
2185            (args->dev->link->ap->pflags & ATA_PFLAG_EXTERNAL))
2186                hdr[1] |= (1 << 7);
2187
2188        if (args->dev->class == ATA_DEV_ZAC) {
2189                hdr[0] = TYPE_ZBC;
2190                hdr[2] = 0x7; /* claim SPC-5 version compatibility */
2191        }
2192
2193        memcpy(rbuf, hdr, sizeof(hdr));
2194        memcpy(&rbuf[8], "ATA     ", 8);
2195        ata_id_string(args->id, &rbuf[16], ATA_ID_PROD, 16);
2196
2197        /* From SAT, use last 2 words from fw rev unless they are spaces */
2198        ata_id_string(args->id, &rbuf[32], ATA_ID_FW_REV + 2, 4);
2199        if (strncmp(&rbuf[32], "    ", 4) == 0)
2200                ata_id_string(args->id, &rbuf[32], ATA_ID_FW_REV, 4);
2201
2202        if (rbuf[32] == 0 || rbuf[32] == ' ')
2203                memcpy(&rbuf[32], "n/a ", 4);
2204
2205        if (ata_id_zoned_cap(args->id) || args->dev->class == ATA_DEV_ZAC)
2206                memcpy(rbuf + 58, versions_zbc, sizeof(versions_zbc));
2207        else
2208                memcpy(rbuf + 58, versions, sizeof(versions));
2209
2210        return 0;
2211}
2212
2213/**
2214 *      ata_scsiop_inq_00 - Simulate INQUIRY VPD page 0, list of pages
2215 *      @args: device IDENTIFY data / SCSI command of interest.
2216 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2217 *
2218 *      Returns list of inquiry VPD pages available.
2219 *
2220 *      LOCKING:
2221 *      spin_lock_irqsave(host lock)
2222 */
2223static unsigned int ata_scsiop_inq_00(struct ata_scsi_args *args, u8 *rbuf)
2224{
2225        int num_pages;
2226        static const u8 pages[] = {
2227                0x00,   /* page 0x00, this page */
2228                0x80,   /* page 0x80, unit serial no page */
2229                0x83,   /* page 0x83, device ident page */
2230                0x89,   /* page 0x89, ata info page */
2231                0xb0,   /* page 0xb0, block limits page */
2232                0xb1,   /* page 0xb1, block device characteristics page */
2233                0xb2,   /* page 0xb2, thin provisioning page */
2234                0xb6,   /* page 0xb6, zoned block device characteristics */
2235        };
2236
2237        num_pages = sizeof(pages);
2238        if (!(args->dev->flags & ATA_DFLAG_ZAC))
2239                num_pages--;
2240        rbuf[3] = num_pages;    /* number of supported VPD pages */
2241        memcpy(rbuf + 4, pages, num_pages);
2242        return 0;
2243}
2244
2245/**
2246 *      ata_scsiop_inq_80 - Simulate INQUIRY VPD page 80, device serial number
2247 *      @args: device IDENTIFY data / SCSI command of interest.
2248 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2249 *
2250 *      Returns ATA device serial number.
2251 *
2252 *      LOCKING:
2253 *      spin_lock_irqsave(host lock)
2254 */
2255static unsigned int ata_scsiop_inq_80(struct ata_scsi_args *args, u8 *rbuf)
2256{
2257        static const u8 hdr[] = {
2258                0,
2259                0x80,                   /* this page code */
2260                0,
2261                ATA_ID_SERNO_LEN,       /* page len */
2262        };
2263
2264        memcpy(rbuf, hdr, sizeof(hdr));
2265        ata_id_string(args->id, (unsigned char *) &rbuf[4],
2266                      ATA_ID_SERNO, ATA_ID_SERNO_LEN);
2267        return 0;
2268}
2269
2270/**
2271 *      ata_scsiop_inq_83 - Simulate INQUIRY VPD page 83, device identity
2272 *      @args: device IDENTIFY data / SCSI command of interest.
2273 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2274 *
2275 *      Yields two logical unit device identification designators:
2276 *       - vendor specific ASCII containing the ATA serial number
2277 *       - SAT defined "t10 vendor id based" containing ASCII vendor
2278 *         name ("ATA     "), model and serial numbers.
2279 *
2280 *      LOCKING:
2281 *      spin_lock_irqsave(host lock)
2282 */
2283static unsigned int ata_scsiop_inq_83(struct ata_scsi_args *args, u8 *rbuf)
2284{
2285        const int sat_model_serial_desc_len = 68;
2286        int num;
2287
2288        rbuf[1] = 0x83;                 /* this page code */
2289        num = 4;
2290
2291        /* piv=0, assoc=lu, code_set=ACSII, designator=vendor */
2292        rbuf[num + 0] = 2;
2293        rbuf[num + 3] = ATA_ID_SERNO_LEN;
2294        num += 4;
2295        ata_id_string(args->id, (unsigned char *) rbuf + num,
2296                      ATA_ID_SERNO, ATA_ID_SERNO_LEN);
2297        num += ATA_ID_SERNO_LEN;
2298
2299        /* SAT defined lu model and serial numbers descriptor */
2300        /* piv=0, assoc=lu, code_set=ACSII, designator=t10 vendor id */
2301        rbuf[num + 0] = 2;
2302        rbuf[num + 1] = 1;
2303        rbuf[num + 3] = sat_model_serial_desc_len;
2304        num += 4;
2305        memcpy(rbuf + num, "ATA     ", 8);
2306        num += 8;
2307        ata_id_string(args->id, (unsigned char *) rbuf + num, ATA_ID_PROD,
2308                      ATA_ID_PROD_LEN);
2309        num += ATA_ID_PROD_LEN;
2310        ata_id_string(args->id, (unsigned char *) rbuf + num, ATA_ID_SERNO,
2311                      ATA_ID_SERNO_LEN);
2312        num += ATA_ID_SERNO_LEN;
2313
2314        if (ata_id_has_wwn(args->id)) {
2315                /* SAT defined lu world wide name */
2316                /* piv=0, assoc=lu, code_set=binary, designator=NAA */
2317                rbuf[num + 0] = 1;
2318                rbuf[num + 1] = 3;
2319                rbuf[num + 3] = ATA_ID_WWN_LEN;
2320                num += 4;
2321                ata_id_string(args->id, (unsigned char *) rbuf + num,
2322                              ATA_ID_WWN, ATA_ID_WWN_LEN);
2323                num += ATA_ID_WWN_LEN;
2324        }
2325        rbuf[3] = num - 4;    /* page len (assume less than 256 bytes) */
2326        return 0;
2327}
2328
2329/**
2330 *      ata_scsiop_inq_89 - Simulate INQUIRY VPD page 89, ATA info
2331 *      @args: device IDENTIFY data / SCSI command of interest.
2332 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2333 *
2334 *      Yields SAT-specified ATA VPD page.
2335 *
2336 *      LOCKING:
2337 *      spin_lock_irqsave(host lock)
2338 */
2339static unsigned int ata_scsiop_inq_89(struct ata_scsi_args *args, u8 *rbuf)
2340{
2341        struct ata_taskfile tf;
2342
2343        memset(&tf, 0, sizeof(tf));
2344
2345        rbuf[1] = 0x89;                 /* our page code */
2346        rbuf[2] = (0x238 >> 8);         /* page size fixed at 238h */
2347        rbuf[3] = (0x238 & 0xff);
2348
2349        memcpy(&rbuf[8], "linux   ", 8);
2350        memcpy(&rbuf[16], "libata          ", 16);
2351        memcpy(&rbuf[32], DRV_VERSION, 4);
2352
2353        /* we don't store the ATA device signature, so we fake it */
2354
2355        tf.command = ATA_DRDY;          /* really, this is Status reg */
2356        tf.lbal = 0x1;
2357        tf.nsect = 0x1;
2358
2359        ata_tf_to_fis(&tf, 0, 1, &rbuf[36]);    /* TODO: PMP? */
2360        rbuf[36] = 0x34;                /* force D2H Reg FIS (34h) */
2361
2362        rbuf[56] = ATA_CMD_ID_ATA;
2363
2364        memcpy(&rbuf[60], &args->id[0], 512);
2365        return 0;
2366}
2367
2368static unsigned int ata_scsiop_inq_b0(struct ata_scsi_args *args, u8 *rbuf)
2369{
2370        u16 min_io_sectors;
2371
2372        rbuf[1] = 0xb0;
2373        rbuf[3] = 0x3c;         /* required VPD size with unmap support */
2374
2375        /*
2376         * Optimal transfer length granularity.
2377         *
2378         * This is always one physical block, but for disks with a smaller
2379         * logical than physical sector size we need to figure out what the
2380         * latter is.
2381         */
2382        min_io_sectors = 1 << ata_id_log2_per_physical_sector(args->id);
2383        put_unaligned_be16(min_io_sectors, &rbuf[6]);
2384
2385        /*
2386         * Optimal unmap granularity.
2387         *
2388         * The ATA spec doesn't even know about a granularity or alignment
2389         * for the TRIM command.  We can leave away most of the unmap related
2390         * VPD page entries, but we have specifify a granularity to signal
2391         * that we support some form of unmap - in thise case via WRITE SAME
2392         * with the unmap bit set.
2393         */
2394        if (ata_id_has_trim(args->id)) {
2395                put_unaligned_be64(65535 * ATA_MAX_TRIM_RNUM, &rbuf[36]);
2396                put_unaligned_be32(1, &rbuf[28]);
2397        }
2398
2399        return 0;
2400}
2401
2402static unsigned int ata_scsiop_inq_b1(struct ata_scsi_args *args, u8 *rbuf)
2403{
2404        int form_factor = ata_id_form_factor(args->id);
2405        int media_rotation_rate = ata_id_rotation_rate(args->id);
2406        u8 zoned = ata_id_zoned_cap(args->id);
2407
2408        rbuf[1] = 0xb1;
2409        rbuf[3] = 0x3c;
2410        rbuf[4] = media_rotation_rate >> 8;
2411        rbuf[5] = media_rotation_rate;
2412        rbuf[7] = form_factor;
2413        if (zoned)
2414                rbuf[8] = (zoned << 4);
2415
2416        return 0;
2417}
2418
2419static unsigned int ata_scsiop_inq_b2(struct ata_scsi_args *args, u8 *rbuf)
2420{
2421        /* SCSI Thin Provisioning VPD page: SBC-3 rev 22 or later */
2422        rbuf[1] = 0xb2;
2423        rbuf[3] = 0x4;
2424        rbuf[5] = 1 << 6;       /* TPWS */
2425
2426        return 0;
2427}
2428
2429static unsigned int ata_scsiop_inq_b6(struct ata_scsi_args *args, u8 *rbuf)
2430{
2431        /*
2432         * zbc-r05 SCSI Zoned Block device characteristics VPD page
2433         */
2434        rbuf[1] = 0xb6;
2435        rbuf[3] = 0x3C;
2436
2437        /*
2438         * URSWRZ bit is only meaningful for host-managed ZAC drives
2439         */
2440        if (args->dev->zac_zoned_cap & 1)
2441                rbuf[4] |= 1;
2442        put_unaligned_be32(args->dev->zac_zones_optimal_open, &rbuf[8]);
2443        put_unaligned_be32(args->dev->zac_zones_optimal_nonseq, &rbuf[12]);
2444        put_unaligned_be32(args->dev->zac_zones_max_open, &rbuf[16]);
2445
2446        return 0;
2447}
2448
2449/**
2450 *      modecpy - Prepare response for MODE SENSE
2451 *      @dest: output buffer
2452 *      @src: data being copied
2453 *      @n: length of mode page
2454 *      @changeable: whether changeable parameters are requested
2455 *
2456 *      Generate a generic MODE SENSE page for either current or changeable
2457 *      parameters.
2458 *
2459 *      LOCKING:
2460 *      None.
2461 */
2462static void modecpy(u8 *dest, const u8 *src, int n, bool changeable)
2463{
2464        if (changeable) {
2465                memcpy(dest, src, 2);
2466                memset(dest + 2, 0, n - 2);
2467        } else {
2468                memcpy(dest, src, n);
2469        }
2470}
2471
2472/**
2473 *      ata_msense_caching - Simulate MODE SENSE caching info page
2474 *      @id: device IDENTIFY data
2475 *      @buf: output buffer
2476 *      @changeable: whether changeable parameters are requested
2477 *
2478 *      Generate a caching info page, which conditionally indicates
2479 *      write caching to the SCSI layer, depending on device
2480 *      capabilities.
2481 *
2482 *      LOCKING:
2483 *      None.
2484 */
2485static unsigned int ata_msense_caching(u16 *id, u8 *buf, bool changeable)
2486{
2487        modecpy(buf, def_cache_mpage, sizeof(def_cache_mpage), changeable);
2488        if (changeable) {
2489                buf[2] |= (1 << 2);     /* ata_mselect_caching() */
2490        } else {
2491                buf[2] |= (ata_id_wcache_enabled(id) << 2);     /* write cache enable */
2492                buf[12] |= (!ata_id_rahead_enabled(id) << 5);   /* disable read ahead */
2493        }
2494        return sizeof(def_cache_mpage);
2495}
2496
2497/**
2498 *      ata_msense_control - Simulate MODE SENSE control mode page
2499 *      @dev: ATA device of interest
2500 *      @buf: output buffer
2501 *      @changeable: whether changeable parameters are requested
2502 *
2503 *      Generate a generic MODE SENSE control mode page.
2504 *
2505 *      LOCKING:
2506 *      None.
2507 */
2508static unsigned int ata_msense_control(struct ata_device *dev, u8 *buf,
2509                                        bool changeable)
2510{
2511        modecpy(buf, def_control_mpage, sizeof(def_control_mpage), changeable);
2512        if (changeable) {
2513                buf[2] |= (1 << 2);     /* ata_mselect_control() */
2514        } else {
2515                bool d_sense = (dev->flags & ATA_DFLAG_D_SENSE);
2516
2517                buf[2] |= (d_sense << 2);       /* descriptor format sense data */
2518        }
2519        return sizeof(def_control_mpage);
2520}
2521
2522/**
2523 *      ata_msense_rw_recovery - Simulate MODE SENSE r/w error recovery page
2524 *      @buf: output buffer
2525 *      @changeable: whether changeable parameters are requested
2526 *
2527 *      Generate a generic MODE SENSE r/w error recovery page.
2528 *
2529 *      LOCKING:
2530 *      None.
2531 */
2532static unsigned int ata_msense_rw_recovery(u8 *buf, bool changeable)
2533{
2534        modecpy(buf, def_rw_recovery_mpage, sizeof(def_rw_recovery_mpage),
2535                changeable);
2536        return sizeof(def_rw_recovery_mpage);
2537}
2538
2539/*
2540 * We can turn this into a real blacklist if it's needed, for now just
2541 * blacklist any Maxtor BANC1G10 revision firmware
2542 */
2543static int ata_dev_supports_fua(u16 *id)
2544{
2545        unsigned char model[ATA_ID_PROD_LEN + 1], fw[ATA_ID_FW_REV_LEN + 1];
2546
2547        if (!libata_fua)
2548                return 0;
2549        if (!ata_id_has_fua(id))
2550                return 0;
2551
2552        ata_id_c_string(id, model, ATA_ID_PROD, sizeof(model));
2553        ata_id_c_string(id, fw, ATA_ID_FW_REV, sizeof(fw));
2554
2555        if (strcmp(model, "Maxtor"))
2556                return 1;
2557        if (strcmp(fw, "BANC1G10"))
2558                return 1;
2559
2560        return 0; /* blacklisted */
2561}
2562
2563/**
2564 *      ata_scsiop_mode_sense - Simulate MODE SENSE 6, 10 commands
2565 *      @args: device IDENTIFY data / SCSI command of interest.
2566 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2567 *
2568 *      Simulate MODE SENSE commands. Assume this is invoked for direct
2569 *      access devices (e.g. disks) only. There should be no block
2570 *      descriptor for other device types.
2571 *
2572 *      LOCKING:
2573 *      spin_lock_irqsave(host lock)
2574 */
2575static unsigned int ata_scsiop_mode_sense(struct ata_scsi_args *args, u8 *rbuf)
2576{
2577        struct ata_device *dev = args->dev;
2578        u8 *scsicmd = args->cmd->cmnd, *p = rbuf;
2579        static const u8 sat_blk_desc[] = {
2580                0, 0, 0, 0,     /* number of blocks: sat unspecified */
2581                0,
2582                0, 0x2, 0x0     /* block length: 512 bytes */
2583        };
2584        u8 pg, spg;
2585        unsigned int ebd, page_control, six_byte;
2586        u8 dpofua, bp = 0xff;
2587        u16 fp;
2588
2589        VPRINTK("ENTER\n");
2590
2591        six_byte = (scsicmd[0] == MODE_SENSE);
2592        ebd = !(scsicmd[1] & 0x8);      /* dbd bit inverted == edb */
2593        /*
2594         * LLBA bit in msense(10) ignored (compliant)
2595         */
2596
2597        page_control = scsicmd[2] >> 6;
2598        switch (page_control) {
2599        case 0: /* current */
2600        case 1: /* changeable */
2601        case 2: /* defaults */
2602                break;  /* supported */
2603        case 3: /* saved */
2604                goto saving_not_supp;
2605        default:
2606                fp = 2;
2607                bp = 6;
2608                goto invalid_fld;
2609        }
2610
2611        if (six_byte)
2612                p += 4 + (ebd ? 8 : 0);
2613        else
2614                p += 8 + (ebd ? 8 : 0);
2615
2616        pg = scsicmd[2] & 0x3f;
2617        spg = scsicmd[3];
2618        /*
2619         * No mode subpages supported (yet) but asking for _all_
2620         * subpages may be valid
2621         */
2622        if (spg && (spg != ALL_SUB_MPAGES)) {
2623                fp = 3;
2624                goto invalid_fld;
2625        }
2626
2627        switch(pg) {
2628        case RW_RECOVERY_MPAGE:
2629                p += ata_msense_rw_recovery(p, page_control == 1);
2630                break;
2631
2632        case CACHE_MPAGE:
2633                p += ata_msense_caching(args->id, p, page_control == 1);
2634                break;
2635
2636        case CONTROL_MPAGE:
2637                p += ata_msense_control(args->dev, p, page_control == 1);
2638                break;
2639
2640        case ALL_MPAGES:
2641                p += ata_msense_rw_recovery(p, page_control == 1);
2642                p += ata_msense_caching(args->id, p, page_control == 1);
2643                p += ata_msense_control(args->dev, p, page_control == 1);
2644                break;
2645
2646        default:                /* invalid page code */
2647                fp = 2;
2648                goto invalid_fld;
2649        }
2650
2651        dpofua = 0;
2652        if (ata_dev_supports_fua(args->id) && (dev->flags & ATA_DFLAG_LBA48) &&
2653            (!(dev->flags & ATA_DFLAG_PIO) || dev->multi_count))
2654                dpofua = 1 << 4;
2655
2656        if (six_byte) {
2657                rbuf[0] = p - rbuf - 1;
2658                rbuf[2] |= dpofua;
2659                if (ebd) {
2660                        rbuf[3] = sizeof(sat_blk_desc);
2661                        memcpy(rbuf + 4, sat_blk_desc, sizeof(sat_blk_desc));
2662                }
2663        } else {
2664                unsigned int output_len = p - rbuf - 2;
2665
2666                rbuf[0] = output_len >> 8;
2667                rbuf[1] = output_len;
2668                rbuf[3] |= dpofua;
2669                if (ebd) {
2670                        rbuf[7] = sizeof(sat_blk_desc);
2671                        memcpy(rbuf + 8, sat_blk_desc, sizeof(sat_blk_desc));
2672                }
2673        }
2674        return 0;
2675
2676invalid_fld:
2677        ata_scsi_set_invalid_field(dev, args->cmd, fp, bp);
2678        return 1;
2679
2680saving_not_supp:
2681        ata_scsi_set_sense(dev, args->cmd, ILLEGAL_REQUEST, 0x39, 0x0);
2682         /* "Saving parameters not supported" */
2683        return 1;
2684}
2685
2686/**
2687 *      ata_scsiop_read_cap - Simulate READ CAPACITY[ 16] commands
2688 *      @args: device IDENTIFY data / SCSI command of interest.
2689 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2690 *
2691 *      Simulate READ CAPACITY commands.
2692 *
2693 *      LOCKING:
2694 *      None.
2695 */
2696static unsigned int ata_scsiop_read_cap(struct ata_scsi_args *args, u8 *rbuf)
2697{
2698        struct ata_device *dev = args->dev;
2699        u64 last_lba = dev->n_sectors - 1; /* LBA of the last block */
2700        u32 sector_size; /* physical sector size in bytes */
2701        u8 log2_per_phys;
2702        u16 lowest_aligned;
2703
2704        sector_size = ata_id_logical_sector_size(dev->id);
2705        log2_per_phys = ata_id_log2_per_physical_sector(dev->id);
2706        lowest_aligned = ata_id_logical_sector_offset(dev->id, log2_per_phys);
2707
2708        VPRINTK("ENTER\n");
2709
2710        if (args->cmd->cmnd[0] == READ_CAPACITY) {
2711                if (last_lba >= 0xffffffffULL)
2712                        last_lba = 0xffffffff;
2713
2714                /* sector count, 32-bit */
2715                rbuf[0] = last_lba >> (8 * 3);
2716                rbuf[1] = last_lba >> (8 * 2);
2717                rbuf[2] = last_lba >> (8 * 1);
2718                rbuf[3] = last_lba;
2719
2720                /* sector size */
2721                rbuf[4] = sector_size >> (8 * 3);
2722                rbuf[5] = sector_size >> (8 * 2);
2723                rbuf[6] = sector_size >> (8 * 1);
2724                rbuf[7] = sector_size;
2725        } else {
2726                /* sector count, 64-bit */
2727                rbuf[0] = last_lba >> (8 * 7);
2728                rbuf[1] = last_lba >> (8 * 6);
2729                rbuf[2] = last_lba >> (8 * 5);
2730                rbuf[3] = last_lba >> (8 * 4);
2731                rbuf[4] = last_lba >> (8 * 3);
2732                rbuf[5] = last_lba >> (8 * 2);
2733                rbuf[6] = last_lba >> (8 * 1);
2734                rbuf[7] = last_lba;
2735
2736                /* sector size */
2737                rbuf[ 8] = sector_size >> (8 * 3);
2738                rbuf[ 9] = sector_size >> (8 * 2);
2739                rbuf[10] = sector_size >> (8 * 1);
2740                rbuf[11] = sector_size;
2741
2742                rbuf[12] = 0;
2743                rbuf[13] = log2_per_phys;
2744                rbuf[14] = (lowest_aligned >> 8) & 0x3f;
2745                rbuf[15] = lowest_aligned;
2746
2747                if (ata_id_has_trim(args->id) &&
2748                    !(dev->horkage & ATA_HORKAGE_NOTRIM)) {
2749                        rbuf[14] |= 0x80; /* LBPME */
2750
2751                        if (ata_id_has_zero_after_trim(args->id) &&
2752                            dev->horkage & ATA_HORKAGE_ZERO_AFTER_TRIM) {
2753                                ata_dev_info(dev, "Enabling discard_zeroes_data\n");
2754                                rbuf[14] |= 0x40; /* LBPRZ */
2755                        }
2756                }
2757                if (ata_id_zoned_cap(args->id) ||
2758                    args->dev->class == ATA_DEV_ZAC)
2759                        rbuf[12] = (1 << 4); /* RC_BASIS */
2760        }
2761        return 0;
2762}
2763
2764/**
2765 *      ata_scsiop_report_luns - Simulate REPORT LUNS command
2766 *      @args: device IDENTIFY data / SCSI command of interest.
2767 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2768 *
2769 *      Simulate REPORT LUNS command.
2770 *
2771 *      LOCKING:
2772 *      spin_lock_irqsave(host lock)
2773 */
2774static unsigned int ata_scsiop_report_luns(struct ata_scsi_args *args, u8 *rbuf)
2775{
2776        VPRINTK("ENTER\n");
2777        rbuf[3] = 8;    /* just one lun, LUN 0, size 8 bytes */
2778
2779        return 0;
2780}
2781
2782static void atapi_sense_complete(struct ata_queued_cmd *qc)
2783{
2784        if (qc->err_mask && ((qc->err_mask & AC_ERR_DEV) == 0)) {
2785                /* FIXME: not quite right; we don't want the
2786                 * translation of taskfile registers into
2787                 * a sense descriptors, since that's only
2788                 * correct for ATA, not ATAPI
2789                 */
2790                ata_gen_passthru_sense(qc);
2791        }
2792
2793        ata_qc_done(qc);
2794}
2795
2796/* is it pointless to prefer PIO for "safety reasons"? */
2797static inline int ata_pio_use_silly(struct ata_port *ap)
2798{
2799        return (ap->flags & ATA_FLAG_PIO_DMA);
2800}
2801
2802static void atapi_request_sense(struct ata_queued_cmd *qc)
2803{
2804        struct ata_port *ap = qc->ap;
2805        struct scsi_cmnd *cmd = qc->scsicmd;
2806
2807        DPRINTK("ATAPI request sense\n");
2808
2809        memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
2810
2811#ifdef CONFIG_ATA_SFF
2812        if (ap->ops->sff_tf_read)
2813                ap->ops->sff_tf_read(ap, &qc->tf);
2814#endif
2815
2816        /* fill these in, for the case where they are -not- overwritten */
2817        cmd->sense_buffer[0] = 0x70;
2818        cmd->sense_buffer[2] = qc->tf.feature >> 4;
2819
2820        ata_qc_reinit(qc);
2821
2822        /* setup sg table and init transfer direction */
2823        sg_init_one(&qc->sgent, cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
2824        ata_sg_init(qc, &qc->sgent, 1);
2825        qc->dma_dir = DMA_FROM_DEVICE;
2826
2827        memset(&qc->cdb, 0, qc->dev->cdb_len);
2828        qc->cdb[0] = REQUEST_SENSE;
2829        qc->cdb[4] = SCSI_SENSE_BUFFERSIZE;
2830
2831        qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2832        qc->tf.command = ATA_CMD_PACKET;
2833
2834        if (ata_pio_use_silly(ap)) {
2835                qc->tf.protocol = ATAPI_PROT_DMA;
2836                qc->tf.feature |= ATAPI_PKT_DMA;
2837        } else {
2838                qc->tf.protocol = ATAPI_PROT_PIO;
2839                qc->tf.lbam = SCSI_SENSE_BUFFERSIZE;
2840                qc->tf.lbah = 0;
2841        }
2842        qc->nbytes = SCSI_SENSE_BUFFERSIZE;
2843
2844        qc->complete_fn = atapi_sense_complete;
2845
2846        ata_qc_issue(qc);
2847
2848        DPRINTK("EXIT\n");
2849}
2850
2851/*
2852 * ATAPI devices typically report zero for their SCSI version, and sometimes
2853 * deviate from the spec WRT response data format.  If SCSI version is
2854 * reported as zero like normal, then we make the following fixups:
2855 *   1) Fake MMC-5 version, to indicate to the Linux scsi midlayer this is a
2856 *      modern device.
2857 *   2) Ensure response data format / ATAPI information are always correct.
2858 */
2859static void atapi_fixup_inquiry(struct scsi_cmnd *cmd)
2860{
2861        u8 buf[4];
2862
2863        sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, 4);
2864        if (buf[2] == 0) {
2865                buf[2] = 0x5;
2866                buf[3] = 0x32;
2867        }
2868        sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, 4);
2869}
2870
2871static void atapi_qc_complete(struct ata_queued_cmd *qc)
2872{
2873        struct scsi_cmnd *cmd = qc->scsicmd;
2874        unsigned int err_mask = qc->err_mask;
2875
2876        VPRINTK("ENTER, err_mask 0x%X\n", err_mask);
2877
2878        /* handle completion from new EH */
2879        if (unlikely(qc->ap->ops->error_handler &&
2880                     (err_mask || qc->flags & ATA_QCFLAG_SENSE_VALID))) {
2881
2882                if (!(qc->flags & ATA_QCFLAG_SENSE_VALID)) {
2883                        /* FIXME: not quite right; we don't want the
2884                         * translation of taskfile registers into a
2885                         * sense descriptors, since that's only
2886                         * correct for ATA, not ATAPI
2887                         */
2888                        ata_gen_passthru_sense(qc);
2889                }
2890
2891                /* SCSI EH automatically locks door if sdev->locked is
2892                 * set.  Sometimes door lock request continues to
2893                 * fail, for example, when no media is present.  This
2894                 * creates a loop - SCSI EH issues door lock which
2895                 * fails and gets invoked again to acquire sense data
2896                 * for the failed command.
2897                 *
2898                 * If door lock fails, always clear sdev->locked to
2899                 * avoid this infinite loop.
2900                 *
2901                 * This may happen before SCSI scan is complete.  Make
2902                 * sure qc->dev->sdev isn't NULL before dereferencing.
2903                 */
2904                if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL && qc->dev->sdev)
2905                        qc->dev->sdev->locked = 0;
2906
2907                qc->scsicmd->result = SAM_STAT_CHECK_CONDITION;
2908                ata_qc_done(qc);
2909                return;
2910        }
2911
2912        /* successful completion or old EH failure path */
2913        if (unlikely(err_mask & AC_ERR_DEV)) {
2914                cmd->result = SAM_STAT_CHECK_CONDITION;
2915                atapi_request_sense(qc);
2916                return;
2917        } else if (unlikely(err_mask)) {
2918                /* FIXME: not quite right; we don't want the
2919                 * translation of taskfile registers into
2920                 * a sense descriptors, since that's only
2921                 * correct for ATA, not ATAPI
2922                 */
2923                ata_gen_passthru_sense(qc);
2924        } else {
2925                if (cmd->cmnd[0] == INQUIRY && (cmd->cmnd[1] & 0x03) == 0)
2926                        atapi_fixup_inquiry(cmd);
2927                cmd->result = SAM_STAT_GOOD;
2928        }
2929
2930        ata_qc_done(qc);
2931}
2932/**
2933 *      atapi_xlat - Initialize PACKET taskfile
2934 *      @qc: command structure to be initialized
2935 *
2936 *      LOCKING:
2937 *      spin_lock_irqsave(host lock)
2938 *
2939 *      RETURNS:
2940 *      Zero on success, non-zero on failure.
2941 */
2942static unsigned int atapi_xlat(struct ata_queued_cmd *qc)
2943{
2944        struct scsi_cmnd *scmd = qc->scsicmd;
2945        struct ata_device *dev = qc->dev;
2946        int nodata = (scmd->sc_data_direction == DMA_NONE);
2947        int using_pio = !nodata && (dev->flags & ATA_DFLAG_PIO);
2948        unsigned int nbytes;
2949
2950        memset(qc->cdb, 0, dev->cdb_len);
2951        memcpy(qc->cdb, scmd->cmnd, scmd->cmd_len);
2952
2953        qc->complete_fn = atapi_qc_complete;
2954
2955        qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2956        if (scmd->sc_data_direction == DMA_TO_DEVICE) {
2957                qc->tf.flags |= ATA_TFLAG_WRITE;
2958                DPRINTK("direction: write\n");
2959        }
2960
2961        qc->tf.command = ATA_CMD_PACKET;
2962        ata_qc_set_pc_nbytes(qc);
2963
2964        /* check whether ATAPI DMA is safe */
2965        if (!nodata && !using_pio && atapi_check_dma(qc))
2966                using_pio = 1;
2967
2968        /* Some controller variants snoop this value for Packet
2969         * transfers to do state machine and FIFO management.  Thus we
2970         * want to set it properly, and for DMA where it is
2971         * effectively meaningless.
2972         */
2973        nbytes = min(ata_qc_raw_nbytes(qc), (unsigned int)63 * 1024);
2974
2975        /* Most ATAPI devices which honor transfer chunk size don't
2976         * behave according to the spec when odd chunk size which
2977         * matches the transfer length is specified.  If the number of
2978         * bytes to transfer is 2n+1.  According to the spec, what
2979         * should happen is to indicate that 2n+1 is going to be
2980         * transferred and transfer 2n+2 bytes where the last byte is
2981         * padding.
2982         *
2983         * In practice, this doesn't happen.  ATAPI devices first
2984         * indicate and transfer 2n bytes and then indicate and
2985         * transfer 2 bytes where the last byte is padding.
2986         *
2987         * This inconsistency confuses several controllers which
2988         * perform PIO using DMA such as Intel AHCIs and sil3124/32.
2989         * These controllers use actual number of transferred bytes to
2990         * update DMA poitner and transfer of 4n+2 bytes make those
2991         * controller push DMA pointer by 4n+4 bytes because SATA data
2992         * FISes are aligned to 4 bytes.  This causes data corruption
2993         * and buffer overrun.
2994         *
2995         * Always setting nbytes to even number solves this problem
2996         * because then ATAPI devices don't have to split data at 2n
2997         * boundaries.
2998         */
2999        if (nbytes & 0x1)
3000                nbytes++;
3001
3002        qc->tf.lbam = (nbytes & 0xFF);
3003        qc->tf.lbah = (nbytes >> 8);
3004
3005        if (nodata)
3006                qc->tf.protocol = ATAPI_PROT_NODATA;
3007        else if (using_pio)
3008                qc->tf.protocol = ATAPI_PROT_PIO;
3009        else {
3010                /* DMA data xfer */
3011                qc->tf.protocol = ATAPI_PROT_DMA;
3012                qc->tf.feature |= ATAPI_PKT_DMA;
3013
3014                if ((dev->flags & ATA_DFLAG_DMADIR) &&
3015                    (scmd->sc_data_direction != DMA_TO_DEVICE))
3016                        /* some SATA bridges need us to indicate data xfer direction */
3017                        qc->tf.feature |= ATAPI_DMADIR;
3018        }
3019
3020
3021        /* FIXME: We need to translate 0x05 READ_BLOCK_LIMITS to a MODE_SENSE
3022           as ATAPI tape drives don't get this right otherwise */
3023        return 0;
3024}
3025
3026static struct ata_device *ata_find_dev(struct ata_port *ap, int devno)
3027{
3028        if (!sata_pmp_attached(ap)) {
3029                if (likely(devno >= 0 &&
3030                           devno < ata_link_max_devices(&ap->link)))
3031                        return &ap->link.device[devno];
3032        } else {
3033                if (likely(devno >= 0 &&
3034                           devno < ap->nr_pmp_links))
3035                        return &ap->pmp_link[devno].device[0];
3036        }
3037
3038        return NULL;
3039}
3040
3041static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
3042                                              const struct scsi_device *scsidev)
3043{
3044        int devno;
3045
3046        /* skip commands not addressed to targets we simulate */
3047        if (!sata_pmp_attached(ap)) {
3048                if (unlikely(scsidev->channel || scsidev->lun))
3049                        return NULL;
3050                devno = scsidev->id;
3051        } else {
3052                if (unlikely(scsidev->id || scsidev->lun))
3053                        return NULL;
3054                devno = scsidev->channel;
3055        }
3056
3057        return ata_find_dev(ap, devno);
3058}
3059
3060/**
3061 *      ata_scsi_find_dev - lookup ata_device from scsi_cmnd
3062 *      @ap: ATA port to which the device is attached
3063 *      @scsidev: SCSI device from which we derive the ATA device
3064 *
3065 *      Given various information provided in struct scsi_cmnd,
3066 *      map that onto an ATA bus, and using that mapping
3067 *      determine which ata_device is associated with the
3068 *      SCSI command to be sent.
3069 *
3070 *      LOCKING:
3071 *      spin_lock_irqsave(host lock)
3072 *
3073 *      RETURNS:
3074 *      Associated ATA device, or %NULL if not found.
3075 */
3076static struct ata_device *
3077ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
3078{
3079        struct ata_device *dev = __ata_scsi_find_dev(ap, scsidev);
3080
3081        if (unlikely(!dev || !ata_dev_enabled(dev)))
3082                return NULL;
3083
3084        return dev;
3085}
3086
3087/*
3088 *      ata_scsi_map_proto - Map pass-thru protocol value to taskfile value.
3089 *      @byte1: Byte 1 from pass-thru CDB.
3090 *
3091 *      RETURNS:
3092 *      ATA_PROT_UNKNOWN if mapping failed/unimplemented, protocol otherwise.
3093 */
3094static u8
3095ata_scsi_map_proto(u8 byte1)
3096{
3097        switch((byte1 & 0x1e) >> 1) {
3098        case 3:         /* Non-data */
3099                return ATA_PROT_NODATA;
3100
3101        case 6:         /* DMA */
3102        case 10:        /* UDMA Data-in */
3103        case 11:        /* UDMA Data-Out */
3104                return ATA_PROT_DMA;
3105
3106        case 4:         /* PIO Data-in */
3107        case 5:         /* PIO Data-out */
3108                return ATA_PROT_PIO;
3109
3110        case 12:        /* FPDMA */
3111                return ATA_PROT_NCQ;
3112
3113        case 0:         /* Hard Reset */
3114        case 1:         /* SRST */
3115        case 8:         /* Device Diagnostic */
3116        case 9:         /* Device Reset */
3117        case 7:         /* DMA Queued */
3118        case 15:        /* Return Response Info */
3119        default:        /* Reserved */
3120                break;
3121        }
3122
3123        return ATA_PROT_UNKNOWN;
3124}
3125
3126/**
3127 *      ata_scsi_pass_thru - convert ATA pass-thru CDB to taskfile
3128 *      @qc: command structure to be initialized
3129 *
3130 *      Handles either 12, 16, or 32-byte versions of the CDB.
3131 *
3132 *      RETURNS:
3133 *      Zero on success, non-zero on failure.
3134 */
3135static unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
3136{
3137        struct ata_taskfile *tf = &(qc->tf);
3138        struct scsi_cmnd *scmd = qc->scsicmd;
3139        struct ata_device *dev = qc->dev;
3140        const u8 *cdb = scmd->cmnd;
3141        u16 fp;
3142        u16 cdb_offset = 0;
3143
3144        /* 7Fh variable length cmd means a ata pass-thru(32) */
3145        if (cdb[0] == VARIABLE_LENGTH_CMD)
3146                cdb_offset = 9;
3147
3148        tf->protocol = ata_scsi_map_proto(cdb[1 + cdb_offset]);
3149        if (tf->protocol == ATA_PROT_UNKNOWN) {
3150                fp = 1;
3151                goto invalid_fld;
3152        }
3153
3154        if (ata_is_ncq(tf->protocol) && (cdb[2 + cdb_offset] & 0x3) == 0)
3155                tf->protocol = ATA_PROT_NCQ_NODATA;
3156
3157        /* enable LBA */
3158        tf->flags |= ATA_TFLAG_LBA;
3159
3160        /*
3161         * 12 and 16 byte CDBs use different offsets to
3162         * provide the various register values.
3163         */
3164        if (cdb[0] == ATA_16) {
3165                /*
3166                 * 16-byte CDB - may contain extended commands.
3167                 *
3168                 * If that is the case, copy the upper byte register values.
3169                 */
3170                if (cdb[1] & 0x01) {
3171                        tf->hob_feature = cdb[3];
3172                        tf->hob_nsect = cdb[5];
3173                        tf->hob_lbal = cdb[7];
3174                        tf->hob_lbam = cdb[9];
3175                        tf->hob_lbah = cdb[11];
3176                        tf->flags |= ATA_TFLAG_LBA48;
3177                } else
3178                        tf->flags &= ~ATA_TFLAG_LBA48;
3179
3180                /*
3181                 * Always copy low byte, device and command registers.
3182                 */
3183                tf->feature = cdb[4];
3184                tf->nsect = cdb[6];
3185                tf->lbal = cdb[8];
3186                tf->lbam = cdb[10];
3187                tf->lbah = cdb[12];
3188                tf->device = cdb[13];
3189                tf->command = cdb[14];
3190        } else if (cdb[0] == ATA_12) {
3191                /*
3192                 * 12-byte CDB - incapable of extended commands.
3193                 */
3194                tf->flags &= ~ATA_TFLAG_LBA48;
3195
3196                tf->feature = cdb[3];
3197                tf->nsect = cdb[4];
3198                tf->lbal = cdb[5];
3199                tf->lbam = cdb[6];
3200                tf->lbah = cdb[7];
3201                tf->device = cdb[8];
3202                tf->command = cdb[9];
3203        } else {
3204                /*
3205                 * 32-byte CDB - may contain extended command fields.
3206                 *
3207                 * If that is the case, copy the upper byte register values.
3208                 */
3209                if (cdb[10] & 0x01) {
3210                        tf->hob_feature = cdb[20];
3211                        tf->hob_nsect = cdb[22];
3212                        tf->hob_lbal = cdb[16];
3213                        tf->hob_lbam = cdb[15];
3214                        tf->hob_lbah = cdb[14];
3215                        tf->flags |= ATA_TFLAG_LBA48;
3216                } else
3217                        tf->flags &= ~ATA_TFLAG_LBA48;
3218
3219                tf->feature = cdb[21];
3220                tf->nsect = cdb[23];
3221                tf->lbal = cdb[19];
3222                tf->lbam = cdb[18];
3223                tf->lbah = cdb[17];
3224                tf->device = cdb[24];
3225                tf->command = cdb[25];
3226                tf->auxiliary = get_unaligned_be32(&cdb[28]);
3227        }
3228
3229        /* For NCQ commands copy the tag value */
3230        if (ata_is_ncq(tf->protocol))
3231                tf->nsect = qc->hw_tag << 3;
3232
3233        /* enforce correct master/slave bit */
3234        tf->device = dev->devno ?
3235                tf->device | ATA_DEV1 : tf->device & ~ATA_DEV1;
3236
3237        switch (tf->command) {
3238        /* READ/WRITE LONG use a non-standard sect_size */
3239        case ATA_CMD_READ_LONG:
3240        case ATA_CMD_READ_LONG_ONCE:
3241        case ATA_CMD_WRITE_LONG:
3242        case ATA_CMD_WRITE_LONG_ONCE:
3243                if (tf->protocol != ATA_PROT_PIO || tf->nsect != 1) {
3244                        fp = 1;
3245                        goto invalid_fld;
3246                }
3247                qc->sect_size = scsi_bufflen(scmd);
3248                break;
3249
3250        /* commands using reported Logical Block size (e.g. 512 or 4K) */
3251        case ATA_CMD_CFA_WRITE_NE:
3252        case ATA_CMD_CFA_TRANS_SECT:
3253        case ATA_CMD_CFA_WRITE_MULT_NE:
3254        /* XXX: case ATA_CMD_CFA_WRITE_SECTORS_WITHOUT_ERASE: */
3255        case ATA_CMD_READ:
3256        case ATA_CMD_READ_EXT:
3257        case ATA_CMD_READ_QUEUED:
3258        /* XXX: case ATA_CMD_READ_QUEUED_EXT: */
3259        case ATA_CMD_FPDMA_READ:
3260        case ATA_CMD_READ_MULTI:
3261        case ATA_CMD_READ_MULTI_EXT:
3262        case ATA_CMD_PIO_READ:
3263        case ATA_CMD_PIO_READ_EXT:
3264        case ATA_CMD_READ_STREAM_DMA_EXT:
3265        case ATA_CMD_READ_STREAM_EXT:
3266        case ATA_CMD_VERIFY:
3267        case ATA_CMD_VERIFY_EXT:
3268        case ATA_CMD_WRITE:
3269        case ATA_CMD_WRITE_EXT:
3270        case ATA_CMD_WRITE_FUA_EXT:
3271        case ATA_CMD_WRITE_QUEUED:
3272        case ATA_CMD_WRITE_QUEUED_FUA_EXT:
3273        case ATA_CMD_FPDMA_WRITE:
3274        case ATA_CMD_WRITE_MULTI:
3275        case ATA_CMD_WRITE_MULTI_EXT:
3276        case ATA_CMD_WRITE_MULTI_FUA_EXT:
3277        case ATA_CMD_PIO_WRITE:
3278        case ATA_CMD_PIO_WRITE_EXT:
3279        case ATA_CMD_WRITE_STREAM_DMA_EXT:
3280        case ATA_CMD_WRITE_STREAM_EXT:
3281                qc->sect_size = scmd->device->sector_size;
3282                break;
3283
3284        /* Everything else uses 512 byte "sectors" */
3285        default:
3286                qc->sect_size = ATA_SECT_SIZE;
3287        }
3288
3289        /*
3290         * Set flags so that all registers will be written, pass on
3291         * write indication (used for PIO/DMA setup), result TF is
3292         * copied back and we don't whine too much about its failure.
3293         */
3294        tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3295        if (scmd->sc_data_direction == DMA_TO_DEVICE)
3296                tf->flags |= ATA_TFLAG_WRITE;
3297
3298        qc->flags |= ATA_QCFLAG_RESULT_TF | ATA_QCFLAG_QUIET;
3299
3300        /*
3301         * Set transfer length.
3302         *
3303         * TODO: find out if we need to do more here to
3304         *       cover scatter/gather case.
3305         */
3306        ata_qc_set_pc_nbytes(qc);
3307
3308        /* We may not issue DMA commands if no DMA mode is set */
3309        if (tf->protocol == ATA_PROT_DMA && dev->dma_mode == 0) {
3310                fp = 1;
3311                goto invalid_fld;
3312        }
3313
3314        /* We may not issue NCQ commands to devices not supporting NCQ */
3315        if (ata_is_ncq(tf->protocol) && !ata_ncq_enabled(dev)) {
3316                fp = 1;
3317                goto invalid_fld;
3318        }
3319
3320        /* sanity check for pio multi commands */
3321        if ((cdb[1] & 0xe0) && !is_multi_taskfile(tf)) {
3322                fp = 1;
3323                goto invalid_fld;
3324        }
3325
3326        if (is_multi_taskfile(tf)) {
3327                unsigned int multi_count = 1 << (cdb[1] >> 5);
3328
3329                /* compare the passed through multi_count
3330                 * with the cached multi_count of libata
3331                 */
3332                if (multi_count != dev->multi_count)
3333                        ata_dev_warn(dev, "invalid multi_count %u ignored\n",
3334                                     multi_count);
3335        }
3336
3337        /*
3338         * Filter SET_FEATURES - XFER MODE command -- otherwise,
3339         * SET_FEATURES - XFER MODE must be preceded/succeeded
3340         * by an update to hardware-specific registers for each
3341         * controller (i.e. the reason for ->set_piomode(),
3342         * ->set_dmamode(), and ->post_set_mode() hooks).
3343         */
3344        if (tf->command == ATA_CMD_SET_FEATURES &&
3345            tf->feature == SETFEATURES_XFER) {
3346                fp = (cdb[0] == ATA_16) ? 4 : 3;
3347                goto invalid_fld;
3348        }
3349
3350        /*
3351         * Filter TPM commands by default. These provide an
3352         * essentially uncontrolled encrypted "back door" between
3353         * applications and the disk. Set libata.allow_tpm=1 if you
3354         * have a real reason for wanting to use them. This ensures
3355         * that installed software cannot easily mess stuff up without
3356         * user intent. DVR type users will probably ship with this enabled
3357         * for movie content management.
3358         *
3359         * Note that for ATA8 we can issue a DCS change and DCS freeze lock
3360         * for this and should do in future but that it is not sufficient as
3361         * DCS is an optional feature set. Thus we also do the software filter
3362         * so that we comply with the TC consortium stated goal that the user
3363         * can turn off TC features of their system.
3364         */
3365        if (tf->command >= 0x5C && tf->command <= 0x5F && !libata_allow_tpm) {
3366                fp = (cdb[0] == ATA_16) ? 14 : 9;
3367                goto invalid_fld;
3368        }
3369
3370        return 0;
3371
3372 invalid_fld:
3373        ata_scsi_set_invalid_field(dev, scmd, fp, 0xff);
3374        return 1;
3375}
3376
3377/**
3378 * ata_format_dsm_trim_descr() - SATL Write Same to DSM Trim
3379 * @cmd: SCSI command being translated
3380 * @trmax: Maximum number of entries that will fit in sector_size bytes.
3381 * @sector: Starting sector
3382 * @count: Total Range of request in logical sectors
3383 *
3384 * Rewrite the WRITE SAME descriptor to be a DSM TRIM little-endian formatted
3385 * descriptor.
3386 *
3387 * Upto 64 entries of the format:
3388 *   63:48 Range Length
3389 *   47:0  LBA
3390 *
3391 *  Range Length of 0 is ignored.
3392 *  LBA's should be sorted order and not overlap.
3393 *
3394 * NOTE: this is the same format as ADD LBA(S) TO NV CACHE PINNED SET
3395 *
3396 * Return: Number of bytes copied into sglist.
3397 */
3398static size_t ata_format_dsm_trim_descr(struct scsi_cmnd *cmd, u32 trmax,
3399                                        u64 sector, u32 count)
3400{
3401        struct scsi_device *sdp = cmd->device;
3402        size_t len = sdp->sector_size;
3403        size_t r;
3404        __le64 *buf;
3405        u32 i = 0;
3406        unsigned long flags;
3407
3408        WARN_ON(len > ATA_SCSI_RBUF_SIZE);
3409
3410        if (len > ATA_SCSI_RBUF_SIZE)
3411                len = ATA_SCSI_RBUF_SIZE;
3412
3413        spin_lock_irqsave(&ata_scsi_rbuf_lock, flags);
3414        buf = ((void *)ata_scsi_rbuf);
3415        memset(buf, 0, len);
3416        while (i < trmax) {
3417                u64 entry = sector |
3418                        ((u64)(count > 0xffff ? 0xffff : count) << 48);
3419                buf[i++] = __cpu_to_le64(entry);
3420                if (count <= 0xffff)
3421                        break;
3422                count -= 0xffff;
3423                sector += 0xffff;
3424        }
3425        r = sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, len);
3426        spin_unlock_irqrestore(&ata_scsi_rbuf_lock, flags);
3427
3428        return r;
3429}
3430
3431/**
3432 * ata_scsi_write_same_xlat() - SATL Write Same to ATA SCT Write Same
3433 * @qc: Command to be translated
3434 *
3435 * Translate a SCSI WRITE SAME command to be either a DSM TRIM command or
3436 * an SCT Write Same command.
3437 * Based on WRITE SAME has the UNMAP flag:
3438 *
3439 *   - When set translate to DSM TRIM
3440 *   - When clear translate to SCT Write Same
3441 */
3442static unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
3443{
3444        struct ata_taskfile *tf = &qc->tf;
3445        struct scsi_cmnd *scmd = qc->scsicmd;
3446        struct scsi_device *sdp = scmd->device;
3447        size_t len = sdp->sector_size;
3448        struct ata_device *dev = qc->dev;
3449        const u8 *cdb = scmd->cmnd;
3450        u64 block;
3451        u32 n_block;
3452        const u32 trmax = len >> 3;
3453        u32 size;
3454        u16 fp;
3455        u8 bp = 0xff;
3456        u8 unmap = cdb[1] & 0x8;
3457
3458        /* we may not issue DMA commands if no DMA mode is set */
3459        if (unlikely(!dev->dma_mode))
3460                goto invalid_opcode;
3461
3462        /*
3463         * We only allow sending this command through the block layer,
3464         * as it modifies the DATA OUT buffer, which would corrupt user
3465         * memory for SG_IO commands.
3466         */
3467        if (unlikely(blk_rq_is_passthrough(scmd->request)))
3468                goto invalid_opcode;
3469
3470        if (unlikely(scmd->cmd_len < 16)) {
3471                fp = 15;
3472                goto invalid_fld;
3473        }
3474        scsi_16_lba_len(cdb, &block, &n_block);
3475
3476        if (!unmap ||
3477            (dev->horkage & ATA_HORKAGE_NOTRIM) ||
3478            !ata_id_has_trim(dev->id)) {
3479                fp = 1;
3480                bp = 3;
3481                goto invalid_fld;
3482        }
3483        /* If the request is too large the cmd is invalid */
3484        if (n_block > 0xffff * trmax) {
3485                fp = 2;
3486                goto invalid_fld;
3487        }
3488
3489        /*
3490         * WRITE SAME always has a sector sized buffer as payload, this
3491         * should never be a multiple entry S/G list.
3492         */
3493        if (!scsi_sg_count(scmd))
3494                goto invalid_param_len;
3495
3496        /*
3497         * size must match sector size in bytes
3498         * For DATA SET MANAGEMENT TRIM in ACS-2 nsect (aka count)
3499         * is defined as number of 512 byte blocks to be transferred.
3500         */
3501
3502        size = ata_format_dsm_trim_descr(scmd, trmax, block, n_block);
3503        if (size != len)
3504                goto invalid_param_len;
3505
3506        if (ata_ncq_enabled(dev) && ata_fpdma_dsm_supported(dev)) {
3507                /* Newer devices support queued TRIM commands */
3508                tf->protocol = ATA_PROT_NCQ;
3509                tf->command = ATA_CMD_FPDMA_SEND;
3510                tf->hob_nsect = ATA_SUBCMD_FPDMA_SEND_DSM & 0x1f;
3511                tf->nsect = qc->hw_tag << 3;
3512                tf->hob_feature = (size / 512) >> 8;
3513                tf->feature = size / 512;
3514
3515                tf->auxiliary = 1;
3516        } else {
3517                tf->protocol = ATA_PROT_DMA;
3518                tf->hob_feature = 0;
3519                tf->feature = ATA_DSM_TRIM;
3520                tf->hob_nsect = (size / 512) >> 8;
3521                tf->nsect = size / 512;
3522                tf->command = ATA_CMD_DSM;
3523        }
3524
3525        tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48 |
3526                     ATA_TFLAG_WRITE;
3527
3528        ata_qc_set_pc_nbytes(qc);
3529
3530        return 0;
3531
3532invalid_fld:
3533        ata_scsi_set_invalid_field(dev, scmd, fp, bp);
3534        return 1;
3535invalid_param_len:
3536        /* "Parameter list length error" */
3537        ata_scsi_set_sense(dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3538        return 1;
3539invalid_opcode:
3540        /* "Invalid command operation code" */
3541        ata_scsi_set_sense(dev, scmd, ILLEGAL_REQUEST, 0x20, 0x0);
3542        return 1;
3543}
3544
3545/**
3546 *      ata_scsiop_maint_in - Simulate a subset of MAINTENANCE_IN
3547 *      @args: device MAINTENANCE_IN data / SCSI command of interest.
3548 *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
3549 *
3550 *      Yields a subset to satisfy scsi_report_opcode()
3551 *
3552 *      LOCKING:
3553 *      spin_lock_irqsave(host lock)
3554 */
3555static unsigned int ata_scsiop_maint_in(struct ata_scsi_args *args, u8 *rbuf)
3556{
3557        struct ata_device *dev = args->dev;
3558        u8 *cdb = args->cmd->cmnd;
3559        u8 supported = 0;
3560        unsigned int err = 0;
3561
3562        if (cdb[2] != 1) {
3563                ata_dev_warn(dev, "invalid command format %d\n", cdb[2]);
3564                err = 2;
3565                goto out;
3566        }
3567        switch (cdb[3]) {
3568        case INQUIRY:
3569        case MODE_SENSE:
3570        case MODE_SENSE_10:
3571        case READ_CAPACITY:
3572        case SERVICE_ACTION_IN_16:
3573        case REPORT_LUNS:
3574        case REQUEST_SENSE:
3575        case SYNCHRONIZE_CACHE:
3576        case REZERO_UNIT:
3577        case SEEK_6:
3578        case SEEK_10:
3579        case TEST_UNIT_READY:
3580        case SEND_DIAGNOSTIC:
3581        case MAINTENANCE_IN:
3582        case READ_6:
3583        case READ_10:
3584        case READ_16:
3585        case WRITE_6:
3586        case WRITE_10:
3587        case WRITE_16:
3588        case ATA_12:
3589        case ATA_16:
3590        case VERIFY:
3591        case VERIFY_16:
3592        case MODE_SELECT:
3593        case MODE_SELECT_10:
3594        case START_STOP:
3595                supported = 3;
3596                break;
3597        case ZBC_IN:
3598        case ZBC_OUT:
3599                if (ata_id_zoned_cap(dev->id) ||
3600                    dev->class == ATA_DEV_ZAC)
3601                        supported = 3;
3602                break;
3603        case SECURITY_PROTOCOL_IN:
3604        case SECURITY_PROTOCOL_OUT:
3605                if (dev->flags & ATA_DFLAG_TRUSTED)
3606                        supported = 3;
3607                break;
3608        default:
3609                break;
3610        }
3611out:
3612        rbuf[1] = supported; /* supported */
3613        return err;
3614}
3615
3616/**
3617 *      ata_scsi_report_zones_complete - convert ATA output
3618 *      @qc: command structure returning the data
3619 *
3620 *      Convert T-13 little-endian field representation into
3621 *      T-10 big-endian field representation.
3622 *      What a mess.
3623 */
3624static void ata_scsi_report_zones_complete(struct ata_queued_cmd *qc)
3625{
3626        struct scsi_cmnd *scmd = qc->scsicmd;
3627        struct sg_mapping_iter miter;
3628        unsigned long flags;
3629        unsigned int bytes = 0;
3630
3631        sg_miter_start(&miter, scsi_sglist(scmd), scsi_sg_count(scmd),
3632                       SG_MITER_TO_SG | SG_MITER_ATOMIC);
3633
3634        local_irq_save(flags);
3635        while (sg_miter_next(&miter)) {
3636                unsigned int offset = 0;
3637
3638                if (bytes == 0) {
3639                        char *hdr;
3640                        u32 list_length;
3641                        u64 max_lba, opt_lba;
3642                        u16 same;
3643
3644                        /* Swizzle header */
3645                        hdr = miter.addr;
3646                        list_length = get_unaligned_le32(&hdr[0]);
3647                        same = get_unaligned_le16(&hdr[4]);
3648                        max_lba = get_unaligned_le64(&hdr[8]);
3649                        opt_lba = get_unaligned_le64(&hdr[16]);
3650                        put_unaligned_be32(list_length, &hdr[0]);
3651                        hdr[4] = same & 0xf;
3652                        put_unaligned_be64(max_lba, &hdr[8]);
3653                        put_unaligned_be64(opt_lba, &hdr[16]);
3654                        offset += 64;
3655                        bytes += 64;
3656                }
3657                while (offset < miter.length) {
3658                        char *rec;
3659                        u8 cond, type, non_seq, reset;
3660                        u64 size, start, wp;
3661
3662                        /* Swizzle zone descriptor */
3663                        rec = miter.addr + offset;
3664                        type = rec[0] & 0xf;
3665                        cond = (rec[1] >> 4) & 0xf;
3666                        non_seq = (rec[1] & 2);
3667                        reset = (rec[1] & 1);
3668                        size = get_unaligned_le64(&rec[8]);
3669                        start = get_unaligned_le64(&rec[16]);
3670                        wp = get_unaligned_le64(&rec[24]);
3671                        rec[0] = type;
3672                        rec[1] = (cond << 4) | non_seq | reset;
3673                        put_unaligned_be64(size, &rec[8]);
3674                        put_unaligned_be64(start, &rec[16]);
3675                        put_unaligned_be64(wp, &rec[24]);
3676                        WARN_ON(offset + 64 > miter.length);
3677                        offset += 64;
3678                        bytes += 64;
3679                }
3680        }
3681        sg_miter_stop(&miter);
3682        local_irq_restore(flags);
3683
3684        ata_scsi_qc_complete(qc);
3685}
3686
3687static unsigned int ata_scsi_zbc_in_xlat(struct ata_queued_cmd *qc)
3688{
3689        struct ata_taskfile *tf = &qc->tf;
3690        struct scsi_cmnd *scmd = qc->scsicmd;
3691        const u8 *cdb = scmd->cmnd;
3692        u16 sect, fp = (u16)-1;
3693        u8 sa, options, bp = 0xff;
3694        u64 block;
3695        u32 n_block;
3696
3697        if (unlikely(scmd->cmd_len < 16)) {
3698                ata_dev_warn(qc->dev, "invalid cdb length %d\n",
3699                             scmd->cmd_len);
3700                fp = 15;
3701                goto invalid_fld;
3702        }
3703        scsi_16_lba_len(cdb, &block, &n_block);
3704        if (n_block != scsi_bufflen(scmd)) {
3705                ata_dev_warn(qc->dev, "non-matching transfer count (%d/%d)\n",
3706                             n_block, scsi_bufflen(scmd));
3707                goto invalid_param_len;
3708        }
3709        sa = cdb[1] & 0x1f;
3710        if (sa != ZI_REPORT_ZONES) {
3711                ata_dev_warn(qc->dev, "invalid service action %d\n", sa);
3712                fp = 1;
3713                goto invalid_fld;
3714        }
3715        /*
3716         * ZAC allows only for transfers in 512 byte blocks,
3717         * and uses a 16 bit value for the transfer count.
3718         */
3719        if ((n_block / 512) > 0xffff || n_block < 512 || (n_block % 512)) {
3720                ata_dev_warn(qc->dev, "invalid transfer count %d\n", n_block);
3721                goto invalid_param_len;
3722        }
3723        sect = n_block / 512;
3724        options = cdb[14] & 0xbf;
3725
3726        if (ata_ncq_enabled(qc->dev) &&
3727            ata_fpdma_zac_mgmt_in_supported(qc->dev)) {
3728                tf->protocol = ATA_PROT_NCQ;
3729                tf->command = ATA_CMD_FPDMA_RECV;
3730                tf->hob_nsect = ATA_SUBCMD_FPDMA_RECV_ZAC_MGMT_IN & 0x1f;
3731                tf->nsect = qc->hw_tag << 3;
3732                tf->feature = sect & 0xff;
3733                tf->hob_feature = (sect >> 8) & 0xff;
3734                tf->auxiliary = ATA_SUBCMD_ZAC_MGMT_IN_REPORT_ZONES | (options << 8);
3735        } else {
3736                tf->command = ATA_CMD_ZAC_MGMT_IN;
3737                tf->feature = ATA_SUBCMD_ZAC_MGMT_IN_REPORT_ZONES;
3738                tf->protocol = ATA_PROT_DMA;
3739                tf->hob_feature = options;
3740                tf->hob_nsect = (sect >> 8) & 0xff;
3741                tf->nsect = sect & 0xff;
3742        }
3743        tf->device = ATA_LBA;
3744        tf->lbah = (block >> 16) & 0xff;
3745        tf->lbam = (block >> 8) & 0xff;
3746        tf->lbal = block & 0xff;
3747        tf->hob_lbah = (block >> 40) & 0xff;
3748        tf->hob_lbam = (block >> 32) & 0xff;
3749        tf->hob_lbal = (block >> 24) & 0xff;
3750
3751        tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48;
3752        qc->flags |= ATA_QCFLAG_RESULT_TF;
3753
3754        ata_qc_set_pc_nbytes(qc);
3755
3756        qc->complete_fn = ata_scsi_report_zones_complete;
3757
3758        return 0;
3759
3760invalid_fld:
3761        ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
3762        return 1;
3763
3764invalid_param_len:
3765        /* "Parameter list length error" */
3766        ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3767        return 1;
3768}
3769
3770static unsigned int ata_scsi_zbc_out_xlat(struct ata_queued_cmd *qc)
3771{
3772        struct ata_taskfile *tf = &qc->tf;
3773        struct scsi_cmnd *scmd = qc->scsicmd;
3774        struct ata_device *dev = qc->dev;
3775        const u8 *cdb = scmd->cmnd;
3776        u8 all, sa;
3777        u64 block;
3778        u32 n_block;
3779        u16 fp = (u16)-1;
3780
3781        if (unlikely(scmd->cmd_len < 16)) {
3782                fp = 15;
3783                goto invalid_fld;
3784        }
3785
3786        sa = cdb[1] & 0x1f;
3787        if ((sa != ZO_CLOSE_ZONE) && (sa != ZO_FINISH_ZONE) &&
3788            (sa != ZO_OPEN_ZONE) && (sa != ZO_RESET_WRITE_POINTER)) {
3789                fp = 1;
3790                goto invalid_fld;
3791        }
3792
3793        scsi_16_lba_len(cdb, &block, &n_block);
3794        if (n_block) {
3795                /*
3796                 * ZAC MANAGEMENT OUT doesn't define any length
3797                 */
3798                goto invalid_param_len;
3799        }
3800
3801        all = cdb[14] & 0x1;
3802        if (all) {
3803                /*
3804                 * Ignore the block address (zone ID) as defined by ZBC.
3805                 */
3806                block = 0;
3807        } else if (block >= dev->n_sectors) {
3808                /*
3809                 * Block must be a valid zone ID (a zone start LBA).
3810                 */
3811                fp = 2;
3812                goto invalid_fld;
3813        }
3814
3815        if (ata_ncq_enabled(qc->dev) &&
3816            ata_fpdma_zac_mgmt_out_supported(qc->dev)) {
3817                tf->protocol = ATA_PROT_NCQ_NODATA;
3818                tf->command = ATA_CMD_NCQ_NON_DATA;
3819                tf->feature = ATA_SUBCMD_NCQ_NON_DATA_ZAC_MGMT_OUT;
3820                tf->nsect = qc->hw_tag << 3;
3821                tf->auxiliary = sa | ((u16)all << 8);
3822        } else {
3823                tf->protocol = ATA_PROT_NODATA;
3824                tf->command = ATA_CMD_ZAC_MGMT_OUT;
3825                tf->feature = sa;
3826                tf->hob_feature = all;
3827        }
3828        tf->lbah = (block >> 16) & 0xff;
3829        tf->lbam = (block >> 8) & 0xff;
3830        tf->lbal = block & 0xff;
3831        tf->hob_lbah = (block >> 40) & 0xff;
3832        tf->hob_lbam = (block >> 32) & 0xff;
3833        tf->hob_lbal = (block >> 24) & 0xff;
3834        tf->device = ATA_LBA;
3835        tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48;
3836
3837        return 0;
3838
3839 invalid_fld:
3840        ata_scsi_set_invalid_field(qc->dev, scmd, fp, 0xff);
3841        return 1;
3842invalid_param_len:
3843        /* "Parameter list length error" */
3844        ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3845        return 1;
3846}
3847
3848/**
3849 *      ata_mselect_caching - Simulate MODE SELECT for caching info page
3850 *      @qc: Storage for translated ATA taskfile
3851 *      @buf: input buffer
3852 *      @len: number of valid bytes in the input buffer
3853 *      @fp: out parameter for the failed field on error
3854 *
3855 *      Prepare a taskfile to modify caching information for the device.
3856 *
3857 *      LOCKING:
3858 *      None.
3859 */
3860static int ata_mselect_caching(struct ata_queued_cmd *qc,
3861                               const u8 *buf, int len, u16 *fp)
3862{
3863        struct ata_taskfile *tf = &qc->tf;
3864        struct ata_device *dev = qc->dev;
3865        u8 mpage[CACHE_MPAGE_LEN];
3866        u8 wce;
3867        int i;
3868
3869        /*
3870         * The first two bytes of def_cache_mpage are a header, so offsets
3871         * in mpage are off by 2 compared to buf.  Same for len.
3872         */
3873
3874        if (len != CACHE_MPAGE_LEN - 2) {
3875                if (len < CACHE_MPAGE_LEN - 2)
3876                        *fp = len;
3877                else
3878                        *fp = CACHE_MPAGE_LEN - 2;
3879                return -EINVAL;
3880        }
3881
3882        wce = buf[0] & (1 << 2);
3883
3884        /*
3885         * Check that read-only bits are not modified.
3886         */
3887        ata_msense_caching(dev->id, mpage, false);
3888        for (i = 0; i < CACHE_MPAGE_LEN - 2; i++) {
3889                if (i == 0)
3890                        continue;
3891                if (mpage[i + 2] != buf[i]) {
3892                        *fp = i;
3893                        return -EINVAL;
3894                }
3895        }
3896
3897        tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
3898        tf->protocol = ATA_PROT_NODATA;
3899        tf->nsect = 0;
3900        tf->command = ATA_CMD_SET_FEATURES;
3901        tf->feature = wce ? SETFEATURES_WC_ON : SETFEATURES_WC_OFF;
3902        return 0;
3903}
3904
3905/**
3906 *      ata_mselect_control - Simulate MODE SELECT for control page
3907 *      @qc: Storage for translated ATA taskfile
3908 *      @buf: input buffer
3909 *      @len: number of valid bytes in the input buffer
3910 *      @fp: out parameter for the failed field on error
3911 *
3912 *      Prepare a taskfile to modify caching information for the device.
3913 *
3914 *      LOCKING:
3915 *      None.
3916 */
3917static int ata_mselect_control(struct ata_queued_cmd *qc,
3918                               const u8 *buf, int len, u16 *fp)
3919{
3920        struct ata_device *dev = qc->dev;
3921        u8 mpage[CONTROL_MPAGE_LEN];
3922        u8 d_sense;
3923        int i;
3924
3925        /*
3926         * The first two bytes of def_control_mpage are a header, so offsets
3927         * in mpage are off by 2 compared to buf.  Same for len.
3928         */
3929
3930        if (len != CONTROL_MPAGE_LEN - 2) {
3931                if (len < CONTROL_MPAGE_LEN - 2)
3932                        *fp = len;
3933                else
3934                        *fp = CONTROL_MPAGE_LEN - 2;
3935                return -EINVAL;
3936        }
3937
3938        d_sense = buf[0] & (1 << 2);
3939
3940        /*
3941         * Check that read-only bits are not modified.
3942         */
3943        ata_msense_control(dev, mpage, false);
3944        for (i = 0; i < CONTROL_MPAGE_LEN - 2; i++) {
3945                if (i == 0)
3946                        continue;
3947                if (mpage[2 + i] != buf[i]) {
3948                        *fp = i;
3949                        return -EINVAL;
3950                }
3951        }
3952        if (d_sense & (1 << 2))
3953                dev->flags |= ATA_DFLAG_D_SENSE;
3954        else
3955                dev->flags &= ~ATA_DFLAG_D_SENSE;
3956        return 0;
3957}
3958
3959/**
3960 *      ata_scsi_mode_select_xlat - Simulate MODE SELECT 6, 10 commands
3961 *      @qc: Storage for translated ATA taskfile
3962 *
3963 *      Converts a MODE SELECT command to an ATA SET FEATURES taskfile.
3964 *      Assume this is invoked for direct access devices (e.g. disks) only.
3965 *      There should be no block descriptor for other device types.
3966 *
3967 *      LOCKING:
3968 *      spin_lock_irqsave(host lock)
3969 */
3970static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc)
3971{
3972        struct scsi_cmnd *scmd = qc->scsicmd;
3973        const u8 *cdb = scmd->cmnd;
3974        const u8 *p;
3975        u8 pg, spg;
3976        unsigned six_byte, pg_len, hdr_len, bd_len;
3977        int len;
3978        u16 fp = (u16)-1;
3979        u8 bp = 0xff;
3980
3981        VPRINTK("ENTER\n");
3982
3983        six_byte = (cdb[0] == MODE_SELECT);
3984        if (six_byte) {
3985                if (scmd->cmd_len < 5) {
3986                        fp = 4;
3987                        goto invalid_fld;
3988                }
3989
3990                len = cdb[4];
3991                hdr_len = 4;
3992        } else {
3993                if (scmd->cmd_len < 9) {
3994                        fp = 8;
3995                        goto invalid_fld;
3996                }
3997
3998                len = (cdb[7] << 8) + cdb[8];
3999                hdr_len = 8;
4000        }
4001
4002        /* We only support PF=1, SP=0.  */
4003        if ((cdb[1] & 0x11) != 0x10) {
4004                fp = 1;
4005                bp = (cdb[1] & 0x01) ? 1 : 5;
4006                goto invalid_fld;
4007        }
4008
4009        /* Test early for possible overrun.  */
4010        if (!scsi_sg_count(scmd) || scsi_sglist(scmd)->length < len)
4011                goto invalid_param_len;
4012
4013        p = page_address(sg_page(scsi_sglist(scmd)));
4014
4015        /* Move past header and block descriptors.  */
4016        if (len < hdr_len)
4017                goto invalid_param_len;
4018
4019        if (six_byte)
4020                bd_len = p[3];
4021        else
4022                bd_len = (p[6] << 8) + p[7];
4023
4024        len -= hdr_len;
4025        p += hdr_len;
4026        if (len < bd_len)
4027                goto invalid_param_len;
4028        if (bd_len != 0 && bd_len != 8) {
4029                fp = (six_byte) ? 3 : 6;
4030                fp += bd_len + hdr_len;
4031                goto invalid_param;
4032        }
4033
4034        len -= bd_len;
4035        p += bd_len;
4036        if (len == 0)
4037                goto skip;
4038
4039        /* Parse both possible formats for the mode page headers.  */
4040        pg = p[0] & 0x3f;
4041        if (p[0] & 0x40) {
4042                if (len < 4)
4043                        goto invalid_param_len;
4044
4045                spg = p[1];
4046                pg_len = (p[2] << 8) | p[3];
4047                p += 4;
4048                len -= 4;
4049        } else {
4050                if (len < 2)
4051                        goto invalid_param_len;
4052
4053                spg = 0;
4054                pg_len = p[1];
4055                p += 2;
4056                len -= 2;
4057        }
4058
4059        /*
4060         * No mode subpages supported (yet) but asking for _all_
4061         * subpages may be valid
4062         */
4063        if (spg && (spg != ALL_SUB_MPAGES)) {
4064                fp = (p[0] & 0x40) ? 1 : 0;
4065                fp += hdr_len + bd_len;
4066                goto invalid_param;
4067        }
4068        if (pg_len > len)
4069                goto invalid_param_len;
4070
4071        switch (pg) {
4072        case CACHE_MPAGE:
4073                if (ata_mselect_caching(qc, p, pg_len, &fp) < 0) {
4074                        fp += hdr_len + bd_len;
4075                        goto invalid_param;
4076                }
4077                break;
4078        case CONTROL_MPAGE:
4079                if (ata_mselect_control(qc, p, pg_len, &fp) < 0) {
4080                        fp += hdr_len + bd_len;
4081                        goto invalid_param;
4082                } else {
4083                        goto skip; /* No ATA command to send */
4084                }
4085                break;
4086        default:                /* invalid page code */
4087                fp = bd_len + hdr_len;
4088                goto invalid_param;
4089        }
4090
4091        /*
4092         * Only one page has changeable data, so we only support setting one
4093         * page at a time.
4094         */
4095        if (len > pg_len)
4096                goto invalid_param;
4097
4098        return 0;
4099
4100 invalid_fld:
4101        ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
4102        return 1;
4103
4104 invalid_param:
4105        ata_scsi_set_invalid_parameter(qc->dev, scmd, fp);
4106        return 1;
4107
4108 invalid_param_len:
4109        /* "Parameter list length error" */
4110        ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
4111        return 1;
4112
4113 skip:
4114        scmd->result = SAM_STAT_GOOD;
4115        return 1;
4116}
4117
4118static u8 ata_scsi_trusted_op(u32 len, bool send, bool dma)
4119{
4120        if (len == 0)
4121                return ATA_CMD_TRUSTED_NONDATA;
4122        else if (send)
4123                return dma ? ATA_CMD_TRUSTED_SND_DMA : ATA_CMD_TRUSTED_SND;
4124        else
4125                return dma ? ATA_CMD_TRUSTED_RCV_DMA : ATA_CMD_TRUSTED_RCV;
4126}
4127
4128static unsigned int ata_scsi_security_inout_xlat(struct ata_queued_cmd *qc)
4129{
4130        struct scsi_cmnd *scmd = qc->scsicmd;
4131        const u8 *cdb = scmd->cmnd;
4132        struct ata_taskfile *tf = &qc->tf;
4133        u8 secp = cdb[1];
4134        bool send = (cdb[0] == SECURITY_PROTOCOL_OUT);
4135        u16 spsp = get_unaligned_be16(&cdb[2]);
4136        u32 len = get_unaligned_be32(&cdb[6]);
4137        bool dma = !(qc->dev->flags & ATA_DFLAG_PIO);
4138
4139        /*
4140         * We don't support the ATA "security" protocol.
4141         */
4142        if (secp == 0xef) {
4143                ata_scsi_set_invalid_field(qc->dev, scmd, 1, 0);
4144                return 1;
4145        }
4146
4147        if (cdb[4] & 7) { /* INC_512 */
4148                if (len > 0xffff) {
4149                        ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0);
4150                        return 1;
4151                }
4152        } else {
4153                if (len > 0x01fffe00) {
4154                        ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0);
4155                        return 1;
4156                }
4157
4158                /* convert to the sector-based ATA addressing */
4159                len = (len + 511) / 512;
4160        }
4161
4162        tf->protocol = dma ? ATA_PROT_DMA : ATA_PROT_PIO;
4163        tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR | ATA_TFLAG_LBA;
4164        if (send)
4165                tf->flags |= ATA_TFLAG_WRITE;
4166        tf->command = ata_scsi_trusted_op(len, send, dma);
4167        tf->feature = secp;
4168        tf->lbam = spsp & 0xff;
4169        tf->lbah = spsp >> 8;
4170
4171        if (len) {
4172                tf->nsect = len & 0xff;
4173                tf->lbal = len >> 8;
4174        } else {
4175                if (!send)
4176                        tf->lbah = (1 << 7);
4177        }
4178
4179        ata_qc_set_pc_nbytes(qc);
4180        return 0;
4181}
4182
4183/**
4184 *      ata_scsi_var_len_cdb_xlat - SATL variable length CDB to Handler
4185 *      @qc: Command to be translated
4186 *
4187 *      Translate a SCSI variable length CDB to specified commands.
4188 *      It checks a service action value in CDB to call corresponding handler.
4189 *
4190 *      RETURNS:
4191 *      Zero on success, non-zero on failure
4192 *
4193 */
4194static unsigned int ata_scsi_var_len_cdb_xlat(struct ata_queued_cmd *qc)
4195{
4196        struct scsi_cmnd *scmd = qc->scsicmd;
4197        const u8 *cdb = scmd->cmnd;
4198        const u16 sa = get_unaligned_be16(&cdb[8]);
4199
4200        /*
4201         * if service action represents a ata pass-thru(32) command,
4202         * then pass it to ata_scsi_pass_thru handler.
4203         */
4204        if (sa == ATA_32)
4205                return ata_scsi_pass_thru(qc);
4206
4207        /* unsupported service action */
4208        return 1;
4209}
4210
4211/**
4212 *      ata_get_xlat_func - check if SCSI to ATA translation is possible
4213 *      @dev: ATA device
4214 *      @cmd: SCSI command opcode to consider
4215 *
4216 *      Look up the SCSI command given, and determine whether the
4217 *      SCSI command is to be translated or simulated.
4218 *
4219 *      RETURNS:
4220 *      Pointer to translation function if possible, %NULL if not.
4221 */
4222
4223static inline ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
4224{
4225        switch (cmd) {
4226        case READ_6:
4227        case READ_10:
4228        case READ_16:
4229
4230        case WRITE_6:
4231        case WRITE_10:
4232        case WRITE_16:
4233                return ata_scsi_rw_xlat;
4234
4235        case WRITE_SAME_16:
4236                return ata_scsi_write_same_xlat;
4237
4238        case SYNCHRONIZE_CACHE:
4239                if (ata_try_flush_cache(dev))
4240                        return ata_scsi_flush_xlat;
4241                break;
4242
4243        case VERIFY:
4244        case VERIFY_16:
4245                return ata_scsi_verify_xlat;
4246
4247        case ATA_12:
4248        case ATA_16:
4249                return ata_scsi_pass_thru;
4250
4251        case VARIABLE_LENGTH_CMD:
4252                return ata_scsi_var_len_cdb_xlat;
4253
4254        case MODE_SELECT:
4255        case MODE_SELECT_10:
4256                return ata_scsi_mode_select_xlat;
4257                break;
4258
4259        case ZBC_IN:
4260                return ata_scsi_zbc_in_xlat;
4261
4262        case ZBC_OUT:
4263                return ata_scsi_zbc_out_xlat;
4264
4265        case SECURITY_PROTOCOL_IN:
4266        case SECURITY_PROTOCOL_OUT:
4267                if (!(dev->flags & ATA_DFLAG_TRUSTED))
4268                        break;
4269                return ata_scsi_security_inout_xlat;
4270
4271        case START_STOP:
4272                return ata_scsi_start_stop_xlat;
4273        }
4274
4275        return NULL;
4276}
4277
4278/**
4279 *      ata_scsi_dump_cdb - dump SCSI command contents to dmesg
4280 *      @ap: ATA port to which the command was being sent
4281 *      @cmd: SCSI command to dump
4282 *
4283 *      Prints the contents of a SCSI command via printk().
4284 */
4285
4286static inline void ata_scsi_dump_cdb(struct ata_port *ap,
4287                                     struct scsi_cmnd *cmd)
4288{
4289#ifdef ATA_DEBUG
4290        struct scsi_device *scsidev = cmd->device;
4291
4292        DPRINTK("CDB (%u:%d,%d,%lld) %9ph\n",
4293                ap->print_id,
4294                scsidev->channel, scsidev->id, scsidev->lun,
4295                cmd->cmnd);
4296#endif
4297}
4298
4299static inline int __ata_scsi_queuecmd(struct scsi_cmnd *scmd,
4300                                      struct ata_device *dev)
4301{
4302        u8 scsi_op = scmd->cmnd[0];
4303        ata_xlat_func_t xlat_func;
4304        int rc = 0;
4305
4306        if (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ZAC) {
4307                if (unlikely(!scmd->cmd_len || scmd->cmd_len > dev->cdb_len))
4308                        goto bad_cdb_len;
4309
4310                xlat_func = ata_get_xlat_func(dev, scsi_op);
4311        } else {
4312                if (unlikely(!scmd->cmd_len))
4313                        goto bad_cdb_len;
4314
4315                xlat_func = NULL;
4316                if (likely((scsi_op != ATA_16) || !atapi_passthru16)) {
4317                        /* relay SCSI command to ATAPI device */
4318                        int len = COMMAND_SIZE(scsi_op);
4319                        if (unlikely(len > scmd->cmd_len ||
4320                                     len > dev->cdb_len ||
4321                                     scmd->cmd_len > ATAPI_CDB_LEN))
4322                                goto bad_cdb_len;
4323
4324                        xlat_func = atapi_xlat;
4325                } else {
4326                        /* ATA_16 passthru, treat as an ATA command */
4327                        if (unlikely(scmd->cmd_len > 16))
4328                                goto bad_cdb_len;
4329
4330                        xlat_func = ata_get_xlat_func(dev, scsi_op);
4331                }
4332        }
4333
4334        if (xlat_func)
4335                rc = ata_scsi_translate(dev, scmd, xlat_func);
4336        else
4337                ata_scsi_simulate(dev, scmd);
4338
4339        return rc;
4340
4341 bad_cdb_len:
4342        DPRINTK("bad CDB len=%u, scsi_op=0x%02x, max=%u\n",
4343                scmd->cmd_len, scsi_op, dev->cdb_len);
4344        scmd->result = DID_ERROR << 16;
4345        scmd->scsi_done(scmd);
4346        return 0;
4347}
4348
4349/**
4350 *      ata_scsi_queuecmd - Issue SCSI cdb to libata-managed device
4351 *      @shost: SCSI host of command to be sent
4352 *      @cmd: SCSI command to be sent
4353 *
4354 *      In some cases, this function translates SCSI commands into
4355 *      ATA taskfiles, and queues the taskfiles to be sent to
4356 *      hardware.  In other cases, this function simulates a
4357 *      SCSI device by evaluating and responding to certain
4358 *      SCSI commands.  This creates the overall effect of
4359 *      ATA and ATAPI devices appearing as SCSI devices.
4360 *
4361 *      LOCKING:
4362 *      ATA host lock
4363 *
4364 *      RETURNS:
4365 *      Return value from __ata_scsi_queuecmd() if @cmd can be queued,
4366 *      0 otherwise.
4367 */
4368int ata_scsi_queuecmd(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
4369{
4370        struct ata_port *ap;
4371        struct ata_device *dev;
4372        struct scsi_device *scsidev = cmd->device;
4373        int rc = 0;
4374        unsigned long irq_flags;
4375
4376        ap = ata_shost_to_port(shost);
4377
4378        spin_lock_irqsave(ap->lock, irq_flags);
4379
4380        ata_scsi_dump_cdb(ap, cmd);
4381
4382        dev = ata_scsi_find_dev(ap, scsidev);
4383        if (likely(dev))
4384                rc = __ata_scsi_queuecmd(cmd, dev);
4385        else {
4386                cmd->result = (DID_BAD_TARGET << 16);
4387                cmd->scsi_done(cmd);
4388        }
4389
4390        spin_unlock_irqrestore(ap->lock, irq_flags);
4391
4392        return rc;
4393}
4394
4395/**
4396 *      ata_scsi_simulate - simulate SCSI command on ATA device
4397 *      @dev: the target device
4398 *      @cmd: SCSI command being sent to device.
4399 *
4400 *      Interprets and directly executes a select list of SCSI commands
4401 *      that can be handled internally.
4402 *
4403 *      LOCKING:
4404 *      spin_lock_irqsave(host lock)
4405 */
4406
4407void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd)
4408{
4409        struct ata_scsi_args args;
4410        const u8 *scsicmd = cmd->cmnd;
4411        u8 tmp8;
4412
4413        args.dev = dev;
4414        args.id = dev->id;
4415        args.cmd = cmd;
4416
4417        switch(scsicmd[0]) {
4418        case INQUIRY:
4419                if (scsicmd[1] & 2)                /* is CmdDt set?  */
4420                        ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4421                else if ((scsicmd[1] & 1) == 0)    /* is EVPD clear? */
4422                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_std);
4423                else switch (scsicmd[2]) {
4424                case 0x00:
4425                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_00);
4426                        break;
4427                case 0x80:
4428                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_80);
4429                        break;
4430                case 0x83:
4431                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_83);
4432                        break;
4433                case 0x89:
4434                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_89);
4435                        break;
4436                case 0xb0:
4437                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b0);
4438                        break;
4439                case 0xb1:
4440                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b1);
4441                        break;
4442                case 0xb2:
4443                        ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b2);
4444                        break;
4445                case 0xb6:
4446                        if (dev->flags & ATA_DFLAG_ZAC) {
4447                                ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b6);
4448                                break;
4449                        }
4450                        /* Fallthrough */
4451                default:
4452                        ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
4453                        break;
4454                }
4455                break;
4456
4457        case MODE_SENSE:
4458        case MODE_SENSE_10:
4459                ata_scsi_rbuf_fill(&args, ata_scsiop_mode_sense);
4460                break;
4461
4462        case READ_CAPACITY:
4463                ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
4464                break;
4465
4466        case SERVICE_ACTION_IN_16:
4467                if ((scsicmd[1] & 0x1f) == SAI_READ_CAPACITY_16)
4468                        ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
4469                else
4470                        ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4471                break;
4472
4473        case REPORT_LUNS:
4474                ata_scsi_rbuf_fill(&args, ata_scsiop_report_luns);
4475                break;
4476
4477        case REQUEST_SENSE:
4478                ata_scsi_set_sense(dev, cmd, 0, 0, 0);
4479                cmd->result = (DRIVER_SENSE << 24);
4480                break;
4481
4482        /* if we reach this, then writeback caching is disabled,
4483         * turning this into a no-op.
4484         */
4485        case SYNCHRONIZE_CACHE:
4486                /* fall through */
4487
4488        /* no-op's, complete with success */
4489        case REZERO_UNIT:
4490        case SEEK_6:
4491        case SEEK_10:
4492        case TEST_UNIT_READY:
4493                break;
4494
4495        case SEND_DIAGNOSTIC:
4496                tmp8 = scsicmd[1] & ~(1 << 3);
4497                if (tmp8 != 0x4 || scsicmd[3] || scsicmd[4])
4498                        ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4499                break;
4500
4501        case MAINTENANCE_IN:
4502                if (scsicmd[1] == MI_REPORT_SUPPORTED_OPERATION_CODES)
4503                        ata_scsi_rbuf_fill(&args, ata_scsiop_maint_in);
4504                else
4505                        ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4506                break;
4507
4508        /* all other commands */
4509        default:
4510                ata_scsi_set_sense(dev, cmd, ILLEGAL_REQUEST, 0x20, 0x0);
4511                /* "Invalid command operation code" */
4512                break;
4513        }
4514
4515        cmd->scsi_done(cmd);
4516}
4517
4518int ata_scsi_add_hosts(struct ata_host *host, struct scsi_host_template *sht)
4519{
4520        int i, rc;
4521
4522        for (i = 0; i < host->n_ports; i++) {
4523                struct ata_port *ap = host->ports[i];
4524                struct Scsi_Host *shost;
4525
4526                rc = -ENOMEM;
4527                shost = scsi_host_alloc(sht, sizeof(struct ata_port *));
4528                if (!shost)
4529                        goto err_alloc;
4530
4531                shost->eh_noresume = 1;
4532                *(struct ata_port **)&shost->hostdata[0] = ap;
4533                ap->scsi_host = shost;
4534
4535                shost->transportt = ata_scsi_transport_template;
4536                shost->unique_id = ap->print_id;
4537                shost->max_id = 16;
4538                shost->max_lun = 1;
4539                shost->max_channel = 1;
4540                shost->max_cmd_len = 32;
4541
4542                /* Schedule policy is determined by ->qc_defer()
4543                 * callback and it needs to see every deferred qc.
4544                 * Set host_blocked to 1 to prevent SCSI midlayer from
4545                 * automatically deferring requests.
4546                 */
4547                shost->max_host_blocked = 1;
4548
4549                rc = scsi_add_host_with_dma(ap->scsi_host,
4550                                                &ap->tdev, ap->host->dev);
4551                if (rc)
4552                        goto err_add;
4553        }
4554
4555        return 0;
4556
4557 err_add:
4558        scsi_host_put(host->ports[i]->scsi_host);
4559 err_alloc:
4560        while (--i >= 0) {
4561                struct Scsi_Host *shost = host->ports[i]->scsi_host;
4562
4563                scsi_remove_host(shost);
4564                scsi_host_put(shost);
4565        }
4566        return rc;
4567}
4568
4569void ata_scsi_scan_host(struct ata_port *ap, int sync)
4570{
4571        int tries = 5;
4572        struct ata_device *last_failed_dev = NULL;
4573        struct ata_link *link;
4574        struct ata_device *dev;
4575
4576 repeat:
4577        ata_for_each_link(link, ap, EDGE) {
4578                ata_for_each_dev(dev, link, ENABLED) {
4579                        struct scsi_device *sdev;
4580                        int channel = 0, id = 0;
4581
4582                        if (dev->sdev)
4583                                continue;
4584
4585                        if (ata_is_host_link(link))
4586                                id = dev->devno;
4587                        else
4588                                channel = link->pmp;
4589
4590                        sdev = __scsi_add_device(ap->scsi_host, channel, id, 0,
4591                                                 NULL);
4592                        if (!IS_ERR(sdev)) {
4593                                dev->sdev = sdev;
4594                                scsi_device_put(sdev);
4595                        } else {
4596                                dev->sdev = NULL;
4597                        }
4598                }
4599        }
4600
4601        /* If we scanned while EH was in progress or allocation
4602         * failure occurred, scan would have failed silently.  Check
4603         * whether all devices are attached.
4604         */
4605        ata_for_each_link(link, ap, EDGE) {
4606                ata_for_each_dev(dev, link, ENABLED) {
4607                        if (!dev->sdev)
4608                                goto exit_loop;
4609                }
4610        }
4611 exit_loop:
4612        if (!link)
4613                return;
4614
4615        /* we're missing some SCSI devices */
4616        if (sync) {
4617                /* If caller requested synchrnous scan && we've made
4618                 * any progress, sleep briefly and repeat.
4619                 */
4620                if (dev != last_failed_dev) {
4621                        msleep(100);
4622                        last_failed_dev = dev;
4623                        goto repeat;
4624                }
4625
4626                /* We might be failing to detect boot device, give it
4627                 * a few more chances.
4628                 */
4629                if (--tries) {
4630                        msleep(100);
4631                        goto repeat;
4632                }
4633
4634                ata_port_err(ap,
4635                             "WARNING: synchronous SCSI scan failed without making any progress, switching to async\n");
4636        }
4637
4638        queue_delayed_work(system_long_wq, &ap->hotplug_task,
4639                           round_jiffies_relative(HZ));
4640}
4641
4642/**
4643 *      ata_scsi_offline_dev - offline attached SCSI device
4644 *      @dev: ATA device to offline attached SCSI device for
4645 *
4646 *      This function is called from ata_eh_hotplug() and responsible
4647 *      for taking the SCSI device attached to @dev offline.  This
4648 *      function is called with host lock which protects dev->sdev
4649 *      against clearing.
4650 *
4651 *      LOCKING:
4652 *      spin_lock_irqsave(host lock)
4653 *
4654 *      RETURNS:
4655 *      1 if attached SCSI device exists, 0 otherwise.
4656 */
4657int ata_scsi_offline_dev(struct ata_device *dev)
4658{
4659        if (dev->sdev) {
4660                scsi_device_set_state(dev->sdev, SDEV_OFFLINE);
4661                return 1;
4662        }
4663        return 0;
4664}
4665
4666/**
4667 *      ata_scsi_remove_dev - remove attached SCSI device
4668 *      @dev: ATA device to remove attached SCSI device for
4669 *
4670 *      This function is called from ata_eh_scsi_hotplug() and
4671 *      responsible for removing the SCSI device attached to @dev.
4672 *
4673 *      LOCKING:
4674 *      Kernel thread context (may sleep).
4675 */
4676static void ata_scsi_remove_dev(struct ata_device *dev)
4677{
4678        struct ata_port *ap = dev->link->ap;
4679        struct scsi_device *sdev;
4680        unsigned long flags;
4681
4682        /* Alas, we need to grab scan_mutex to ensure SCSI device
4683         * state doesn't change underneath us and thus
4684         * scsi_device_get() always succeeds.  The mutex locking can
4685         * be removed if there is __scsi_device_get() interface which
4686         * increments reference counts regardless of device state.
4687         */
4688        mutex_lock(&ap->scsi_host->scan_mutex);
4689        spin_lock_irqsave(ap->lock, flags);
4690
4691        /* clearing dev->sdev is protected by host lock */
4692        sdev = dev->sdev;
4693        dev->sdev = NULL;
4694
4695        if (sdev) {
4696                /* If user initiated unplug races with us, sdev can go
4697                 * away underneath us after the host lock and
4698                 * scan_mutex are released.  Hold onto it.
4699                 */
4700                if (scsi_device_get(sdev) == 0) {
4701                        /* The following ensures the attached sdev is
4702                         * offline on return from ata_scsi_offline_dev()
4703                         * regardless it wins or loses the race
4704                         * against this function.
4705                         */
4706                        scsi_device_set_state(sdev, SDEV_OFFLINE);
4707                } else {
4708                        WARN_ON(1);
4709                        sdev = NULL;
4710                }
4711        }
4712
4713        spin_unlock_irqrestore(ap->lock, flags);
4714        mutex_unlock(&ap->scsi_host->scan_mutex);
4715
4716        if (sdev) {
4717                ata_dev_info(dev, "detaching (SCSI %s)\n",
4718                             dev_name(&sdev->sdev_gendev));
4719
4720                scsi_remove_device(sdev);
4721                scsi_device_put(sdev);
4722        }
4723}
4724
4725static void ata_scsi_handle_link_detach(struct ata_link *link)
4726{
4727        struct ata_port *ap = link->ap;
4728        struct ata_device *dev;
4729
4730        ata_for_each_dev(dev, link, ALL) {
4731                unsigned long flags;
4732
4733                if (!(dev->flags & ATA_DFLAG_DETACHED))
4734                        continue;
4735
4736                spin_lock_irqsave(ap->lock, flags);
4737                dev->flags &= ~ATA_DFLAG_DETACHED;
4738                spin_unlock_irqrestore(ap->lock, flags);
4739
4740                if (zpodd_dev_enabled(dev))
4741                        zpodd_exit(dev);
4742
4743                ata_scsi_remove_dev(dev);
4744        }
4745}
4746
4747/**
4748 *      ata_scsi_media_change_notify - send media change event
4749 *      @dev: Pointer to the disk device with media change event
4750 *
4751 *      Tell the block layer to send a media change notification
4752 *      event.
4753 *
4754 *      LOCKING:
4755 *      spin_lock_irqsave(host lock)
4756 */
4757void ata_scsi_media_change_notify(struct ata_device *dev)
4758{
4759        if (dev->sdev)
4760                sdev_evt_send_simple(dev->sdev, SDEV_EVT_MEDIA_CHANGE,
4761                                     GFP_ATOMIC);
4762}
4763
4764/**
4765 *      ata_scsi_hotplug - SCSI part of hotplug
4766 *      @work: Pointer to ATA port to perform SCSI hotplug on
4767 *
4768 *      Perform SCSI part of hotplug.  It's executed from a separate
4769 *      workqueue after EH completes.  This is necessary because SCSI
4770 *      hot plugging requires working EH and hot unplugging is
4771 *      synchronized with hot plugging with a mutex.
4772 *
4773 *      LOCKING:
4774 *      Kernel thread context (may sleep).
4775 */
4776void ata_scsi_hotplug(struct work_struct *work)
4777{
4778        struct ata_port *ap =
4779                container_of(work, struct ata_port, hotplug_task.work);
4780        int i;
4781
4782        if (ap->pflags & ATA_PFLAG_UNLOADING) {
4783                DPRINTK("ENTER/EXIT - unloading\n");
4784                return;
4785        }
4786
4787        DPRINTK("ENTER\n");
4788        mutex_lock(&ap->scsi_scan_mutex);
4789
4790        /* Unplug detached devices.  We cannot use link iterator here
4791         * because PMP links have to be scanned even if PMP is
4792         * currently not attached.  Iterate manually.
4793         */
4794        ata_scsi_handle_link_detach(&ap->link);
4795        if (ap->pmp_link)
4796                for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
4797                        ata_scsi_handle_link_detach(&ap->pmp_link[i]);
4798
4799        /* scan for new ones */
4800        ata_scsi_scan_host(ap, 0);
4801
4802        mutex_unlock(&ap->scsi_scan_mutex);
4803        DPRINTK("EXIT\n");
4804}
4805
4806/**
4807 *      ata_scsi_user_scan - indication for user-initiated bus scan
4808 *      @shost: SCSI host to scan
4809 *      @channel: Channel to scan
4810 *      @id: ID to scan
4811 *      @lun: LUN to scan
4812 *
4813 *      This function is called when user explicitly requests bus
4814 *      scan.  Set probe pending flag and invoke EH.
4815 *
4816 *      LOCKING:
4817 *      SCSI layer (we don't care)
4818 *
4819 *      RETURNS:
4820 *      Zero.
4821 */
4822int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel,
4823                       unsigned int id, u64 lun)
4824{
4825        struct ata_port *ap = ata_shost_to_port(shost);
4826        unsigned long flags;
4827        int devno, rc = 0;
4828
4829        if (!ap->ops->error_handler)
4830                return -EOPNOTSUPP;
4831
4832        if (lun != SCAN_WILD_CARD && lun)
4833                return -EINVAL;
4834
4835        if (!sata_pmp_attached(ap)) {
4836                if (channel != SCAN_WILD_CARD && channel)
4837                        return -EINVAL;
4838                devno = id;
4839        } else {
4840                if (id != SCAN_WILD_CARD && id)
4841                        return -EINVAL;
4842                devno = channel;
4843        }
4844
4845        spin_lock_irqsave(ap->lock, flags);
4846
4847        if (devno == SCAN_WILD_CARD) {
4848                struct ata_link *link;
4849
4850                ata_for_each_link(link, ap, EDGE) {
4851                        struct ata_eh_info *ehi = &link->eh_info;
4852                        ehi->probe_mask |= ATA_ALL_DEVICES;
4853                        ehi->action |= ATA_EH_RESET;
4854                }
4855        } else {
4856                struct ata_device *dev = ata_find_dev(ap, devno);
4857
4858                if (dev) {
4859                        struct ata_eh_info *ehi = &dev->link->eh_info;
4860                        ehi->probe_mask |= 1 << dev->devno;
4861                        ehi->action |= ATA_EH_RESET;
4862                } else
4863                        rc = -EINVAL;
4864        }
4865
4866        if (rc == 0) {
4867                ata_port_schedule_eh(ap);
4868                spin_unlock_irqrestore(ap->lock, flags);
4869                ata_port_wait_eh(ap);
4870        } else
4871                spin_unlock_irqrestore(ap->lock, flags);
4872
4873        return rc;
4874}
4875
4876/**
4877 *      ata_scsi_dev_rescan - initiate scsi_rescan_device()
4878 *      @work: Pointer to ATA port to perform scsi_rescan_device()
4879 *
4880 *      After ATA pass thru (SAT) commands are executed successfully,
4881 *      libata need to propagate the changes to SCSI layer.
4882 *
4883 *      LOCKING:
4884 *      Kernel thread context (may sleep).
4885 */
4886void ata_scsi_dev_rescan(struct work_struct *work)
4887{
4888        struct ata_port *ap =
4889                container_of(work, struct ata_port, scsi_rescan_task);
4890        struct ata_link *link;
4891        struct ata_device *dev;
4892        unsigned long flags;
4893
4894        mutex_lock(&ap->scsi_scan_mutex);
4895        spin_lock_irqsave(ap->lock, flags);
4896
4897        ata_for_each_link(link, ap, EDGE) {
4898                ata_for_each_dev(dev, link, ENABLED) {
4899                        struct scsi_device *sdev = dev->sdev;
4900
4901                        if (!sdev)
4902                                continue;
4903                        if (scsi_device_get(sdev))
4904                                continue;
4905
4906                        spin_unlock_irqrestore(ap->lock, flags);
4907                        scsi_rescan_device(&(sdev->sdev_gendev));
4908                        scsi_device_put(sdev);
4909                        spin_lock_irqsave(ap->lock, flags);
4910                }
4911        }
4912
4913        spin_unlock_irqrestore(ap->lock, flags);
4914        mutex_unlock(&ap->scsi_scan_mutex);
4915}
4916
4917/**
4918 *      ata_sas_port_alloc - Allocate port for a SAS attached SATA device
4919 *      @host: ATA host container for all SAS ports
4920 *      @port_info: Information from low-level host driver
4921 *      @shost: SCSI host that the scsi device is attached to
4922 *
4923 *      LOCKING:
4924 *      PCI/etc. bus probe sem.
4925 *
4926 *      RETURNS:
4927 *      ata_port pointer on success / NULL on failure.
4928 */
4929
4930struct ata_port *ata_sas_port_alloc(struct ata_host *host,
4931                                    struct ata_port_info *port_info,
4932                                    struct Scsi_Host *shost)
4933{
4934        struct ata_port *ap;
4935
4936        ap = ata_port_alloc(host);
4937        if (!ap)
4938                return NULL;
4939
4940        ap->port_no = 0;
4941        ap->lock = &host->lock;
4942        ap->pio_mask = port_info->pio_mask;
4943        ap->mwdma_mask = port_info->mwdma_mask;
4944        ap->udma_mask = port_info->udma_mask;
4945        ap->flags |= port_info->flags;
4946        ap->ops = port_info->port_ops;
4947        ap->cbl = ATA_CBL_SATA;
4948
4949        return ap;
4950}
4951EXPORT_SYMBOL_GPL(ata_sas_port_alloc);
4952
4953/**
4954 *      ata_sas_port_start - Set port up for dma.
4955 *      @ap: Port to initialize
4956 *
4957 *      Called just after data structures for each port are
4958 *      initialized.
4959 *
4960 *      May be used as the port_start() entry in ata_port_operations.
4961 *
4962 *      LOCKING:
4963 *      Inherited from caller.
4964 */
4965int ata_sas_port_start(struct ata_port *ap)
4966{
4967        /*
4968         * the port is marked as frozen at allocation time, but if we don't
4969         * have new eh, we won't thaw it
4970         */
4971        if (!ap->ops->error_handler)
4972                ap->pflags &= ~ATA_PFLAG_FROZEN;
4973        return 0;
4974}
4975EXPORT_SYMBOL_GPL(ata_sas_port_start);
4976
4977/**
4978 *      ata_port_stop - Undo ata_sas_port_start()
4979 *      @ap: Port to shut down
4980 *
4981 *      May be used as the port_stop() entry in ata_port_operations.
4982 *
4983 *      LOCKING:
4984 *      Inherited from caller.
4985 */
4986
4987void ata_sas_port_stop(struct ata_port *ap)
4988{
4989}
4990EXPORT_SYMBOL_GPL(ata_sas_port_stop);
4991
4992/**
4993 * ata_sas_async_probe - simply schedule probing and return
4994 * @ap: Port to probe
4995 *
4996 * For batch scheduling of probe for sas attached ata devices, assumes
4997 * the port has already been through ata_sas_port_init()
4998 */
4999void ata_sas_async_probe(struct ata_port *ap)
5000{
5001        __ata_port_probe(ap);
5002}
5003EXPORT_SYMBOL_GPL(ata_sas_async_probe);
5004
5005int ata_sas_sync_probe(struct ata_port *ap)
5006{
5007        return ata_port_probe(ap);
5008}
5009EXPORT_SYMBOL_GPL(ata_sas_sync_probe);
5010
5011
5012/**
5013 *      ata_sas_port_init - Initialize a SATA device
5014 *      @ap: SATA port to initialize
5015 *
5016 *      LOCKING:
5017 *      PCI/etc. bus probe sem.
5018 *
5019 *      RETURNS:
5020 *      Zero on success, non-zero on error.
5021 */
5022
5023int ata_sas_port_init(struct ata_port *ap)
5024{
5025        int rc = ap->ops->port_start(ap);
5026
5027        if (rc)
5028                return rc;
5029        ap->print_id = atomic_inc_return(&ata_print_id);
5030        return 0;
5031}
5032EXPORT_SYMBOL_GPL(ata_sas_port_init);
5033
5034int ata_sas_tport_add(struct device *parent, struct ata_port *ap)
5035{
5036        return ata_tport_add(parent, ap);
5037}
5038EXPORT_SYMBOL_GPL(ata_sas_tport_add);
5039
5040void ata_sas_tport_delete(struct ata_port *ap)
5041{
5042        ata_tport_delete(ap);
5043}
5044EXPORT_SYMBOL_GPL(ata_sas_tport_delete);
5045
5046/**
5047 *      ata_sas_port_destroy - Destroy a SATA port allocated by ata_sas_port_alloc
5048 *      @ap: SATA port to destroy
5049 *
5050 */
5051
5052void ata_sas_port_destroy(struct ata_port *ap)
5053{
5054        if (ap->ops->port_stop)
5055                ap->ops->port_stop(ap);
5056        kfree(ap);
5057}
5058EXPORT_SYMBOL_GPL(ata_sas_port_destroy);
5059
5060/**
5061 *      ata_sas_slave_configure - Default slave_config routine for libata devices
5062 *      @sdev: SCSI device to configure
5063 *      @ap: ATA port to which SCSI device is attached
5064 *
5065 *      RETURNS:
5066 *      Zero.
5067 */
5068
5069int ata_sas_slave_configure(struct scsi_device *sdev, struct ata_port *ap)
5070{
5071        ata_scsi_sdev_config(sdev);
5072        ata_scsi_dev_config(sdev, ap->link.device);
5073        return 0;
5074}
5075EXPORT_SYMBOL_GPL(ata_sas_slave_configure);
5076
5077/**
5078 *      ata_sas_queuecmd - Issue SCSI cdb to libata-managed device
5079 *      @cmd: SCSI command to be sent
5080 *      @ap:    ATA port to which the command is being sent
5081 *
5082 *      RETURNS:
5083 *      Return value from __ata_scsi_queuecmd() if @cmd can be queued,
5084 *      0 otherwise.
5085 */
5086
5087int ata_sas_queuecmd(struct scsi_cmnd *cmd, struct ata_port *ap)
5088{
5089        int rc = 0;
5090
5091        ata_scsi_dump_cdb(ap, cmd);
5092
5093        if (likely(ata_dev_enabled(ap->link.device)))
5094                rc = __ata_scsi_queuecmd(cmd, ap->link.device);
5095        else {
5096                cmd->result = (DID_BAD_TARGET << 16);
5097                cmd->scsi_done(cmd);
5098        }
5099        return rc;
5100}
5101EXPORT_SYMBOL_GPL(ata_sas_queuecmd);
5102
5103int ata_sas_allocate_tag(struct ata_port *ap)
5104{
5105        unsigned int max_queue = ap->host->n_tags;
5106        unsigned int i, tag;
5107
5108        for (i = 0, tag = ap->sas_last_tag + 1; i < max_queue; i++, tag++) {
5109                tag = tag < max_queue ? tag : 0;
5110
5111                /* the last tag is reserved for internal command. */
5112                if (ata_tag_internal(tag))
5113                        continue;
5114
5115                if (!test_and_set_bit(tag, &ap->sas_tag_allocated)) {
5116                        ap->sas_last_tag = tag;
5117                        return tag;
5118                }
5119        }
5120        return -1;
5121}
5122
5123void ata_sas_free_tag(unsigned int tag, struct ata_port *ap)
5124{
5125        clear_bit(tag, &ap->sas_tag_allocated);
5126}
5127