Merge branch 'for-linus' of git://neil.brown.name/md
[sfrench/cifs-2.6.git] / drivers / ata / libata-scsi.c
1 /*
2  *  libata-scsi.c - helper library for ATA
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
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/DocBook/libata.*
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 <scsi/scsi.h>
41 #include <scsi/scsi_host.h>
42 #include <scsi/scsi_cmnd.h>
43 #include <scsi/scsi_eh.h>
44 #include <scsi/scsi_device.h>
45 #include <scsi/scsi_tcq.h>
46 #include <scsi/scsi_transport.h>
47 #include <linux/libata.h>
48 #include <linux/hdreg.h>
49 #include <linux/uaccess.h>
50 #include <linux/suspend.h>
51 #include <asm/unaligned.h>
52
53 #include "libata.h"
54
55 #define SECTOR_SIZE             512
56 #define ATA_SCSI_RBUF_SIZE      4096
57
58 static DEFINE_SPINLOCK(ata_scsi_rbuf_lock);
59 static u8 ata_scsi_rbuf[ATA_SCSI_RBUF_SIZE];
60
61 typedef unsigned int (*ata_xlat_func_t)(struct ata_queued_cmd *qc);
62
63 static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
64                                         const struct scsi_device *scsidev);
65 static struct ata_device *ata_scsi_find_dev(struct ata_port *ap,
66                                             const struct scsi_device *scsidev);
67 static int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel,
68                               unsigned int id, unsigned int lun);
69
70
71 #define RW_RECOVERY_MPAGE 0x1
72 #define RW_RECOVERY_MPAGE_LEN 12
73 #define CACHE_MPAGE 0x8
74 #define CACHE_MPAGE_LEN 20
75 #define CONTROL_MPAGE 0xa
76 #define CONTROL_MPAGE_LEN 12
77 #define ALL_MPAGES 0x3f
78 #define ALL_SUB_MPAGES 0xff
79
80
81 static const u8 def_rw_recovery_mpage[RW_RECOVERY_MPAGE_LEN] = {
82         RW_RECOVERY_MPAGE,
83         RW_RECOVERY_MPAGE_LEN - 2,
84         (1 << 7),       /* AWRE */
85         0,              /* read retry count */
86         0, 0, 0, 0,
87         0,              /* write retry count */
88         0, 0, 0
89 };
90
91 static const u8 def_cache_mpage[CACHE_MPAGE_LEN] = {
92         CACHE_MPAGE,
93         CACHE_MPAGE_LEN - 2,
94         0,              /* contains WCE, needs to be 0 for logic */
95         0, 0, 0, 0, 0, 0, 0, 0, 0,
96         0,              /* contains DRA, needs to be 0 for logic */
97         0, 0, 0, 0, 0, 0, 0
98 };
99
100 static const u8 def_control_mpage[CONTROL_MPAGE_LEN] = {
101         CONTROL_MPAGE,
102         CONTROL_MPAGE_LEN - 2,
103         2,      /* DSENSE=0, GLTSD=1 */
104         0,      /* [QAM+QERR may be 1, see 05-359r1] */
105         0, 0, 0, 0, 0xff, 0xff,
106         0, 30   /* extended self test time, see 05-359r1 */
107 };
108
109 /*
110  * libata transport template.  libata doesn't do real transport stuff.
111  * It just needs the eh_timed_out hook.
112  */
113 static struct scsi_transport_template ata_scsi_transport_template = {
114         .eh_strategy_handler    = ata_scsi_error,
115         .eh_timed_out           = ata_scsi_timed_out,
116         .user_scan              = ata_scsi_user_scan,
117 };
118
119
120 static const struct {
121         enum link_pm    value;
122         const char      *name;
123 } link_pm_policy[] = {
124         { NOT_AVAILABLE, "max_performance" },
125         { MIN_POWER, "min_power" },
126         { MAX_PERFORMANCE, "max_performance" },
127         { MEDIUM_POWER, "medium_power" },
128 };
129
130 static const char *ata_scsi_lpm_get(enum link_pm policy)
131 {
132         int i;
133
134         for (i = 0; i < ARRAY_SIZE(link_pm_policy); i++)
135                 if (link_pm_policy[i].value == policy)
136                         return link_pm_policy[i].name;
137
138         return NULL;
139 }
140
141 static ssize_t ata_scsi_lpm_put(struct device *dev,
142                                 struct device_attribute *attr,
143                                 const char *buf, size_t count)
144 {
145         struct Scsi_Host *shost = class_to_shost(dev);
146         struct ata_port *ap = ata_shost_to_port(shost);
147         enum link_pm policy = 0;
148         int i;
149
150         /*
151          * we are skipping array location 0 on purpose - this
152          * is because a value of NOT_AVAILABLE is displayed
153          * to the user as max_performance, but when the user
154          * writes "max_performance", they actually want the
155          * value to match MAX_PERFORMANCE.
156          */
157         for (i = 1; i < ARRAY_SIZE(link_pm_policy); i++) {
158                 const int len = strlen(link_pm_policy[i].name);
159                 if (strncmp(link_pm_policy[i].name, buf, len) == 0) {
160                         policy = link_pm_policy[i].value;
161                         break;
162                 }
163         }
164         if (!policy)
165                 return -EINVAL;
166
167         ata_lpm_schedule(ap, policy);
168         return count;
169 }
170
171 static ssize_t
172 ata_scsi_lpm_show(struct device *dev, struct device_attribute *attr, char *buf)
173 {
174         struct Scsi_Host *shost = class_to_shost(dev);
175         struct ata_port *ap = ata_shost_to_port(shost);
176         const char *policy =
177                 ata_scsi_lpm_get(ap->pm_policy);
178
179         if (!policy)
180                 return -EINVAL;
181
182         return snprintf(buf, 23, "%s\n", policy);
183 }
184 DEVICE_ATTR(link_power_management_policy, S_IRUGO | S_IWUSR,
185                 ata_scsi_lpm_show, ata_scsi_lpm_put);
186 EXPORT_SYMBOL_GPL(dev_attr_link_power_management_policy);
187
188 static ssize_t ata_scsi_park_show(struct device *device,
189                                   struct device_attribute *attr, char *buf)
190 {
191         struct scsi_device *sdev = to_scsi_device(device);
192         struct ata_port *ap;
193         struct ata_link *link;
194         struct ata_device *dev;
195         unsigned long flags, now;
196         unsigned int uninitialized_var(msecs);
197         int rc = 0;
198
199         ap = ata_shost_to_port(sdev->host);
200
201         spin_lock_irqsave(ap->lock, flags);
202         dev = ata_scsi_find_dev(ap, sdev);
203         if (!dev) {
204                 rc = -ENODEV;
205                 goto unlock;
206         }
207         if (dev->flags & ATA_DFLAG_NO_UNLOAD) {
208                 rc = -EOPNOTSUPP;
209                 goto unlock;
210         }
211
212         link = dev->link;
213         now = jiffies;
214         if (ap->pflags & ATA_PFLAG_EH_IN_PROGRESS &&
215             link->eh_context.unloaded_mask & (1 << dev->devno) &&
216             time_after(dev->unpark_deadline, now))
217                 msecs = jiffies_to_msecs(dev->unpark_deadline - now);
218         else
219                 msecs = 0;
220
221 unlock:
222         spin_unlock_irq(ap->lock);
223
224         return rc ? rc : snprintf(buf, 20, "%u\n", msecs);
225 }
226
227 static ssize_t ata_scsi_park_store(struct device *device,
228                                    struct device_attribute *attr,
229                                    const char *buf, size_t len)
230 {
231         struct scsi_device *sdev = to_scsi_device(device);
232         struct ata_port *ap;
233         struct ata_device *dev;
234         long int input;
235         unsigned long flags;
236         int rc;
237
238         rc = strict_strtol(buf, 10, &input);
239         if (rc || input < -2)
240                 return -EINVAL;
241         if (input > ATA_TMOUT_MAX_PARK) {
242                 rc = -EOVERFLOW;
243                 input = ATA_TMOUT_MAX_PARK;
244         }
245
246         ap = ata_shost_to_port(sdev->host);
247
248         spin_lock_irqsave(ap->lock, flags);
249         dev = ata_scsi_find_dev(ap, sdev);
250         if (unlikely(!dev)) {
251                 rc = -ENODEV;
252                 goto unlock;
253         }
254         if (dev->class != ATA_DEV_ATA) {
255                 rc = -EOPNOTSUPP;
256                 goto unlock;
257         }
258
259         if (input >= 0) {
260                 if (dev->flags & ATA_DFLAG_NO_UNLOAD) {
261                         rc = -EOPNOTSUPP;
262                         goto unlock;
263                 }
264
265                 dev->unpark_deadline = ata_deadline(jiffies, input);
266                 dev->link->eh_info.dev_action[dev->devno] |= ATA_EH_PARK;
267                 ata_port_schedule_eh(ap);
268                 complete(&ap->park_req_pending);
269         } else {
270                 switch (input) {
271                 case -1:
272                         dev->flags &= ~ATA_DFLAG_NO_UNLOAD;
273                         break;
274                 case -2:
275                         dev->flags |= ATA_DFLAG_NO_UNLOAD;
276                         break;
277                 }
278         }
279 unlock:
280         spin_unlock_irqrestore(ap->lock, flags);
281
282         return rc ? rc : len;
283 }
284 DEVICE_ATTR(unload_heads, S_IRUGO | S_IWUSR,
285             ata_scsi_park_show, ata_scsi_park_store);
286 EXPORT_SYMBOL_GPL(dev_attr_unload_heads);
287
288 static void ata_scsi_set_sense(struct scsi_cmnd *cmd, u8 sk, u8 asc, u8 ascq)
289 {
290         cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
291
292         scsi_build_sense_buffer(0, cmd->sense_buffer, sk, asc, ascq);
293 }
294
295 static ssize_t
296 ata_scsi_em_message_store(struct device *dev, struct device_attribute *attr,
297                           const char *buf, size_t count)
298 {
299         struct Scsi_Host *shost = class_to_shost(dev);
300         struct ata_port *ap = ata_shost_to_port(shost);
301         if (ap->ops->em_store && (ap->flags & ATA_FLAG_EM))
302                 return ap->ops->em_store(ap, buf, count);
303         return -EINVAL;
304 }
305
306 static ssize_t
307 ata_scsi_em_message_show(struct device *dev, struct device_attribute *attr,
308                          char *buf)
309 {
310         struct Scsi_Host *shost = class_to_shost(dev);
311         struct ata_port *ap = ata_shost_to_port(shost);
312
313         if (ap->ops->em_show && (ap->flags & ATA_FLAG_EM))
314                 return ap->ops->em_show(ap, buf);
315         return -EINVAL;
316 }
317 DEVICE_ATTR(em_message, S_IRUGO | S_IWUSR,
318                 ata_scsi_em_message_show, ata_scsi_em_message_store);
319 EXPORT_SYMBOL_GPL(dev_attr_em_message);
320
321 static ssize_t
322 ata_scsi_em_message_type_show(struct device *dev, struct device_attribute *attr,
323                               char *buf)
324 {
325         struct Scsi_Host *shost = class_to_shost(dev);
326         struct ata_port *ap = ata_shost_to_port(shost);
327
328         return snprintf(buf, 23, "%d\n", ap->em_message_type);
329 }
330 DEVICE_ATTR(em_message_type, S_IRUGO,
331                   ata_scsi_em_message_type_show, NULL);
332 EXPORT_SYMBOL_GPL(dev_attr_em_message_type);
333
334 static ssize_t
335 ata_scsi_activity_show(struct device *dev, struct device_attribute *attr,
336                 char *buf)
337 {
338         struct scsi_device *sdev = to_scsi_device(dev);
339         struct ata_port *ap = ata_shost_to_port(sdev->host);
340         struct ata_device *atadev = ata_scsi_find_dev(ap, sdev);
341
342         if (ap->ops->sw_activity_show && (ap->flags & ATA_FLAG_SW_ACTIVITY))
343                 return ap->ops->sw_activity_show(atadev, buf);
344         return -EINVAL;
345 }
346
347 static ssize_t
348 ata_scsi_activity_store(struct device *dev, struct device_attribute *attr,
349         const char *buf, size_t count)
350 {
351         struct scsi_device *sdev = to_scsi_device(dev);
352         struct ata_port *ap = ata_shost_to_port(sdev->host);
353         struct ata_device *atadev = ata_scsi_find_dev(ap, sdev);
354         enum sw_activity val;
355         int rc;
356
357         if (ap->ops->sw_activity_store && (ap->flags & ATA_FLAG_SW_ACTIVITY)) {
358                 val = simple_strtoul(buf, NULL, 0);
359                 switch (val) {
360                 case OFF: case BLINK_ON: case BLINK_OFF:
361                         rc = ap->ops->sw_activity_store(atadev, val);
362                         if (!rc)
363                                 return count;
364                         else
365                                 return rc;
366                 }
367         }
368         return -EINVAL;
369 }
370 DEVICE_ATTR(sw_activity, S_IWUSR | S_IRUGO, ata_scsi_activity_show,
371                         ata_scsi_activity_store);
372 EXPORT_SYMBOL_GPL(dev_attr_sw_activity);
373
374 struct device_attribute *ata_common_sdev_attrs[] = {
375         &dev_attr_unload_heads,
376         NULL
377 };
378 EXPORT_SYMBOL_GPL(ata_common_sdev_attrs);
379
380 static void ata_scsi_invalid_field(struct scsi_cmnd *cmd,
381                                    void (*done)(struct scsi_cmnd *))
382 {
383         ata_scsi_set_sense(cmd, ILLEGAL_REQUEST, 0x24, 0x0);
384         /* "Invalid field in cbd" */
385         done(cmd);
386 }
387
388 /**
389  *      ata_std_bios_param - generic bios head/sector/cylinder calculator used by sd.
390  *      @sdev: SCSI device for which BIOS geometry is to be determined
391  *      @bdev: block device associated with @sdev
392  *      @capacity: capacity of SCSI device
393  *      @geom: location to which geometry will be output
394  *
395  *      Generic bios head/sector/cylinder calculator
396  *      used by sd. Most BIOSes nowadays expect a XXX/255/16  (CHS)
397  *      mapping. Some situations may arise where the disk is not
398  *      bootable if this is not used.
399  *
400  *      LOCKING:
401  *      Defined by the SCSI layer.  We don't really care.
402  *
403  *      RETURNS:
404  *      Zero.
405  */
406 int ata_std_bios_param(struct scsi_device *sdev, struct block_device *bdev,
407                        sector_t capacity, int geom[])
408 {
409         geom[0] = 255;
410         geom[1] = 63;
411         sector_div(capacity, 255*63);
412         geom[2] = capacity;
413
414         return 0;
415 }
416
417 /**
418  *      ata_scsi_unlock_native_capacity - unlock native capacity
419  *      @sdev: SCSI device to adjust device capacity for
420  *
421  *      This function is called if a partition on @sdev extends beyond
422  *      the end of the device.  It requests EH to unlock HPA.
423  *
424  *      LOCKING:
425  *      Defined by the SCSI layer.  Might sleep.
426  */
427 void ata_scsi_unlock_native_capacity(struct scsi_device *sdev)
428 {
429         struct ata_port *ap = ata_shost_to_port(sdev->host);
430         struct ata_device *dev;
431         unsigned long flags;
432
433         spin_lock_irqsave(ap->lock, flags);
434
435         dev = ata_scsi_find_dev(ap, sdev);
436         if (dev && dev->n_sectors < dev->n_native_sectors) {
437                 dev->flags |= ATA_DFLAG_UNLOCK_HPA;
438                 dev->link->eh_info.action |= ATA_EH_RESET;
439                 ata_port_schedule_eh(ap);
440         }
441
442         spin_unlock_irqrestore(ap->lock, flags);
443         ata_port_wait_eh(ap);
444 }
445
446 /**
447  *      ata_get_identity - Handler for HDIO_GET_IDENTITY ioctl
448  *      @ap: target port
449  *      @sdev: SCSI device to get identify data for
450  *      @arg: User buffer area for identify data
451  *
452  *      LOCKING:
453  *      Defined by the SCSI layer.  We don't really care.
454  *
455  *      RETURNS:
456  *      Zero on success, negative errno on error.
457  */
458 static int ata_get_identity(struct ata_port *ap, struct scsi_device *sdev,
459                             void __user *arg)
460 {
461         struct ata_device *dev = ata_scsi_find_dev(ap, sdev);
462         u16 __user *dst = arg;
463         char buf[40];
464
465         if (!dev)
466                 return -ENOMSG;
467
468         if (copy_to_user(dst, dev->id, ATA_ID_WORDS * sizeof(u16)))
469                 return -EFAULT;
470
471         ata_id_string(dev->id, buf, ATA_ID_PROD, ATA_ID_PROD_LEN);
472         if (copy_to_user(dst + ATA_ID_PROD, buf, ATA_ID_PROD_LEN))
473                 return -EFAULT;
474
475         ata_id_string(dev->id, buf, ATA_ID_FW_REV, ATA_ID_FW_REV_LEN);
476         if (copy_to_user(dst + ATA_ID_FW_REV, buf, ATA_ID_FW_REV_LEN))
477                 return -EFAULT;
478
479         ata_id_string(dev->id, buf, ATA_ID_SERNO, ATA_ID_SERNO_LEN);
480         if (copy_to_user(dst + ATA_ID_SERNO, buf, ATA_ID_SERNO_LEN))
481                 return -EFAULT;
482
483         return 0;
484 }
485
486 /**
487  *      ata_cmd_ioctl - Handler for HDIO_DRIVE_CMD ioctl
488  *      @scsidev: Device to which we are issuing command
489  *      @arg: User provided data for issuing command
490  *
491  *      LOCKING:
492  *      Defined by the SCSI layer.  We don't really care.
493  *
494  *      RETURNS:
495  *      Zero on success, negative errno on error.
496  */
497 int ata_cmd_ioctl(struct scsi_device *scsidev, void __user *arg)
498 {
499         int rc = 0;
500         u8 scsi_cmd[MAX_COMMAND_SIZE];
501         u8 args[4], *argbuf = NULL, *sensebuf = NULL;
502         int argsize = 0;
503         enum dma_data_direction data_dir;
504         int cmd_result;
505
506         if (arg == NULL)
507                 return -EINVAL;
508
509         if (copy_from_user(args, arg, sizeof(args)))
510                 return -EFAULT;
511
512         sensebuf = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
513         if (!sensebuf)
514                 return -ENOMEM;
515
516         memset(scsi_cmd, 0, sizeof(scsi_cmd));
517
518         if (args[3]) {
519                 argsize = SECTOR_SIZE * args[3];
520                 argbuf = kmalloc(argsize, GFP_KERNEL);
521                 if (argbuf == NULL) {
522                         rc = -ENOMEM;
523                         goto error;
524                 }
525
526                 scsi_cmd[1]  = (4 << 1); /* PIO Data-in */
527                 scsi_cmd[2]  = 0x0e;     /* no off.line or cc, read from dev,
528                                             block count in sector count field */
529                 data_dir = DMA_FROM_DEVICE;
530         } else {
531                 scsi_cmd[1]  = (3 << 1); /* Non-data */
532                 scsi_cmd[2]  = 0x20;     /* cc but no off.line or data xfer */
533                 data_dir = DMA_NONE;
534         }
535
536         scsi_cmd[0] = ATA_16;
537
538         scsi_cmd[4] = args[2];
539         if (args[0] == ATA_CMD_SMART) { /* hack -- ide driver does this too */
540                 scsi_cmd[6]  = args[3];
541                 scsi_cmd[8]  = args[1];
542                 scsi_cmd[10] = 0x4f;
543                 scsi_cmd[12] = 0xc2;
544         } else {
545                 scsi_cmd[6]  = args[1];
546         }
547         scsi_cmd[14] = args[0];
548
549         /* Good values for timeout and retries?  Values below
550            from scsi_ioctl_send_command() for default case... */
551         cmd_result = scsi_execute(scsidev, scsi_cmd, data_dir, argbuf, argsize,
552                                   sensebuf, (10*HZ), 5, 0, NULL);
553
554         if (driver_byte(cmd_result) == DRIVER_SENSE) {/* sense data available */
555                 u8 *desc = sensebuf + 8;
556                 cmd_result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
557
558                 /* If we set cc then ATA pass-through will cause a
559                  * check condition even if no error. Filter that. */
560                 if (cmd_result & SAM_STAT_CHECK_CONDITION) {
561                         struct scsi_sense_hdr sshdr;
562                         scsi_normalize_sense(sensebuf, SCSI_SENSE_BUFFERSIZE,
563                                              &sshdr);
564                         if (sshdr.sense_key == 0 &&
565                             sshdr.asc == 0 && sshdr.ascq == 0)
566                                 cmd_result &= ~SAM_STAT_CHECK_CONDITION;
567                 }
568
569                 /* Send userspace a few ATA registers (same as drivers/ide) */
570                 if (sensebuf[0] == 0x72 &&      /* format is "descriptor" */
571                     desc[0] == 0x09) {          /* code is "ATA Descriptor" */
572                         args[0] = desc[13];     /* status */
573                         args[1] = desc[3];      /* error */
574                         args[2] = desc[5];      /* sector count (0:7) */
575                         if (copy_to_user(arg, args, sizeof(args)))
576                                 rc = -EFAULT;
577                 }
578         }
579
580
581         if (cmd_result) {
582                 rc = -EIO;
583                 goto error;
584         }
585
586         if ((argbuf)
587          && copy_to_user(arg + sizeof(args), argbuf, argsize))
588                 rc = -EFAULT;
589 error:
590         kfree(sensebuf);
591         kfree(argbuf);
592         return rc;
593 }
594
595 /**
596  *      ata_task_ioctl - Handler for HDIO_DRIVE_TASK ioctl
597  *      @scsidev: Device to which we are issuing command
598  *      @arg: User provided data for issuing command
599  *
600  *      LOCKING:
601  *      Defined by the SCSI layer.  We don't really care.
602  *
603  *      RETURNS:
604  *      Zero on success, negative errno on error.
605  */
606 int ata_task_ioctl(struct scsi_device *scsidev, void __user *arg)
607 {
608         int rc = 0;
609         u8 scsi_cmd[MAX_COMMAND_SIZE];
610         u8 args[7], *sensebuf = NULL;
611         int cmd_result;
612
613         if (arg == NULL)
614                 return -EINVAL;
615
616         if (copy_from_user(args, arg, sizeof(args)))
617                 return -EFAULT;
618
619         sensebuf = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
620         if (!sensebuf)
621                 return -ENOMEM;
622
623         memset(scsi_cmd, 0, sizeof(scsi_cmd));
624         scsi_cmd[0]  = ATA_16;
625         scsi_cmd[1]  = (3 << 1); /* Non-data */
626         scsi_cmd[2]  = 0x20;     /* cc but no off.line or data xfer */
627         scsi_cmd[4]  = args[1];
628         scsi_cmd[6]  = args[2];
629         scsi_cmd[8]  = args[3];
630         scsi_cmd[10] = args[4];
631         scsi_cmd[12] = args[5];
632         scsi_cmd[13] = args[6] & 0x4f;
633         scsi_cmd[14] = args[0];
634
635         /* Good values for timeout and retries?  Values below
636            from scsi_ioctl_send_command() for default case... */
637         cmd_result = scsi_execute(scsidev, scsi_cmd, DMA_NONE, NULL, 0,
638                                 sensebuf, (10*HZ), 5, 0, NULL);
639
640         if (driver_byte(cmd_result) == DRIVER_SENSE) {/* sense data available */
641                 u8 *desc = sensebuf + 8;
642                 cmd_result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
643
644                 /* If we set cc then ATA pass-through will cause a
645                  * check condition even if no error. Filter that. */
646                 if (cmd_result & SAM_STAT_CHECK_CONDITION) {
647                         struct scsi_sense_hdr sshdr;
648                         scsi_normalize_sense(sensebuf, SCSI_SENSE_BUFFERSIZE,
649                                                 &sshdr);
650                         if (sshdr.sense_key == 0 &&
651                                 sshdr.asc == 0 && sshdr.ascq == 0)
652                                 cmd_result &= ~SAM_STAT_CHECK_CONDITION;
653                 }
654
655                 /* Send userspace ATA registers */
656                 if (sensebuf[0] == 0x72 &&      /* format is "descriptor" */
657                                 desc[0] == 0x09) {/* code is "ATA Descriptor" */
658                         args[0] = desc[13];     /* status */
659                         args[1] = desc[3];      /* error */
660                         args[2] = desc[5];      /* sector count (0:7) */
661                         args[3] = desc[7];      /* lbal */
662                         args[4] = desc[9];      /* lbam */
663                         args[5] = desc[11];     /* lbah */
664                         args[6] = desc[12];     /* select */
665                         if (copy_to_user(arg, args, sizeof(args)))
666                                 rc = -EFAULT;
667                 }
668         }
669
670         if (cmd_result) {
671                 rc = -EIO;
672                 goto error;
673         }
674
675  error:
676         kfree(sensebuf);
677         return rc;
678 }
679
680 static int ata_ioc32(struct ata_port *ap)
681 {
682         if (ap->flags & ATA_FLAG_PIO_DMA)
683                 return 1;
684         if (ap->pflags & ATA_PFLAG_PIO32)
685                 return 1;
686         return 0;
687 }
688
689 int ata_sas_scsi_ioctl(struct ata_port *ap, struct scsi_device *scsidev,
690                      int cmd, void __user *arg)
691 {
692         int val = -EINVAL, rc = -EINVAL;
693         unsigned long flags;
694
695         switch (cmd) {
696         case ATA_IOC_GET_IO32:
697                 spin_lock_irqsave(ap->lock, flags);
698                 val = ata_ioc32(ap);
699                 spin_unlock_irqrestore(ap->lock, flags);
700                 if (copy_to_user(arg, &val, 1))
701                         return -EFAULT;
702                 return 0;
703
704         case ATA_IOC_SET_IO32:
705                 val = (unsigned long) arg;
706                 rc = 0;
707                 spin_lock_irqsave(ap->lock, flags);
708                 if (ap->pflags & ATA_PFLAG_PIO32CHANGE) {
709                         if (val)
710                                 ap->pflags |= ATA_PFLAG_PIO32;
711                         else
712                                 ap->pflags &= ~ATA_PFLAG_PIO32;
713                 } else {
714                         if (val != ata_ioc32(ap))
715                                 rc = -EINVAL;
716                 }
717                 spin_unlock_irqrestore(ap->lock, flags);
718                 return rc;
719
720         case HDIO_GET_IDENTITY:
721                 return ata_get_identity(ap, scsidev, arg);
722
723         case HDIO_DRIVE_CMD:
724                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
725                         return -EACCES;
726                 return ata_cmd_ioctl(scsidev, arg);
727
728         case HDIO_DRIVE_TASK:
729                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
730                         return -EACCES;
731                 return ata_task_ioctl(scsidev, arg);
732
733         default:
734                 rc = -ENOTTY;
735                 break;
736         }
737
738         return rc;
739 }
740 EXPORT_SYMBOL_GPL(ata_sas_scsi_ioctl);
741
742 int ata_scsi_ioctl(struct scsi_device *scsidev, int cmd, void __user *arg)
743 {
744         return ata_sas_scsi_ioctl(ata_shost_to_port(scsidev->host),
745                                 scsidev, cmd, arg);
746 }
747 EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
748
749 /**
750  *      ata_scsi_qc_new - acquire new ata_queued_cmd reference
751  *      @dev: ATA device to which the new command is attached
752  *      @cmd: SCSI command that originated this ATA command
753  *      @done: SCSI command completion function
754  *
755  *      Obtain a reference to an unused ata_queued_cmd structure,
756  *      which is the basic libata structure representing a single
757  *      ATA command sent to the hardware.
758  *
759  *      If a command was available, fill in the SCSI-specific
760  *      portions of the structure with information on the
761  *      current command.
762  *
763  *      LOCKING:
764  *      spin_lock_irqsave(host lock)
765  *
766  *      RETURNS:
767  *      Command allocated, or %NULL if none available.
768  */
769 static struct ata_queued_cmd *ata_scsi_qc_new(struct ata_device *dev,
770                                               struct scsi_cmnd *cmd,
771                                               void (*done)(struct scsi_cmnd *))
772 {
773         struct ata_queued_cmd *qc;
774
775         qc = ata_qc_new_init(dev);
776         if (qc) {
777                 qc->scsicmd = cmd;
778                 qc->scsidone = done;
779
780                 qc->sg = scsi_sglist(cmd);
781                 qc->n_elem = scsi_sg_count(cmd);
782         } else {
783                 cmd->result = (DID_OK << 16) | (QUEUE_FULL << 1);
784                 done(cmd);
785         }
786
787         return qc;
788 }
789
790 static void ata_qc_set_pc_nbytes(struct ata_queued_cmd *qc)
791 {
792         struct scsi_cmnd *scmd = qc->scsicmd;
793
794         qc->extrabytes = scmd->request->extra_len;
795         qc->nbytes = scsi_bufflen(scmd) + qc->extrabytes;
796 }
797
798 /**
799  *      ata_dump_status - user friendly display of error info
800  *      @id: id of the port in question
801  *      @tf: ptr to filled out taskfile
802  *
803  *      Decode and dump the ATA error/status registers for the user so
804  *      that they have some idea what really happened at the non
805  *      make-believe layer.
806  *
807  *      LOCKING:
808  *      inherited from caller
809  */
810 static void ata_dump_status(unsigned id, struct ata_taskfile *tf)
811 {
812         u8 stat = tf->command, err = tf->feature;
813
814         printk(KERN_WARNING "ata%u: status=0x%02x { ", id, stat);
815         if (stat & ATA_BUSY) {
816                 printk("Busy }\n");     /* Data is not valid in this case */
817         } else {
818                 if (stat & 0x40)        printk("DriveReady ");
819                 if (stat & 0x20)        printk("DeviceFault ");
820                 if (stat & 0x10)        printk("SeekComplete ");
821                 if (stat & 0x08)        printk("DataRequest ");
822                 if (stat & 0x04)        printk("CorrectedError ");
823                 if (stat & 0x02)        printk("Index ");
824                 if (stat & 0x01)        printk("Error ");
825                 printk("}\n");
826
827                 if (err) {
828                         printk(KERN_WARNING "ata%u: error=0x%02x { ", id, err);
829                         if (err & 0x04)         printk("DriveStatusError ");
830                         if (err & 0x80) {
831                                 if (err & 0x04) printk("BadCRC ");
832                                 else            printk("Sector ");
833                         }
834                         if (err & 0x40)         printk("UncorrectableError ");
835                         if (err & 0x10)         printk("SectorIdNotFound ");
836                         if (err & 0x02)         printk("TrackZeroNotFound ");
837                         if (err & 0x01)         printk("AddrMarkNotFound ");
838                         printk("}\n");
839                 }
840         }
841 }
842
843 /**
844  *      ata_to_sense_error - convert ATA error to SCSI error
845  *      @id: ATA device number
846  *      @drv_stat: value contained in ATA status register
847  *      @drv_err: value contained in ATA error register
848  *      @sk: the sense key we'll fill out
849  *      @asc: the additional sense code we'll fill out
850  *      @ascq: the additional sense code qualifier we'll fill out
851  *      @verbose: be verbose
852  *
853  *      Converts an ATA error into a SCSI error.  Fill out pointers to
854  *      SK, ASC, and ASCQ bytes for later use in fixed or descriptor
855  *      format sense blocks.
856  *
857  *      LOCKING:
858  *      spin_lock_irqsave(host lock)
859  */
860 static void ata_to_sense_error(unsigned id, u8 drv_stat, u8 drv_err, u8 *sk,
861                                u8 *asc, u8 *ascq, int verbose)
862 {
863         int i;
864
865         /* Based on the 3ware driver translation table */
866         static const unsigned char sense_table[][4] = {
867                 /* BBD|ECC|ID|MAR */
868                 {0xd1,          ABORTED_COMMAND, 0x00, 0x00},   // Device busy                  Aborted command
869                 /* BBD|ECC|ID */
870                 {0xd0,          ABORTED_COMMAND, 0x00, 0x00},   // Device busy                  Aborted command
871                 /* ECC|MC|MARK */
872                 {0x61,          HARDWARE_ERROR, 0x00, 0x00},    // Device fault                 Hardware error
873                 /* ICRC|ABRT */         /* NB: ICRC & !ABRT is BBD */
874                 {0x84,          ABORTED_COMMAND, 0x47, 0x00},   // Data CRC error               SCSI parity error
875                 /* MC|ID|ABRT|TRK0|MARK */
876                 {0x37,          NOT_READY, 0x04, 0x00},         // Unit offline                 Not ready
877                 /* MCR|MARK */
878                 {0x09,          NOT_READY, 0x04, 0x00},         // Unrecovered disk error       Not ready
879                 /*  Bad address mark */
880                 {0x01,          MEDIUM_ERROR, 0x13, 0x00},      // Address mark not found       Address mark not found for data field
881                 /* TRK0 */
882                 {0x02,          HARDWARE_ERROR, 0x00, 0x00},    // Track 0 not found              Hardware error
883                 /* Abort & !ICRC */
884                 {0x04,          ABORTED_COMMAND, 0x00, 0x00},   // Aborted command              Aborted command
885                 /* Media change request */
886                 {0x08,          NOT_READY, 0x04, 0x00},         // Media change request   FIXME: faking offline
887                 /* SRV */
888                 {0x10,          ABORTED_COMMAND, 0x14, 0x00},   // ID not found                 Recorded entity not found
889                 /* Media change */
890                 {0x08,          NOT_READY, 0x04, 0x00},         // Media change           FIXME: faking offline
891                 /* ECC */
892                 {0x40,          MEDIUM_ERROR, 0x11, 0x04},      // Uncorrectable ECC error      Unrecovered read error
893                 /* BBD - block marked bad */
894                 {0x80,          MEDIUM_ERROR, 0x11, 0x04},      // Block marked bad               Medium error, unrecovered read error
895                 {0xFF, 0xFF, 0xFF, 0xFF}, // END mark
896         };
897         static const unsigned char stat_table[][4] = {
898                 /* Must be first because BUSY means no other bits valid */
899                 {0x80,          ABORTED_COMMAND, 0x47, 0x00},   // Busy, fake parity for now
900                 {0x20,          HARDWARE_ERROR,  0x00, 0x00},   // Device fault
901                 {0x08,          ABORTED_COMMAND, 0x47, 0x00},   // Timed out in xfer, fake parity for now
902                 {0x04,          RECOVERED_ERROR, 0x11, 0x00},   // Recovered ECC error    Medium error, recovered
903                 {0xFF, 0xFF, 0xFF, 0xFF}, // END mark
904         };
905
906         /*
907          *      Is this an error we can process/parse
908          */
909         if (drv_stat & ATA_BUSY) {
910                 drv_err = 0;    /* Ignore the err bits, they're invalid */
911         }
912
913         if (drv_err) {
914                 /* Look for drv_err */
915                 for (i = 0; sense_table[i][0] != 0xFF; i++) {
916                         /* Look for best matches first */
917                         if ((sense_table[i][0] & drv_err) ==
918                             sense_table[i][0]) {
919                                 *sk = sense_table[i][1];
920                                 *asc = sense_table[i][2];
921                                 *ascq = sense_table[i][3];
922                                 goto translate_done;
923                         }
924                 }
925                 /* No immediate match */
926                 if (verbose)
927                         printk(KERN_WARNING "ata%u: no sense translation for "
928                                "error 0x%02x\n", id, drv_err);
929         }
930
931         /* Fall back to interpreting status bits */
932         for (i = 0; stat_table[i][0] != 0xFF; i++) {
933                 if (stat_table[i][0] & drv_stat) {
934                         *sk = stat_table[i][1];
935                         *asc = stat_table[i][2];
936                         *ascq = stat_table[i][3];
937                         goto translate_done;
938                 }
939         }
940         /* No error?  Undecoded? */
941         if (verbose)
942                 printk(KERN_WARNING "ata%u: no sense translation for "
943                        "status: 0x%02x\n", id, drv_stat);
944
945         /* We need a sensible error return here, which is tricky, and one
946            that won't cause people to do things like return a disk wrongly */
947         *sk = ABORTED_COMMAND;
948         *asc = 0x00;
949         *ascq = 0x00;
950
951  translate_done:
952         if (verbose)
953                 printk(KERN_ERR "ata%u: translated ATA stat/err 0x%02x/%02x "
954                        "to SCSI SK/ASC/ASCQ 0x%x/%02x/%02x\n",
955                        id, drv_stat, drv_err, *sk, *asc, *ascq);
956         return;
957 }
958
959 /*
960  *      ata_gen_passthru_sense - Generate check condition sense block.
961  *      @qc: Command that completed.
962  *
963  *      This function is specific to the ATA descriptor format sense
964  *      block specified for the ATA pass through commands.  Regardless
965  *      of whether the command errored or not, return a sense
966  *      block. Copy all controller registers into the sense
967  *      block. Clear sense key, ASC & ASCQ if there is no error.
968  *
969  *      LOCKING:
970  *      None.
971  */
972 static void ata_gen_passthru_sense(struct ata_queued_cmd *qc)
973 {
974         struct scsi_cmnd *cmd = qc->scsicmd;
975         struct ata_taskfile *tf = &qc->result_tf;
976         unsigned char *sb = cmd->sense_buffer;
977         unsigned char *desc = sb + 8;
978         int verbose = qc->ap->ops->error_handler == NULL;
979
980         memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
981
982         cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
983
984         /*
985          * Use ata_to_sense_error() to map status register bits
986          * onto sense key, asc & ascq.
987          */
988         if (qc->err_mask ||
989             tf->command & (ATA_BUSY | ATA_DF | ATA_ERR | ATA_DRQ)) {
990                 ata_to_sense_error(qc->ap->print_id, tf->command, tf->feature,
991                                    &sb[1], &sb[2], &sb[3], verbose);
992                 sb[1] &= 0x0f;
993         }
994
995         /*
996          * Sense data is current and format is descriptor.
997          */
998         sb[0] = 0x72;
999
1000         desc[0] = 0x09;
1001
1002         /* set length of additional sense data */
1003         sb[7] = 14;
1004         desc[1] = 12;
1005
1006         /*
1007          * Copy registers into sense buffer.
1008          */
1009         desc[2] = 0x00;
1010         desc[3] = tf->feature;  /* == error reg */
1011         desc[5] = tf->nsect;
1012         desc[7] = tf->lbal;
1013         desc[9] = tf->lbam;
1014         desc[11] = tf->lbah;
1015         desc[12] = tf->device;
1016         desc[13] = tf->command; /* == status reg */
1017
1018         /*
1019          * Fill in Extend bit, and the high order bytes
1020          * if applicable.
1021          */
1022         if (tf->flags & ATA_TFLAG_LBA48) {
1023                 desc[2] |= 0x01;
1024                 desc[4] = tf->hob_nsect;
1025                 desc[6] = tf->hob_lbal;
1026                 desc[8] = tf->hob_lbam;
1027                 desc[10] = tf->hob_lbah;
1028         }
1029 }
1030
1031 /**
1032  *      ata_gen_ata_sense - generate a SCSI fixed sense block
1033  *      @qc: Command that we are erroring out
1034  *
1035  *      Generate sense block for a failed ATA command @qc.  Descriptor
1036  *      format is used to accomodate LBA48 block address.
1037  *
1038  *      LOCKING:
1039  *      None.
1040  */
1041 static void ata_gen_ata_sense(struct ata_queued_cmd *qc)
1042 {
1043         struct ata_device *dev = qc->dev;
1044         struct scsi_cmnd *cmd = qc->scsicmd;
1045         struct ata_taskfile *tf = &qc->result_tf;
1046         unsigned char *sb = cmd->sense_buffer;
1047         unsigned char *desc = sb + 8;
1048         int verbose = qc->ap->ops->error_handler == NULL;
1049         u64 block;
1050
1051         memset(sb, 0, SCSI_SENSE_BUFFERSIZE);
1052
1053         cmd->result = (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
1054
1055         /* sense data is current and format is descriptor */
1056         sb[0] = 0x72;
1057
1058         /* Use ata_to_sense_error() to map status register bits
1059          * onto sense key, asc & ascq.
1060          */
1061         if (qc->err_mask ||
1062             tf->command & (ATA_BUSY | ATA_DF | ATA_ERR | ATA_DRQ)) {
1063                 ata_to_sense_error(qc->ap->print_id, tf->command, tf->feature,
1064                                    &sb[1], &sb[2], &sb[3], verbose);
1065                 sb[1] &= 0x0f;
1066         }
1067
1068         block = ata_tf_read_block(&qc->result_tf, dev);
1069
1070         /* information sense data descriptor */
1071         sb[7] = 12;
1072         desc[0] = 0x00;
1073         desc[1] = 10;
1074
1075         desc[2] |= 0x80;        /* valid */
1076         desc[6] = block >> 40;
1077         desc[7] = block >> 32;
1078         desc[8] = block >> 24;
1079         desc[9] = block >> 16;
1080         desc[10] = block >> 8;
1081         desc[11] = block;
1082 }
1083
1084 static void ata_scsi_sdev_config(struct scsi_device *sdev)
1085 {
1086         sdev->use_10_for_rw = 1;
1087         sdev->use_10_for_ms = 1;
1088
1089         /* Schedule policy is determined by ->qc_defer() callback and
1090          * it needs to see every deferred qc.  Set dev_blocked to 1 to
1091          * prevent SCSI midlayer from automatically deferring
1092          * requests.
1093          */
1094         sdev->max_device_blocked = 1;
1095 }
1096
1097 /**
1098  *      atapi_drain_needed - Check whether data transfer may overflow
1099  *      @rq: request to be checked
1100  *
1101  *      ATAPI commands which transfer variable length data to host
1102  *      might overflow due to application error or hardare bug.  This
1103  *      function checks whether overflow should be drained and ignored
1104  *      for @request.
1105  *
1106  *      LOCKING:
1107  *      None.
1108  *
1109  *      RETURNS:
1110  *      1 if ; otherwise, 0.
1111  */
1112 static int atapi_drain_needed(struct request *rq)
1113 {
1114         if (likely(rq->cmd_type != REQ_TYPE_BLOCK_PC))
1115                 return 0;
1116
1117         if (!blk_rq_bytes(rq) || (rq->cmd_flags & REQ_WRITE))
1118                 return 0;
1119
1120         return atapi_cmd_type(rq->cmd[0]) == ATAPI_MISC;
1121 }
1122
1123 static int ata_scsi_dev_config(struct scsi_device *sdev,
1124                                struct ata_device *dev)
1125 {
1126         if (!ata_id_has_unload(dev->id))
1127                 dev->flags |= ATA_DFLAG_NO_UNLOAD;
1128
1129         /* configure max sectors */
1130         blk_queue_max_hw_sectors(sdev->request_queue, dev->max_sectors);
1131
1132         if (dev->class == ATA_DEV_ATAPI) {
1133                 struct request_queue *q = sdev->request_queue;
1134                 void *buf;
1135
1136                 /* set the min alignment and padding */
1137                 blk_queue_update_dma_alignment(sdev->request_queue,
1138                                                ATA_DMA_PAD_SZ - 1);
1139                 blk_queue_update_dma_pad(sdev->request_queue,
1140                                          ATA_DMA_PAD_SZ - 1);
1141
1142                 /* configure draining */
1143                 buf = kmalloc(ATAPI_MAX_DRAIN, q->bounce_gfp | GFP_KERNEL);
1144                 if (!buf) {
1145                         ata_dev_printk(dev, KERN_ERR,
1146                                        "drain buffer allocation failed\n");
1147                         return -ENOMEM;
1148                 }
1149
1150                 blk_queue_dma_drain(q, atapi_drain_needed, buf, ATAPI_MAX_DRAIN);
1151         } else {
1152                 /* ATA devices must be sector aligned */
1153                 blk_queue_update_dma_alignment(sdev->request_queue,
1154                                                ATA_SECT_SIZE - 1);
1155                 sdev->manage_start_stop = 1;
1156         }
1157
1158         if (dev->flags & ATA_DFLAG_AN)
1159                 set_bit(SDEV_EVT_MEDIA_CHANGE, sdev->supported_events);
1160
1161         if (dev->flags & ATA_DFLAG_NCQ) {
1162                 int depth;
1163
1164                 depth = min(sdev->host->can_queue, ata_id_queue_depth(dev->id));
1165                 depth = min(ATA_MAX_QUEUE - 1, depth);
1166                 scsi_adjust_queue_depth(sdev, MSG_SIMPLE_TAG, depth);
1167         }
1168
1169         return 0;
1170 }
1171
1172 /**
1173  *      ata_scsi_slave_config - Set SCSI device attributes
1174  *      @sdev: SCSI device to examine
1175  *
1176  *      This is called before we actually start reading
1177  *      and writing to the device, to configure certain
1178  *      SCSI mid-layer behaviors.
1179  *
1180  *      LOCKING:
1181  *      Defined by SCSI layer.  We don't really care.
1182  */
1183
1184 int ata_scsi_slave_config(struct scsi_device *sdev)
1185 {
1186         struct ata_port *ap = ata_shost_to_port(sdev->host);
1187         struct ata_device *dev = __ata_scsi_find_dev(ap, sdev);
1188         int rc = 0;
1189
1190         ata_scsi_sdev_config(sdev);
1191
1192         if (dev)
1193                 rc = ata_scsi_dev_config(sdev, dev);
1194
1195         return rc;
1196 }
1197
1198 /**
1199  *      ata_scsi_slave_destroy - SCSI device is about to be destroyed
1200  *      @sdev: SCSI device to be destroyed
1201  *
1202  *      @sdev is about to be destroyed for hot/warm unplugging.  If
1203  *      this unplugging was initiated by libata as indicated by NULL
1204  *      dev->sdev, this function doesn't have to do anything.
1205  *      Otherwise, SCSI layer initiated warm-unplug is in progress.
1206  *      Clear dev->sdev, schedule the device for ATA detach and invoke
1207  *      EH.
1208  *
1209  *      LOCKING:
1210  *      Defined by SCSI layer.  We don't really care.
1211  */
1212 void ata_scsi_slave_destroy(struct scsi_device *sdev)
1213 {
1214         struct ata_port *ap = ata_shost_to_port(sdev->host);
1215         struct request_queue *q = sdev->request_queue;
1216         unsigned long flags;
1217         struct ata_device *dev;
1218
1219         if (!ap->ops->error_handler)
1220                 return;
1221
1222         spin_lock_irqsave(ap->lock, flags);
1223         dev = __ata_scsi_find_dev(ap, sdev);
1224         if (dev && dev->sdev) {
1225                 /* SCSI device already in CANCEL state, no need to offline it */
1226                 dev->sdev = NULL;
1227                 dev->flags |= ATA_DFLAG_DETACH;
1228                 ata_port_schedule_eh(ap);
1229         }
1230         spin_unlock_irqrestore(ap->lock, flags);
1231
1232         kfree(q->dma_drain_buffer);
1233         q->dma_drain_buffer = NULL;
1234         q->dma_drain_size = 0;
1235 }
1236
1237 /**
1238  *      ata_scsi_change_queue_depth - SCSI callback for queue depth config
1239  *      @sdev: SCSI device to configure queue depth for
1240  *      @queue_depth: new queue depth
1241  *      @reason: calling context
1242  *
1243  *      This is libata standard hostt->change_queue_depth callback.
1244  *      SCSI will call into this callback when user tries to set queue
1245  *      depth via sysfs.
1246  *
1247  *      LOCKING:
1248  *      SCSI layer (we don't care)
1249  *
1250  *      RETURNS:
1251  *      Newly configured queue depth.
1252  */
1253 int ata_scsi_change_queue_depth(struct scsi_device *sdev, int queue_depth,
1254                                 int reason)
1255 {
1256         struct ata_port *ap = ata_shost_to_port(sdev->host);
1257         struct ata_device *dev;
1258         unsigned long flags;
1259
1260         if (reason != SCSI_QDEPTH_DEFAULT)
1261                 return -EOPNOTSUPP;
1262
1263         if (queue_depth < 1 || queue_depth == sdev->queue_depth)
1264                 return sdev->queue_depth;
1265
1266         dev = ata_scsi_find_dev(ap, sdev);
1267         if (!dev || !ata_dev_enabled(dev))
1268                 return sdev->queue_depth;
1269
1270         /* NCQ enabled? */
1271         spin_lock_irqsave(ap->lock, flags);
1272         dev->flags &= ~ATA_DFLAG_NCQ_OFF;
1273         if (queue_depth == 1 || !ata_ncq_enabled(dev)) {
1274                 dev->flags |= ATA_DFLAG_NCQ_OFF;
1275                 queue_depth = 1;
1276         }
1277         spin_unlock_irqrestore(ap->lock, flags);
1278
1279         /* limit and apply queue depth */
1280         queue_depth = min(queue_depth, sdev->host->can_queue);
1281         queue_depth = min(queue_depth, ata_id_queue_depth(dev->id));
1282         queue_depth = min(queue_depth, ATA_MAX_QUEUE - 1);
1283
1284         if (sdev->queue_depth == queue_depth)
1285                 return -EINVAL;
1286
1287         scsi_adjust_queue_depth(sdev, MSG_SIMPLE_TAG, queue_depth);
1288         return queue_depth;
1289 }
1290
1291 /**
1292  *      ata_scsi_start_stop_xlat - Translate SCSI START STOP UNIT command
1293  *      @qc: Storage for translated ATA taskfile
1294  *
1295  *      Sets up an ATA taskfile to issue STANDBY (to stop) or READ VERIFY
1296  *      (to start). Perhaps these commands should be preceded by
1297  *      CHECK POWER MODE to see what power mode the device is already in.
1298  *      [See SAT revision 5 at www.t10.org]
1299  *
1300  *      LOCKING:
1301  *      spin_lock_irqsave(host lock)
1302  *
1303  *      RETURNS:
1304  *      Zero on success, non-zero on error.
1305  */
1306 static unsigned int ata_scsi_start_stop_xlat(struct ata_queued_cmd *qc)
1307 {
1308         struct scsi_cmnd *scmd = qc->scsicmd;
1309         struct ata_taskfile *tf = &qc->tf;
1310         const u8 *cdb = scmd->cmnd;
1311
1312         if (scmd->cmd_len < 5)
1313                 goto invalid_fld;
1314
1315         tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1316         tf->protocol = ATA_PROT_NODATA;
1317         if (cdb[1] & 0x1) {
1318                 ;       /* ignore IMMED bit, violates sat-r05 */
1319         }
1320         if (cdb[4] & 0x2)
1321                 goto invalid_fld;       /* LOEJ bit set not supported */
1322         if (((cdb[4] >> 4) & 0xf) != 0)
1323                 goto invalid_fld;       /* power conditions not supported */
1324
1325         if (cdb[4] & 0x1) {
1326                 tf->nsect = 1;  /* 1 sector, lba=0 */
1327
1328                 if (qc->dev->flags & ATA_DFLAG_LBA) {
1329                         tf->flags |= ATA_TFLAG_LBA;
1330
1331                         tf->lbah = 0x0;
1332                         tf->lbam = 0x0;
1333                         tf->lbal = 0x0;
1334                         tf->device |= ATA_LBA;
1335                 } else {
1336                         /* CHS */
1337                         tf->lbal = 0x1; /* sect */
1338                         tf->lbam = 0x0; /* cyl low */
1339                         tf->lbah = 0x0; /* cyl high */
1340                 }
1341
1342                 tf->command = ATA_CMD_VERIFY;   /* READ VERIFY */
1343         } else {
1344                 /* Some odd clown BIOSen issue spindown on power off (ACPI S4
1345                  * or S5) causing some drives to spin up and down again.
1346                  */
1347                 if ((qc->ap->flags & ATA_FLAG_NO_POWEROFF_SPINDOWN) &&
1348                     system_state == SYSTEM_POWER_OFF)
1349                         goto skip;
1350
1351                 if ((qc->ap->flags & ATA_FLAG_NO_HIBERNATE_SPINDOWN) &&
1352                      system_entering_hibernation())
1353                         goto skip;
1354
1355                 /* Issue ATA STANDBY IMMEDIATE command */
1356                 tf->command = ATA_CMD_STANDBYNOW1;
1357         }
1358
1359         /*
1360          * Standby and Idle condition timers could be implemented but that
1361          * would require libata to implement the Power condition mode page
1362          * and allow the user to change it. Changing mode pages requires
1363          * MODE SELECT to be implemented.
1364          */
1365
1366         return 0;
1367
1368  invalid_fld:
1369         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x0);
1370         /* "Invalid field in cbd" */
1371         return 1;
1372  skip:
1373         scmd->result = SAM_STAT_GOOD;
1374         return 1;
1375 }
1376
1377
1378 /**
1379  *      ata_scsi_flush_xlat - Translate SCSI SYNCHRONIZE CACHE command
1380  *      @qc: Storage for translated ATA taskfile
1381  *
1382  *      Sets up an ATA taskfile to issue FLUSH CACHE or
1383  *      FLUSH CACHE EXT.
1384  *
1385  *      LOCKING:
1386  *      spin_lock_irqsave(host lock)
1387  *
1388  *      RETURNS:
1389  *      Zero on success, non-zero on error.
1390  */
1391 static unsigned int ata_scsi_flush_xlat(struct ata_queued_cmd *qc)
1392 {
1393         struct ata_taskfile *tf = &qc->tf;
1394
1395         tf->flags |= ATA_TFLAG_DEVICE;
1396         tf->protocol = ATA_PROT_NODATA;
1397
1398         if (qc->dev->flags & ATA_DFLAG_FLUSH_EXT)
1399                 tf->command = ATA_CMD_FLUSH_EXT;
1400         else
1401                 tf->command = ATA_CMD_FLUSH;
1402
1403         /* flush is critical for IO integrity, consider it an IO command */
1404         qc->flags |= ATA_QCFLAG_IO;
1405
1406         return 0;
1407 }
1408
1409 /**
1410  *      scsi_6_lba_len - Get LBA and transfer length
1411  *      @cdb: SCSI command to translate
1412  *
1413  *      Calculate LBA and transfer length for 6-byte commands.
1414  *
1415  *      RETURNS:
1416  *      @plba: the LBA
1417  *      @plen: the transfer length
1418  */
1419 static void scsi_6_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
1420 {
1421         u64 lba = 0;
1422         u32 len;
1423
1424         VPRINTK("six-byte command\n");
1425
1426         lba |= ((u64)(cdb[1] & 0x1f)) << 16;
1427         lba |= ((u64)cdb[2]) << 8;
1428         lba |= ((u64)cdb[3]);
1429
1430         len = cdb[4];
1431
1432         *plba = lba;
1433         *plen = len;
1434 }
1435
1436 /**
1437  *      scsi_10_lba_len - Get LBA and transfer length
1438  *      @cdb: SCSI command to translate
1439  *
1440  *      Calculate LBA and transfer length for 10-byte commands.
1441  *
1442  *      RETURNS:
1443  *      @plba: the LBA
1444  *      @plen: the transfer length
1445  */
1446 static void scsi_10_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
1447 {
1448         u64 lba = 0;
1449         u32 len = 0;
1450
1451         VPRINTK("ten-byte command\n");
1452
1453         lba |= ((u64)cdb[2]) << 24;
1454         lba |= ((u64)cdb[3]) << 16;
1455         lba |= ((u64)cdb[4]) << 8;
1456         lba |= ((u64)cdb[5]);
1457
1458         len |= ((u32)cdb[7]) << 8;
1459         len |= ((u32)cdb[8]);
1460
1461         *plba = lba;
1462         *plen = len;
1463 }
1464
1465 /**
1466  *      scsi_16_lba_len - Get LBA and transfer length
1467  *      @cdb: SCSI command to translate
1468  *
1469  *      Calculate LBA and transfer length for 16-byte commands.
1470  *
1471  *      RETURNS:
1472  *      @plba: the LBA
1473  *      @plen: the transfer length
1474  */
1475 static void scsi_16_lba_len(const u8 *cdb, u64 *plba, u32 *plen)
1476 {
1477         u64 lba = 0;
1478         u32 len = 0;
1479
1480         VPRINTK("sixteen-byte command\n");
1481
1482         lba |= ((u64)cdb[2]) << 56;
1483         lba |= ((u64)cdb[3]) << 48;
1484         lba |= ((u64)cdb[4]) << 40;
1485         lba |= ((u64)cdb[5]) << 32;
1486         lba |= ((u64)cdb[6]) << 24;
1487         lba |= ((u64)cdb[7]) << 16;
1488         lba |= ((u64)cdb[8]) << 8;
1489         lba |= ((u64)cdb[9]);
1490
1491         len |= ((u32)cdb[10]) << 24;
1492         len |= ((u32)cdb[11]) << 16;
1493         len |= ((u32)cdb[12]) << 8;
1494         len |= ((u32)cdb[13]);
1495
1496         *plba = lba;
1497         *plen = len;
1498 }
1499
1500 /**
1501  *      ata_scsi_verify_xlat - Translate SCSI VERIFY command into an ATA one
1502  *      @qc: Storage for translated ATA taskfile
1503  *
1504  *      Converts SCSI VERIFY command to an ATA READ VERIFY command.
1505  *
1506  *      LOCKING:
1507  *      spin_lock_irqsave(host lock)
1508  *
1509  *      RETURNS:
1510  *      Zero on success, non-zero on error.
1511  */
1512 static unsigned int ata_scsi_verify_xlat(struct ata_queued_cmd *qc)
1513 {
1514         struct scsi_cmnd *scmd = qc->scsicmd;
1515         struct ata_taskfile *tf = &qc->tf;
1516         struct ata_device *dev = qc->dev;
1517         u64 dev_sectors = qc->dev->n_sectors;
1518         const u8 *cdb = scmd->cmnd;
1519         u64 block;
1520         u32 n_block;
1521
1522         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1523         tf->protocol = ATA_PROT_NODATA;
1524
1525         if (cdb[0] == VERIFY) {
1526                 if (scmd->cmd_len < 10)
1527                         goto invalid_fld;
1528                 scsi_10_lba_len(cdb, &block, &n_block);
1529         } else if (cdb[0] == VERIFY_16) {
1530                 if (scmd->cmd_len < 16)
1531                         goto invalid_fld;
1532                 scsi_16_lba_len(cdb, &block, &n_block);
1533         } else
1534                 goto invalid_fld;
1535
1536         if (!n_block)
1537                 goto nothing_to_do;
1538         if (block >= dev_sectors)
1539                 goto out_of_range;
1540         if ((block + n_block) > dev_sectors)
1541                 goto out_of_range;
1542
1543         if (dev->flags & ATA_DFLAG_LBA) {
1544                 tf->flags |= ATA_TFLAG_LBA;
1545
1546                 if (lba_28_ok(block, n_block)) {
1547                         /* use LBA28 */
1548                         tf->command = ATA_CMD_VERIFY;
1549                         tf->device |= (block >> 24) & 0xf;
1550                 } else if (lba_48_ok(block, n_block)) {
1551                         if (!(dev->flags & ATA_DFLAG_LBA48))
1552                                 goto out_of_range;
1553
1554                         /* use LBA48 */
1555                         tf->flags |= ATA_TFLAG_LBA48;
1556                         tf->command = ATA_CMD_VERIFY_EXT;
1557
1558                         tf->hob_nsect = (n_block >> 8) & 0xff;
1559
1560                         tf->hob_lbah = (block >> 40) & 0xff;
1561                         tf->hob_lbam = (block >> 32) & 0xff;
1562                         tf->hob_lbal = (block >> 24) & 0xff;
1563                 } else
1564                         /* request too large even for LBA48 */
1565                         goto out_of_range;
1566
1567                 tf->nsect = n_block & 0xff;
1568
1569                 tf->lbah = (block >> 16) & 0xff;
1570                 tf->lbam = (block >> 8) & 0xff;
1571                 tf->lbal = block & 0xff;
1572
1573                 tf->device |= ATA_LBA;
1574         } else {
1575                 /* CHS */
1576                 u32 sect, head, cyl, track;
1577
1578                 if (!lba_28_ok(block, n_block))
1579                         goto out_of_range;
1580
1581                 /* Convert LBA to CHS */
1582                 track = (u32)block / dev->sectors;
1583                 cyl   = track / dev->heads;
1584                 head  = track % dev->heads;
1585                 sect  = (u32)block % dev->sectors + 1;
1586
1587                 DPRINTK("block %u track %u cyl %u head %u sect %u\n",
1588                         (u32)block, track, cyl, head, sect);
1589
1590                 /* Check whether the converted CHS can fit.
1591                    Cylinder: 0-65535
1592                    Head: 0-15
1593                    Sector: 1-255*/
1594                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
1595                         goto out_of_range;
1596
1597                 tf->command = ATA_CMD_VERIFY;
1598                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
1599                 tf->lbal = sect;
1600                 tf->lbam = cyl;
1601                 tf->lbah = cyl >> 8;
1602                 tf->device |= head;
1603         }
1604
1605         return 0;
1606
1607 invalid_fld:
1608         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x0);
1609         /* "Invalid field in cbd" */
1610         return 1;
1611
1612 out_of_range:
1613         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x21, 0x0);
1614         /* "Logical Block Address out of range" */
1615         return 1;
1616
1617 nothing_to_do:
1618         scmd->result = SAM_STAT_GOOD;
1619         return 1;
1620 }
1621
1622 /**
1623  *      ata_scsi_rw_xlat - Translate SCSI r/w command into an ATA one
1624  *      @qc: Storage for translated ATA taskfile
1625  *
1626  *      Converts any of six SCSI read/write commands into the
1627  *      ATA counterpart, including starting sector (LBA),
1628  *      sector count, and taking into account the device's LBA48
1629  *      support.
1630  *
1631  *      Commands %READ_6, %READ_10, %READ_16, %WRITE_6, %WRITE_10, and
1632  *      %WRITE_16 are currently supported.
1633  *
1634  *      LOCKING:
1635  *      spin_lock_irqsave(host lock)
1636  *
1637  *      RETURNS:
1638  *      Zero on success, non-zero on error.
1639  */
1640 static unsigned int ata_scsi_rw_xlat(struct ata_queued_cmd *qc)
1641 {
1642         struct scsi_cmnd *scmd = qc->scsicmd;
1643         const u8 *cdb = scmd->cmnd;
1644         unsigned int tf_flags = 0;
1645         u64 block;
1646         u32 n_block;
1647         int rc;
1648
1649         if (cdb[0] == WRITE_10 || cdb[0] == WRITE_6 || cdb[0] == WRITE_16)
1650                 tf_flags |= ATA_TFLAG_WRITE;
1651
1652         /* Calculate the SCSI LBA, transfer length and FUA. */
1653         switch (cdb[0]) {
1654         case READ_10:
1655         case WRITE_10:
1656                 if (unlikely(scmd->cmd_len < 10))
1657                         goto invalid_fld;
1658                 scsi_10_lba_len(cdb, &block, &n_block);
1659                 if (unlikely(cdb[1] & (1 << 3)))
1660                         tf_flags |= ATA_TFLAG_FUA;
1661                 break;
1662         case READ_6:
1663         case WRITE_6:
1664                 if (unlikely(scmd->cmd_len < 6))
1665                         goto invalid_fld;
1666                 scsi_6_lba_len(cdb, &block, &n_block);
1667
1668                 /* for 6-byte r/w commands, transfer length 0
1669                  * means 256 blocks of data, not 0 block.
1670                  */
1671                 if (!n_block)
1672                         n_block = 256;
1673                 break;
1674         case READ_16:
1675         case WRITE_16:
1676                 if (unlikely(scmd->cmd_len < 16))
1677                         goto invalid_fld;
1678                 scsi_16_lba_len(cdb, &block, &n_block);
1679                 if (unlikely(cdb[1] & (1 << 3)))
1680                         tf_flags |= ATA_TFLAG_FUA;
1681                 break;
1682         default:
1683                 DPRINTK("no-byte command\n");
1684                 goto invalid_fld;
1685         }
1686
1687         /* Check and compose ATA command */
1688         if (!n_block)
1689                 /* For 10-byte and 16-byte SCSI R/W commands, transfer
1690                  * length 0 means transfer 0 block of data.
1691                  * However, for ATA R/W commands, sector count 0 means
1692                  * 256 or 65536 sectors, not 0 sectors as in SCSI.
1693                  *
1694                  * WARNING: one or two older ATA drives treat 0 as 0...
1695                  */
1696                 goto nothing_to_do;
1697
1698         qc->flags |= ATA_QCFLAG_IO;
1699         qc->nbytes = n_block * ATA_SECT_SIZE;
1700
1701         rc = ata_build_rw_tf(&qc->tf, qc->dev, block, n_block, tf_flags,
1702                              qc->tag);
1703         if (likely(rc == 0))
1704                 return 0;
1705
1706         if (rc == -ERANGE)
1707                 goto out_of_range;
1708         /* treat all other errors as -EINVAL, fall through */
1709 invalid_fld:
1710         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x0);
1711         /* "Invalid field in cbd" */
1712         return 1;
1713
1714 out_of_range:
1715         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x21, 0x0);
1716         /* "Logical Block Address out of range" */
1717         return 1;
1718
1719 nothing_to_do:
1720         scmd->result = SAM_STAT_GOOD;
1721         return 1;
1722 }
1723
1724 static void ata_scsi_qc_complete(struct ata_queued_cmd *qc)
1725 {
1726         struct ata_port *ap = qc->ap;
1727         struct scsi_cmnd *cmd = qc->scsicmd;
1728         u8 *cdb = cmd->cmnd;
1729         int need_sense = (qc->err_mask != 0);
1730
1731         /* For ATA pass thru (SAT) commands, generate a sense block if
1732          * user mandated it or if there's an error.  Note that if we
1733          * generate because the user forced us to, a check condition
1734          * is generated and the ATA register values are returned
1735          * whether the command completed successfully or not. If there
1736          * was no error, SK, ASC and ASCQ will all be zero.
1737          */
1738         if (((cdb[0] == ATA_16) || (cdb[0] == ATA_12)) &&
1739             ((cdb[2] & 0x20) || need_sense)) {
1740                 ata_gen_passthru_sense(qc);
1741         } else {
1742                 if (!need_sense) {
1743                         cmd->result = SAM_STAT_GOOD;
1744                 } else {
1745                         /* TODO: decide which descriptor format to use
1746                          * for 48b LBA devices and call that here
1747                          * instead of the fixed desc, which is only
1748                          * good for smaller LBA (and maybe CHS?)
1749                          * devices.
1750                          */
1751                         ata_gen_ata_sense(qc);
1752                 }
1753         }
1754
1755         if (need_sense && !ap->ops->error_handler)
1756                 ata_dump_status(ap->print_id, &qc->result_tf);
1757
1758         qc->scsidone(cmd);
1759
1760         ata_qc_free(qc);
1761 }
1762
1763 /**
1764  *      ata_scsi_translate - Translate then issue SCSI command to ATA device
1765  *      @dev: ATA device to which the command is addressed
1766  *      @cmd: SCSI command to execute
1767  *      @done: SCSI command completion function
1768  *      @xlat_func: Actor which translates @cmd to an ATA taskfile
1769  *
1770  *      Our ->queuecommand() function has decided that the SCSI
1771  *      command issued can be directly translated into an ATA
1772  *      command, rather than handled internally.
1773  *
1774  *      This function sets up an ata_queued_cmd structure for the
1775  *      SCSI command, and sends that ata_queued_cmd to the hardware.
1776  *
1777  *      The xlat_func argument (actor) returns 0 if ready to execute
1778  *      ATA command, else 1 to finish translation. If 1 is returned
1779  *      then cmd->result (and possibly cmd->sense_buffer) are assumed
1780  *      to be set reflecting an error condition or clean (early)
1781  *      termination.
1782  *
1783  *      LOCKING:
1784  *      spin_lock_irqsave(host lock)
1785  *
1786  *      RETURNS:
1787  *      0 on success, SCSI_ML_QUEUE_DEVICE_BUSY if the command
1788  *      needs to be deferred.
1789  */
1790 static int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd,
1791                               void (*done)(struct scsi_cmnd *),
1792                               ata_xlat_func_t xlat_func)
1793 {
1794         struct ata_port *ap = dev->link->ap;
1795         struct ata_queued_cmd *qc;
1796         int rc;
1797
1798         VPRINTK("ENTER\n");
1799
1800         qc = ata_scsi_qc_new(dev, cmd, done);
1801         if (!qc)
1802                 goto err_mem;
1803
1804         /* data is present; dma-map it */
1805         if (cmd->sc_data_direction == DMA_FROM_DEVICE ||
1806             cmd->sc_data_direction == DMA_TO_DEVICE) {
1807                 if (unlikely(scsi_bufflen(cmd) < 1)) {
1808                         ata_dev_printk(dev, KERN_WARNING,
1809                                        "WARNING: zero len r/w req\n");
1810                         goto err_did;
1811                 }
1812
1813                 ata_sg_init(qc, scsi_sglist(cmd), scsi_sg_count(cmd));
1814
1815                 qc->dma_dir = cmd->sc_data_direction;
1816         }
1817
1818         qc->complete_fn = ata_scsi_qc_complete;
1819
1820         if (xlat_func(qc))
1821                 goto early_finish;
1822
1823         if (ap->ops->qc_defer) {
1824                 if ((rc = ap->ops->qc_defer(qc)))
1825                         goto defer;
1826         }
1827
1828         /* select device, send command to hardware */
1829         ata_qc_issue(qc);
1830
1831         VPRINTK("EXIT\n");
1832         return 0;
1833
1834 early_finish:
1835         ata_qc_free(qc);
1836         qc->scsidone(cmd);
1837         DPRINTK("EXIT - early finish (good or error)\n");
1838         return 0;
1839
1840 err_did:
1841         ata_qc_free(qc);
1842         cmd->result = (DID_ERROR << 16);
1843         qc->scsidone(cmd);
1844 err_mem:
1845         DPRINTK("EXIT - internal\n");
1846         return 0;
1847
1848 defer:
1849         ata_qc_free(qc);
1850         DPRINTK("EXIT - defer\n");
1851         if (rc == ATA_DEFER_LINK)
1852                 return SCSI_MLQUEUE_DEVICE_BUSY;
1853         else
1854                 return SCSI_MLQUEUE_HOST_BUSY;
1855 }
1856
1857 /**
1858  *      ata_scsi_rbuf_get - Map response buffer.
1859  *      @cmd: SCSI command containing buffer to be mapped.
1860  *      @flags: unsigned long variable to store irq enable status
1861  *      @copy_in: copy in from user buffer
1862  *
1863  *      Prepare buffer for simulated SCSI commands.
1864  *
1865  *      LOCKING:
1866  *      spin_lock_irqsave(ata_scsi_rbuf_lock) on success
1867  *
1868  *      RETURNS:
1869  *      Pointer to response buffer.
1870  */
1871 static void *ata_scsi_rbuf_get(struct scsi_cmnd *cmd, bool copy_in,
1872                                unsigned long *flags)
1873 {
1874         spin_lock_irqsave(&ata_scsi_rbuf_lock, *flags);
1875
1876         memset(ata_scsi_rbuf, 0, ATA_SCSI_RBUF_SIZE);
1877         if (copy_in)
1878                 sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
1879                                   ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
1880         return ata_scsi_rbuf;
1881 }
1882
1883 /**
1884  *      ata_scsi_rbuf_put - Unmap response buffer.
1885  *      @cmd: SCSI command containing buffer to be unmapped.
1886  *      @copy_out: copy out result
1887  *      @flags: @flags passed to ata_scsi_rbuf_get()
1888  *
1889  *      Returns rbuf buffer.  The result is copied to @cmd's buffer if
1890  *      @copy_back is true.
1891  *
1892  *      LOCKING:
1893  *      Unlocks ata_scsi_rbuf_lock.
1894  */
1895 static inline void ata_scsi_rbuf_put(struct scsi_cmnd *cmd, bool copy_out,
1896                                      unsigned long *flags)
1897 {
1898         if (copy_out)
1899                 sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
1900                                     ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
1901         spin_unlock_irqrestore(&ata_scsi_rbuf_lock, *flags);
1902 }
1903
1904 /**
1905  *      ata_scsi_rbuf_fill - wrapper for SCSI command simulators
1906  *      @args: device IDENTIFY data / SCSI command of interest.
1907  *      @actor: Callback hook for desired SCSI command simulator
1908  *
1909  *      Takes care of the hard work of simulating a SCSI command...
1910  *      Mapping the response buffer, calling the command's handler,
1911  *      and handling the handler's return value.  This return value
1912  *      indicates whether the handler wishes the SCSI command to be
1913  *      completed successfully (0), or not (in which case cmd->result
1914  *      and sense buffer are assumed to be set).
1915  *
1916  *      LOCKING:
1917  *      spin_lock_irqsave(host lock)
1918  */
1919 static void ata_scsi_rbuf_fill(struct ata_scsi_args *args,
1920                 unsigned int (*actor)(struct ata_scsi_args *args, u8 *rbuf))
1921 {
1922         u8 *rbuf;
1923         unsigned int rc;
1924         struct scsi_cmnd *cmd = args->cmd;
1925         unsigned long flags;
1926
1927         rbuf = ata_scsi_rbuf_get(cmd, false, &flags);
1928         rc = actor(args, rbuf);
1929         ata_scsi_rbuf_put(cmd, rc == 0, &flags);
1930
1931         if (rc == 0)
1932                 cmd->result = SAM_STAT_GOOD;
1933         args->done(cmd);
1934 }
1935
1936 /**
1937  *      ata_scsiop_inq_std - Simulate INQUIRY command
1938  *      @args: device IDENTIFY data / SCSI command of interest.
1939  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1940  *
1941  *      Returns standard device identification data associated
1942  *      with non-VPD INQUIRY command output.
1943  *
1944  *      LOCKING:
1945  *      spin_lock_irqsave(host lock)
1946  */
1947 static unsigned int ata_scsiop_inq_std(struct ata_scsi_args *args, u8 *rbuf)
1948 {
1949         const u8 versions[] = {
1950                 0x60,   /* SAM-3 (no version claimed) */
1951
1952                 0x03,
1953                 0x20,   /* SBC-2 (no version claimed) */
1954
1955                 0x02,
1956                 0x60    /* SPC-3 (no version claimed) */
1957         };
1958         u8 hdr[] = {
1959                 TYPE_DISK,
1960                 0,
1961                 0x5,    /* claim SPC-3 version compatibility */
1962                 2,
1963                 95 - 4
1964         };
1965
1966         VPRINTK("ENTER\n");
1967
1968         /* set scsi removeable (RMB) bit per ata bit */
1969         if (ata_id_removeable(args->id))
1970                 hdr[1] |= (1 << 7);
1971
1972         memcpy(rbuf, hdr, sizeof(hdr));
1973         memcpy(&rbuf[8], "ATA     ", 8);
1974         ata_id_string(args->id, &rbuf[16], ATA_ID_PROD, 16);
1975         ata_id_string(args->id, &rbuf[32], ATA_ID_FW_REV, 4);
1976
1977         if (rbuf[32] == 0 || rbuf[32] == ' ')
1978                 memcpy(&rbuf[32], "n/a ", 4);
1979
1980         memcpy(rbuf + 59, versions, sizeof(versions));
1981
1982         return 0;
1983 }
1984
1985 /**
1986  *      ata_scsiop_inq_00 - Simulate INQUIRY VPD page 0, list of pages
1987  *      @args: device IDENTIFY data / SCSI command of interest.
1988  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1989  *
1990  *      Returns list of inquiry VPD pages available.
1991  *
1992  *      LOCKING:
1993  *      spin_lock_irqsave(host lock)
1994  */
1995 static unsigned int ata_scsiop_inq_00(struct ata_scsi_args *args, u8 *rbuf)
1996 {
1997         const u8 pages[] = {
1998                 0x00,   /* page 0x00, this page */
1999                 0x80,   /* page 0x80, unit serial no page */
2000                 0x83,   /* page 0x83, device ident page */
2001                 0x89,   /* page 0x89, ata info page */
2002                 0xb0,   /* page 0xb0, block limits page */
2003                 0xb1,   /* page 0xb1, block device characteristics page */
2004         };
2005
2006         rbuf[3] = sizeof(pages);        /* number of supported VPD pages */
2007         memcpy(rbuf + 4, pages, sizeof(pages));
2008         return 0;
2009 }
2010
2011 /**
2012  *      ata_scsiop_inq_80 - Simulate INQUIRY VPD page 80, device serial number
2013  *      @args: device IDENTIFY data / SCSI command of interest.
2014  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2015  *
2016  *      Returns ATA device serial number.
2017  *
2018  *      LOCKING:
2019  *      spin_lock_irqsave(host lock)
2020  */
2021 static unsigned int ata_scsiop_inq_80(struct ata_scsi_args *args, u8 *rbuf)
2022 {
2023         const u8 hdr[] = {
2024                 0,
2025                 0x80,                   /* this page code */
2026                 0,
2027                 ATA_ID_SERNO_LEN,       /* page len */
2028         };
2029
2030         memcpy(rbuf, hdr, sizeof(hdr));
2031         ata_id_string(args->id, (unsigned char *) &rbuf[4],
2032                       ATA_ID_SERNO, ATA_ID_SERNO_LEN);
2033         return 0;
2034 }
2035
2036 /**
2037  *      ata_scsiop_inq_83 - Simulate INQUIRY VPD page 83, device identity
2038  *      @args: device IDENTIFY data / SCSI command of interest.
2039  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2040  *
2041  *      Yields two logical unit device identification designators:
2042  *       - vendor specific ASCII containing the ATA serial number
2043  *       - SAT defined "t10 vendor id based" containing ASCII vendor
2044  *         name ("ATA     "), model and serial numbers.
2045  *
2046  *      LOCKING:
2047  *      spin_lock_irqsave(host lock)
2048  */
2049 static unsigned int ata_scsiop_inq_83(struct ata_scsi_args *args, u8 *rbuf)
2050 {
2051         const int sat_model_serial_desc_len = 68;
2052         int num;
2053
2054         rbuf[1] = 0x83;                 /* this page code */
2055         num = 4;
2056
2057         /* piv=0, assoc=lu, code_set=ACSII, designator=vendor */
2058         rbuf[num + 0] = 2;
2059         rbuf[num + 3] = ATA_ID_SERNO_LEN;
2060         num += 4;
2061         ata_id_string(args->id, (unsigned char *) rbuf + num,
2062                       ATA_ID_SERNO, ATA_ID_SERNO_LEN);
2063         num += ATA_ID_SERNO_LEN;
2064
2065         /* SAT defined lu model and serial numbers descriptor */
2066         /* piv=0, assoc=lu, code_set=ACSII, designator=t10 vendor id */
2067         rbuf[num + 0] = 2;
2068         rbuf[num + 1] = 1;
2069         rbuf[num + 3] = sat_model_serial_desc_len;
2070         num += 4;
2071         memcpy(rbuf + num, "ATA     ", 8);
2072         num += 8;
2073         ata_id_string(args->id, (unsigned char *) rbuf + num, ATA_ID_PROD,
2074                       ATA_ID_PROD_LEN);
2075         num += ATA_ID_PROD_LEN;
2076         ata_id_string(args->id, (unsigned char *) rbuf + num, ATA_ID_SERNO,
2077                       ATA_ID_SERNO_LEN);
2078         num += ATA_ID_SERNO_LEN;
2079
2080         rbuf[3] = num - 4;    /* page len (assume less than 256 bytes) */
2081         return 0;
2082 }
2083
2084 /**
2085  *      ata_scsiop_inq_89 - Simulate INQUIRY VPD page 89, ATA info
2086  *      @args: device IDENTIFY data / SCSI command of interest.
2087  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2088  *
2089  *      Yields SAT-specified ATA VPD page.
2090  *
2091  *      LOCKING:
2092  *      spin_lock_irqsave(host lock)
2093  */
2094 static unsigned int ata_scsiop_inq_89(struct ata_scsi_args *args, u8 *rbuf)
2095 {
2096         struct ata_taskfile tf;
2097
2098         memset(&tf, 0, sizeof(tf));
2099
2100         rbuf[1] = 0x89;                 /* our page code */
2101         rbuf[2] = (0x238 >> 8);         /* page size fixed at 238h */
2102         rbuf[3] = (0x238 & 0xff);
2103
2104         memcpy(&rbuf[8], "linux   ", 8);
2105         memcpy(&rbuf[16], "libata          ", 16);
2106         memcpy(&rbuf[32], DRV_VERSION, 4);
2107         ata_id_string(args->id, &rbuf[32], ATA_ID_FW_REV, 4);
2108
2109         /* we don't store the ATA device signature, so we fake it */
2110
2111         tf.command = ATA_DRDY;          /* really, this is Status reg */
2112         tf.lbal = 0x1;
2113         tf.nsect = 0x1;
2114
2115         ata_tf_to_fis(&tf, 0, 1, &rbuf[36]);    /* TODO: PMP? */
2116         rbuf[36] = 0x34;                /* force D2H Reg FIS (34h) */
2117
2118         rbuf[56] = ATA_CMD_ID_ATA;
2119
2120         memcpy(&rbuf[60], &args->id[0], 512);
2121         return 0;
2122 }
2123
2124 static unsigned int ata_scsiop_inq_b0(struct ata_scsi_args *args, u8 *rbuf)
2125 {
2126         u32 min_io_sectors;
2127
2128         rbuf[1] = 0xb0;
2129         rbuf[3] = 0x3c;         /* required VPD size with unmap support */
2130
2131         /*
2132          * Optimal transfer length granularity.
2133          *
2134          * This is always one physical block, but for disks with a smaller
2135          * logical than physical sector size we need to figure out what the
2136          * latter is.
2137          */
2138         if (ata_id_has_large_logical_sectors(args->id))
2139                 min_io_sectors = ata_id_logical_per_physical_sectors(args->id);
2140         else
2141                 min_io_sectors = 1;
2142         put_unaligned_be16(min_io_sectors, &rbuf[6]);
2143
2144         /*
2145          * Optimal unmap granularity.
2146          *
2147          * The ATA spec doesn't even know about a granularity or alignment
2148          * for the TRIM command.  We can leave away most of the unmap related
2149          * VPD page entries, but we have specifify a granularity to signal
2150          * that we support some form of unmap - in thise case via WRITE SAME
2151          * with the unmap bit set.
2152          */
2153         if (ata_id_has_trim(args->id)) {
2154                 put_unaligned_be32(65535 * 512 / 8, &rbuf[20]);
2155                 put_unaligned_be32(1, &rbuf[28]);
2156         }
2157
2158         return 0;
2159 }
2160
2161 static unsigned int ata_scsiop_inq_b1(struct ata_scsi_args *args, u8 *rbuf)
2162 {
2163         int form_factor = ata_id_form_factor(args->id);
2164         int media_rotation_rate = ata_id_rotation_rate(args->id);
2165
2166         rbuf[1] = 0xb1;
2167         rbuf[3] = 0x3c;
2168         rbuf[4] = media_rotation_rate >> 8;
2169         rbuf[5] = media_rotation_rate;
2170         rbuf[7] = form_factor;
2171
2172         return 0;
2173 }
2174
2175 /**
2176  *      ata_scsiop_noop - Command handler that simply returns success.
2177  *      @args: device IDENTIFY data / SCSI command of interest.
2178  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2179  *
2180  *      No operation.  Simply returns success to caller, to indicate
2181  *      that the caller should successfully complete this SCSI command.
2182  *
2183  *      LOCKING:
2184  *      spin_lock_irqsave(host lock)
2185  */
2186 static unsigned int ata_scsiop_noop(struct ata_scsi_args *args, u8 *rbuf)
2187 {
2188         VPRINTK("ENTER\n");
2189         return 0;
2190 }
2191
2192 /**
2193  *      ata_msense_caching - Simulate MODE SENSE caching info page
2194  *      @id: device IDENTIFY data
2195  *      @buf: output buffer
2196  *
2197  *      Generate a caching info page, which conditionally indicates
2198  *      write caching to the SCSI layer, depending on device
2199  *      capabilities.
2200  *
2201  *      LOCKING:
2202  *      None.
2203  */
2204 static unsigned int ata_msense_caching(u16 *id, u8 *buf)
2205 {
2206         memcpy(buf, def_cache_mpage, sizeof(def_cache_mpage));
2207         if (ata_id_wcache_enabled(id))
2208                 buf[2] |= (1 << 2);     /* write cache enable */
2209         if (!ata_id_rahead_enabled(id))
2210                 buf[12] |= (1 << 5);    /* disable read ahead */
2211         return sizeof(def_cache_mpage);
2212 }
2213
2214 /**
2215  *      ata_msense_ctl_mode - Simulate MODE SENSE control mode page
2216  *      @buf: output buffer
2217  *
2218  *      Generate a generic MODE SENSE control mode page.
2219  *
2220  *      LOCKING:
2221  *      None.
2222  */
2223 static unsigned int ata_msense_ctl_mode(u8 *buf)
2224 {
2225         memcpy(buf, def_control_mpage, sizeof(def_control_mpage));
2226         return sizeof(def_control_mpage);
2227 }
2228
2229 /**
2230  *      ata_msense_rw_recovery - Simulate MODE SENSE r/w error recovery page
2231  *      @buf: output buffer
2232  *
2233  *      Generate a generic MODE SENSE r/w error recovery page.
2234  *
2235  *      LOCKING:
2236  *      None.
2237  */
2238 static unsigned int ata_msense_rw_recovery(u8 *buf)
2239 {
2240         memcpy(buf, def_rw_recovery_mpage, sizeof(def_rw_recovery_mpage));
2241         return sizeof(def_rw_recovery_mpage);
2242 }
2243
2244 /*
2245  * We can turn this into a real blacklist if it's needed, for now just
2246  * blacklist any Maxtor BANC1G10 revision firmware
2247  */
2248 static int ata_dev_supports_fua(u16 *id)
2249 {
2250         unsigned char model[ATA_ID_PROD_LEN + 1], fw[ATA_ID_FW_REV_LEN + 1];
2251
2252         if (!libata_fua)
2253                 return 0;
2254         if (!ata_id_has_fua(id))
2255                 return 0;
2256
2257         ata_id_c_string(id, model, ATA_ID_PROD, sizeof(model));
2258         ata_id_c_string(id, fw, ATA_ID_FW_REV, sizeof(fw));
2259
2260         if (strcmp(model, "Maxtor"))
2261                 return 1;
2262         if (strcmp(fw, "BANC1G10"))
2263                 return 1;
2264
2265         return 0; /* blacklisted */
2266 }
2267
2268 /**
2269  *      ata_scsiop_mode_sense - Simulate MODE SENSE 6, 10 commands
2270  *      @args: device IDENTIFY data / SCSI command of interest.
2271  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2272  *
2273  *      Simulate MODE SENSE commands. Assume this is invoked for direct
2274  *      access devices (e.g. disks) only. There should be no block
2275  *      descriptor for other device types.
2276  *
2277  *      LOCKING:
2278  *      spin_lock_irqsave(host lock)
2279  */
2280 static unsigned int ata_scsiop_mode_sense(struct ata_scsi_args *args, u8 *rbuf)
2281 {
2282         struct ata_device *dev = args->dev;
2283         u8 *scsicmd = args->cmd->cmnd, *p = rbuf;
2284         const u8 sat_blk_desc[] = {
2285                 0, 0, 0, 0,     /* number of blocks: sat unspecified */
2286                 0,
2287                 0, 0x2, 0x0     /* block length: 512 bytes */
2288         };
2289         u8 pg, spg;
2290         unsigned int ebd, page_control, six_byte;
2291         u8 dpofua;
2292
2293         VPRINTK("ENTER\n");
2294
2295         six_byte = (scsicmd[0] == MODE_SENSE);
2296         ebd = !(scsicmd[1] & 0x8);      /* dbd bit inverted == edb */
2297         /*
2298          * LLBA bit in msense(10) ignored (compliant)
2299          */
2300
2301         page_control = scsicmd[2] >> 6;
2302         switch (page_control) {
2303         case 0: /* current */
2304                 break;  /* supported */
2305         case 3: /* saved */
2306                 goto saving_not_supp;
2307         case 1: /* changeable */
2308         case 2: /* defaults */
2309         default:
2310                 goto invalid_fld;
2311         }
2312
2313         if (six_byte)
2314                 p += 4 + (ebd ? 8 : 0);
2315         else
2316                 p += 8 + (ebd ? 8 : 0);
2317
2318         pg = scsicmd[2] & 0x3f;
2319         spg = scsicmd[3];
2320         /*
2321          * No mode subpages supported (yet) but asking for _all_
2322          * subpages may be valid
2323          */
2324         if (spg && (spg != ALL_SUB_MPAGES))
2325                 goto invalid_fld;
2326
2327         switch(pg) {
2328         case RW_RECOVERY_MPAGE:
2329                 p += ata_msense_rw_recovery(p);
2330                 break;
2331
2332         case CACHE_MPAGE:
2333                 p += ata_msense_caching(args->id, p);
2334                 break;
2335
2336         case CONTROL_MPAGE:
2337                 p += ata_msense_ctl_mode(p);
2338                 break;
2339
2340         case ALL_MPAGES:
2341                 p += ata_msense_rw_recovery(p);
2342                 p += ata_msense_caching(args->id, p);
2343                 p += ata_msense_ctl_mode(p);
2344                 break;
2345
2346         default:                /* invalid page code */
2347                 goto invalid_fld;
2348         }
2349
2350         dpofua = 0;
2351         if (ata_dev_supports_fua(args->id) && (dev->flags & ATA_DFLAG_LBA48) &&
2352             (!(dev->flags & ATA_DFLAG_PIO) || dev->multi_count))
2353                 dpofua = 1 << 4;
2354
2355         if (six_byte) {
2356                 rbuf[0] = p - rbuf - 1;
2357                 rbuf[2] |= dpofua;
2358                 if (ebd) {
2359                         rbuf[3] = sizeof(sat_blk_desc);
2360                         memcpy(rbuf + 4, sat_blk_desc, sizeof(sat_blk_desc));
2361                 }
2362         } else {
2363                 unsigned int output_len = p - rbuf - 2;
2364
2365                 rbuf[0] = output_len >> 8;
2366                 rbuf[1] = output_len;
2367                 rbuf[3] |= dpofua;
2368                 if (ebd) {
2369                         rbuf[7] = sizeof(sat_blk_desc);
2370                         memcpy(rbuf + 8, sat_blk_desc, sizeof(sat_blk_desc));
2371                 }
2372         }
2373         return 0;
2374
2375 invalid_fld:
2376         ata_scsi_set_sense(args->cmd, ILLEGAL_REQUEST, 0x24, 0x0);
2377         /* "Invalid field in cbd" */
2378         return 1;
2379
2380 saving_not_supp:
2381         ata_scsi_set_sense(args->cmd, ILLEGAL_REQUEST, 0x39, 0x0);
2382          /* "Saving parameters not supported" */
2383         return 1;
2384 }
2385
2386 /**
2387  *      ata_scsiop_read_cap - Simulate READ CAPACITY[ 16] commands
2388  *      @args: device IDENTIFY data / SCSI command of interest.
2389  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2390  *
2391  *      Simulate READ CAPACITY commands.
2392  *
2393  *      LOCKING:
2394  *      None.
2395  */
2396 static unsigned int ata_scsiop_read_cap(struct ata_scsi_args *args, u8 *rbuf)
2397 {
2398         struct ata_device *dev = args->dev;
2399         u64 last_lba = dev->n_sectors - 1; /* LBA of the last block */
2400         u8 log_per_phys = 0;
2401         u16 lowest_aligned = 0;
2402         u16 word_106 = dev->id[106];
2403         u16 word_209 = dev->id[209];
2404
2405         if ((word_106 & 0xc000) == 0x4000) {
2406                 /* Number and offset of logical sectors per physical sector */
2407                 if (word_106 & (1 << 13))
2408                         log_per_phys = word_106 & 0xf;
2409                 if ((word_209 & 0xc000) == 0x4000) {
2410                         u16 first = dev->id[209] & 0x3fff;
2411                         if (first > 0)
2412                                 lowest_aligned = (1 << log_per_phys) - first;
2413                 }
2414         }
2415
2416         VPRINTK("ENTER\n");
2417
2418         if (args->cmd->cmnd[0] == READ_CAPACITY) {
2419                 if (last_lba >= 0xffffffffULL)
2420                         last_lba = 0xffffffff;
2421
2422                 /* sector count, 32-bit */
2423                 rbuf[0] = last_lba >> (8 * 3);
2424                 rbuf[1] = last_lba >> (8 * 2);
2425                 rbuf[2] = last_lba >> (8 * 1);
2426                 rbuf[3] = last_lba;
2427
2428                 /* sector size */
2429                 rbuf[6] = ATA_SECT_SIZE >> 8;
2430                 rbuf[7] = ATA_SECT_SIZE & 0xff;
2431         } else {
2432                 /* sector count, 64-bit */
2433                 rbuf[0] = last_lba >> (8 * 7);
2434                 rbuf[1] = last_lba >> (8 * 6);
2435                 rbuf[2] = last_lba >> (8 * 5);
2436                 rbuf[3] = last_lba >> (8 * 4);
2437                 rbuf[4] = last_lba >> (8 * 3);
2438                 rbuf[5] = last_lba >> (8 * 2);
2439                 rbuf[6] = last_lba >> (8 * 1);
2440                 rbuf[7] = last_lba;
2441
2442                 /* sector size */
2443                 rbuf[10] = ATA_SECT_SIZE >> 8;
2444                 rbuf[11] = ATA_SECT_SIZE & 0xff;
2445
2446                 rbuf[12] = 0;
2447                 rbuf[13] = log_per_phys;
2448                 rbuf[14] = (lowest_aligned >> 8) & 0x3f;
2449                 rbuf[15] = lowest_aligned;
2450
2451                 if (ata_id_has_trim(args->id)) {
2452                         rbuf[14] |= 0x80; /* TPE */
2453
2454                         if (ata_id_has_zero_after_trim(args->id))
2455                                 rbuf[14] |= 0x40; /* TPRZ */
2456                 }
2457         }
2458
2459         return 0;
2460 }
2461
2462 /**
2463  *      ata_scsiop_report_luns - Simulate REPORT LUNS command
2464  *      @args: device IDENTIFY data / SCSI command of interest.
2465  *      @rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2466  *
2467  *      Simulate REPORT LUNS command.
2468  *
2469  *      LOCKING:
2470  *      spin_lock_irqsave(host lock)
2471  */
2472 static unsigned int ata_scsiop_report_luns(struct ata_scsi_args *args, u8 *rbuf)
2473 {
2474         VPRINTK("ENTER\n");
2475         rbuf[3] = 8;    /* just one lun, LUN 0, size 8 bytes */
2476
2477         return 0;
2478 }
2479
2480 static void atapi_sense_complete(struct ata_queued_cmd *qc)
2481 {
2482         if (qc->err_mask && ((qc->err_mask & AC_ERR_DEV) == 0)) {
2483                 /* FIXME: not quite right; we don't want the
2484                  * translation of taskfile registers into
2485                  * a sense descriptors, since that's only
2486                  * correct for ATA, not ATAPI
2487                  */
2488                 ata_gen_passthru_sense(qc);
2489         }
2490
2491         qc->scsidone(qc->scsicmd);
2492         ata_qc_free(qc);
2493 }
2494
2495 /* is it pointless to prefer PIO for "safety reasons"? */
2496 static inline int ata_pio_use_silly(struct ata_port *ap)
2497 {
2498         return (ap->flags & ATA_FLAG_PIO_DMA);
2499 }
2500
2501 static void atapi_request_sense(struct ata_queued_cmd *qc)
2502 {
2503         struct ata_port *ap = qc->ap;
2504         struct scsi_cmnd *cmd = qc->scsicmd;
2505
2506         DPRINTK("ATAPI request sense\n");
2507
2508         /* FIXME: is this needed? */
2509         memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
2510
2511 #ifdef CONFIG_ATA_SFF
2512         if (ap->ops->sff_tf_read)
2513                 ap->ops->sff_tf_read(ap, &qc->tf);
2514 #endif
2515
2516         /* fill these in, for the case where they are -not- overwritten */
2517         cmd->sense_buffer[0] = 0x70;
2518         cmd->sense_buffer[2] = qc->tf.feature >> 4;
2519
2520         ata_qc_reinit(qc);
2521
2522         /* setup sg table and init transfer direction */
2523         sg_init_one(&qc->sgent, cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
2524         ata_sg_init(qc, &qc->sgent, 1);
2525         qc->dma_dir = DMA_FROM_DEVICE;
2526
2527         memset(&qc->cdb, 0, qc->dev->cdb_len);
2528         qc->cdb[0] = REQUEST_SENSE;
2529         qc->cdb[4] = SCSI_SENSE_BUFFERSIZE;
2530
2531         qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2532         qc->tf.command = ATA_CMD_PACKET;
2533
2534         if (ata_pio_use_silly(ap)) {
2535                 qc->tf.protocol = ATAPI_PROT_DMA;
2536                 qc->tf.feature |= ATAPI_PKT_DMA;
2537         } else {
2538                 qc->tf.protocol = ATAPI_PROT_PIO;
2539                 qc->tf.lbam = SCSI_SENSE_BUFFERSIZE;
2540                 qc->tf.lbah = 0;
2541         }
2542         qc->nbytes = SCSI_SENSE_BUFFERSIZE;
2543
2544         qc->complete_fn = atapi_sense_complete;
2545
2546         ata_qc_issue(qc);
2547
2548         DPRINTK("EXIT\n");
2549 }
2550
2551 static void atapi_qc_complete(struct ata_queued_cmd *qc)
2552 {
2553         struct scsi_cmnd *cmd = qc->scsicmd;
2554         unsigned int err_mask = qc->err_mask;
2555
2556         VPRINTK("ENTER, err_mask 0x%X\n", err_mask);
2557
2558         /* handle completion from new EH */
2559         if (unlikely(qc->ap->ops->error_handler &&
2560                      (err_mask || qc->flags & ATA_QCFLAG_SENSE_VALID))) {
2561
2562                 if (!(qc->flags & ATA_QCFLAG_SENSE_VALID)) {
2563                         /* FIXME: not quite right; we don't want the
2564                          * translation of taskfile registers into a
2565                          * sense descriptors, since that's only
2566                          * correct for ATA, not ATAPI
2567                          */
2568                         ata_gen_passthru_sense(qc);
2569                 }
2570
2571                 /* SCSI EH automatically locks door if sdev->locked is
2572                  * set.  Sometimes door lock request continues to
2573                  * fail, for example, when no media is present.  This
2574                  * creates a loop - SCSI EH issues door lock which
2575                  * fails and gets invoked again to acquire sense data
2576                  * for the failed command.
2577                  *
2578                  * If door lock fails, always clear sdev->locked to
2579                  * avoid this infinite loop.
2580                  */
2581                 if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL)
2582                         qc->dev->sdev->locked = 0;
2583
2584                 qc->scsicmd->result = SAM_STAT_CHECK_CONDITION;
2585                 qc->scsidone(cmd);
2586                 ata_qc_free(qc);
2587                 return;
2588         }
2589
2590         /* successful completion or old EH failure path */
2591         if (unlikely(err_mask & AC_ERR_DEV)) {
2592                 cmd->result = SAM_STAT_CHECK_CONDITION;
2593                 atapi_request_sense(qc);
2594                 return;
2595         } else if (unlikely(err_mask)) {
2596                 /* FIXME: not quite right; we don't want the
2597                  * translation of taskfile registers into
2598                  * a sense descriptors, since that's only
2599                  * correct for ATA, not ATAPI
2600                  */
2601                 ata_gen_passthru_sense(qc);
2602         } else {
2603                 u8 *scsicmd = cmd->cmnd;
2604
2605                 if ((scsicmd[0] == INQUIRY) && ((scsicmd[1] & 0x03) == 0)) {
2606                         unsigned long flags;
2607                         u8 *buf;
2608
2609                         buf = ata_scsi_rbuf_get(cmd, true, &flags);
2610
2611         /* ATAPI devices typically report zero for their SCSI version,
2612          * and sometimes deviate from the spec WRT response data
2613          * format.  If SCSI version is reported as zero like normal,
2614          * then we make the following fixups:  1) Fake MMC-5 version,
2615          * to indicate to the Linux scsi midlayer this is a modern
2616          * device.  2) Ensure response data format / ATAPI information
2617          * are always correct.
2618          */
2619                         if (buf[2] == 0) {
2620                                 buf[2] = 0x5;
2621                                 buf[3] = 0x32;
2622                         }
2623
2624                         ata_scsi_rbuf_put(cmd, true, &flags);
2625                 }
2626
2627                 cmd->result = SAM_STAT_GOOD;
2628         }
2629
2630         qc->scsidone(cmd);
2631         ata_qc_free(qc);
2632 }
2633 /**
2634  *      atapi_xlat - Initialize PACKET taskfile
2635  *      @qc: command structure to be initialized
2636  *
2637  *      LOCKING:
2638  *      spin_lock_irqsave(host lock)
2639  *
2640  *      RETURNS:
2641  *      Zero on success, non-zero on failure.
2642  */
2643 static unsigned int atapi_xlat(struct ata_queued_cmd *qc)
2644 {
2645         struct scsi_cmnd *scmd = qc->scsicmd;
2646         struct ata_device *dev = qc->dev;
2647         int nodata = (scmd->sc_data_direction == DMA_NONE);
2648         int using_pio = !nodata && (dev->flags & ATA_DFLAG_PIO);
2649         unsigned int nbytes;
2650
2651         memset(qc->cdb, 0, dev->cdb_len);
2652         memcpy(qc->cdb, scmd->cmnd, scmd->cmd_len);
2653
2654         qc->complete_fn = atapi_qc_complete;
2655
2656         qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2657         if (scmd->sc_data_direction == DMA_TO_DEVICE) {
2658                 qc->tf.flags |= ATA_TFLAG_WRITE;
2659                 DPRINTK("direction: write\n");
2660         }
2661
2662         qc->tf.command = ATA_CMD_PACKET;
2663         ata_qc_set_pc_nbytes(qc);
2664
2665         /* check whether ATAPI DMA is safe */
2666         if (!nodata && !using_pio && atapi_check_dma(qc))
2667                 using_pio = 1;
2668
2669         /* Some controller variants snoop this value for Packet
2670          * transfers to do state machine and FIFO management.  Thus we
2671          * want to set it properly, and for DMA where it is
2672          * effectively meaningless.
2673          */
2674         nbytes = min(ata_qc_raw_nbytes(qc), (unsigned int)63 * 1024);
2675
2676         /* Most ATAPI devices which honor transfer chunk size don't
2677          * behave according to the spec when odd chunk size which
2678          * matches the transfer length is specified.  If the number of
2679          * bytes to transfer is 2n+1.  According to the spec, what
2680          * should happen is to indicate that 2n+1 is going to be
2681          * transferred and transfer 2n+2 bytes where the last byte is
2682          * padding.
2683          *
2684          * In practice, this doesn't happen.  ATAPI devices first
2685          * indicate and transfer 2n bytes and then indicate and
2686          * transfer 2 bytes where the last byte is padding.
2687          *
2688          * This inconsistency confuses several controllers which
2689          * perform PIO using DMA such as Intel AHCIs and sil3124/32.
2690          * These controllers use actual number of transferred bytes to
2691          * update DMA poitner and transfer of 4n+2 bytes make those
2692          * controller push DMA pointer by 4n+4 bytes because SATA data
2693          * FISes are aligned to 4 bytes.  This causes data corruption
2694          * and buffer overrun.
2695          *
2696          * Always setting nbytes to even number solves this problem
2697          * because then ATAPI devices don't have to split data at 2n
2698          * boundaries.
2699          */
2700         if (nbytes & 0x1)
2701                 nbytes++;
2702
2703         qc->tf.lbam = (nbytes & 0xFF);
2704         qc->tf.lbah = (nbytes >> 8);
2705
2706         if (nodata)
2707                 qc->tf.protocol = ATAPI_PROT_NODATA;
2708         else if (using_pio)
2709                 qc->tf.protocol = ATAPI_PROT_PIO;
2710         else {
2711                 /* DMA data xfer */
2712                 qc->tf.protocol = ATAPI_PROT_DMA;
2713                 qc->tf.feature |= ATAPI_PKT_DMA;
2714
2715                 if ((dev->flags & ATA_DFLAG_DMADIR) &&
2716                     (scmd->sc_data_direction != DMA_TO_DEVICE))
2717                         /* some SATA bridges need us to indicate data xfer direction */
2718                         qc->tf.feature |= ATAPI_DMADIR;
2719         }
2720
2721
2722         /* FIXME: We need to translate 0x05 READ_BLOCK_LIMITS to a MODE_SENSE
2723            as ATAPI tape drives don't get this right otherwise */
2724         return 0;
2725 }
2726
2727 static struct ata_device *ata_find_dev(struct ata_port *ap, int devno)
2728 {
2729         if (!sata_pmp_attached(ap)) {
2730                 if (likely(devno < ata_link_max_devices(&ap->link)))
2731                         return &ap->link.device[devno];
2732         } else {
2733                 if (likely(devno < ap->nr_pmp_links))
2734                         return &ap->pmp_link[devno].device[0];
2735         }
2736
2737         return NULL;
2738 }
2739
2740 static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
2741                                               const struct scsi_device *scsidev)
2742 {
2743         int devno;
2744
2745         /* skip commands not addressed to targets we simulate */
2746         if (!sata_pmp_attached(ap)) {
2747                 if (unlikely(scsidev->channel || scsidev->lun))
2748                         return NULL;
2749                 devno = scsidev->id;
2750         } else {
2751                 if (unlikely(scsidev->id || scsidev->lun))
2752                         return NULL;
2753                 devno = scsidev->channel;
2754         }
2755
2756         return ata_find_dev(ap, devno);
2757 }
2758
2759 /**
2760  *      ata_scsi_find_dev - lookup ata_device from scsi_cmnd
2761  *      @ap: ATA port to which the device is attached
2762  *      @scsidev: SCSI device from which we derive the ATA device
2763  *
2764  *      Given various information provided in struct scsi_cmnd,
2765  *      map that onto an ATA bus, and using that mapping
2766  *      determine which ata_device is associated with the
2767  *      SCSI command to be sent.
2768  *
2769  *      LOCKING:
2770  *      spin_lock_irqsave(host lock)
2771  *
2772  *      RETURNS:
2773  *      Associated ATA device, or %NULL if not found.
2774  */
2775 static struct ata_device *
2776 ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
2777 {
2778         struct ata_device *dev = __ata_scsi_find_dev(ap, scsidev);
2779
2780         if (unlikely(!dev || !ata_dev_enabled(dev)))
2781                 return NULL;
2782
2783         return dev;
2784 }
2785
2786 /*
2787  *      ata_scsi_map_proto - Map pass-thru protocol value to taskfile value.
2788  *      @byte1: Byte 1 from pass-thru CDB.
2789  *
2790  *      RETURNS:
2791  *      ATA_PROT_UNKNOWN if mapping failed/unimplemented, protocol otherwise.
2792  */
2793 static u8
2794 ata_scsi_map_proto(u8 byte1)
2795 {
2796         switch((byte1 & 0x1e) >> 1) {
2797         case 3:         /* Non-data */
2798                 return ATA_PROT_NODATA;
2799
2800         case 6:         /* DMA */
2801         case 10:        /* UDMA Data-in */
2802         case 11:        /* UDMA Data-Out */
2803                 return ATA_PROT_DMA;
2804
2805         case 4:         /* PIO Data-in */
2806         case 5:         /* PIO Data-out */
2807                 return ATA_PROT_PIO;
2808
2809         case 0:         /* Hard Reset */
2810         case 1:         /* SRST */
2811         case 8:         /* Device Diagnostic */
2812         case 9:         /* Device Reset */
2813         case 7:         /* DMA Queued */
2814         case 12:        /* FPDMA */
2815         case 15:        /* Return Response Info */
2816         default:        /* Reserved */
2817                 break;
2818         }
2819
2820         return ATA_PROT_UNKNOWN;
2821 }
2822
2823 /**
2824  *      ata_scsi_pass_thru - convert ATA pass-thru CDB to taskfile
2825  *      @qc: command structure to be initialized
2826  *
2827  *      Handles either 12 or 16-byte versions of the CDB.
2828  *
2829  *      RETURNS:
2830  *      Zero on success, non-zero on failure.
2831  */
2832 static unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
2833 {
2834         struct ata_taskfile *tf = &(qc->tf);
2835         struct scsi_cmnd *scmd = qc->scsicmd;
2836         struct ata_device *dev = qc->dev;
2837         const u8 *cdb = scmd->cmnd;
2838
2839         if ((tf->protocol = ata_scsi_map_proto(cdb[1])) == ATA_PROT_UNKNOWN)
2840                 goto invalid_fld;
2841
2842         /*
2843          * 12 and 16 byte CDBs use different offsets to
2844          * provide the various register values.
2845          */
2846         if (cdb[0] == ATA_16) {
2847                 /*
2848                  * 16-byte CDB - may contain extended commands.
2849                  *
2850                  * If that is the case, copy the upper byte register values.
2851                  */
2852                 if (cdb[1] & 0x01) {
2853                         tf->hob_feature = cdb[3];
2854                         tf->hob_nsect = cdb[5];
2855                         tf->hob_lbal = cdb[7];
2856                         tf->hob_lbam = cdb[9];
2857                         tf->hob_lbah = cdb[11];
2858                         tf->flags |= ATA_TFLAG_LBA48;
2859                 } else
2860                         tf->flags &= ~ATA_TFLAG_LBA48;
2861
2862                 /*
2863                  * Always copy low byte, device and command registers.
2864                  */
2865                 tf->feature = cdb[4];
2866                 tf->nsect = cdb[6];
2867                 tf->lbal = cdb[8];
2868                 tf->lbam = cdb[10];
2869                 tf->lbah = cdb[12];
2870                 tf->device = cdb[13];
2871                 tf->command = cdb[14];
2872         } else {
2873                 /*
2874                  * 12-byte CDB - incapable of extended commands.
2875                  */
2876                 tf->flags &= ~ATA_TFLAG_LBA48;
2877
2878                 tf->feature = cdb[3];
2879                 tf->nsect = cdb[4];
2880                 tf->lbal = cdb[5];
2881                 tf->lbam = cdb[6];
2882                 tf->lbah = cdb[7];
2883                 tf->device = cdb[8];
2884                 tf->command = cdb[9];
2885         }
2886
2887         /* enforce correct master/slave bit */
2888         tf->device = dev->devno ?
2889                 tf->device | ATA_DEV1 : tf->device & ~ATA_DEV1;
2890
2891         /* READ/WRITE LONG use a non-standard sect_size */
2892         qc->sect_size = ATA_SECT_SIZE;
2893         switch (tf->command) {
2894         case ATA_CMD_READ_LONG:
2895         case ATA_CMD_READ_LONG_ONCE:
2896         case ATA_CMD_WRITE_LONG:
2897         case ATA_CMD_WRITE_LONG_ONCE:
2898                 if (tf->protocol != ATA_PROT_PIO || tf->nsect != 1)
2899                         goto invalid_fld;
2900                 qc->sect_size = scsi_bufflen(scmd);
2901         }
2902
2903         /*
2904          * Set flags so that all registers will be written, pass on
2905          * write indication (used for PIO/DMA setup), result TF is
2906          * copied back and we don't whine too much about its failure.
2907          */
2908         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2909         if (scmd->sc_data_direction == DMA_TO_DEVICE)
2910                 tf->flags |= ATA_TFLAG_WRITE;
2911
2912         qc->flags |= ATA_QCFLAG_RESULT_TF | ATA_QCFLAG_QUIET;
2913
2914         /*
2915          * Set transfer length.
2916          *
2917          * TODO: find out if we need to do more here to
2918          *       cover scatter/gather case.
2919          */
2920         ata_qc_set_pc_nbytes(qc);
2921
2922         /* We may not issue DMA commands if no DMA mode is set */
2923         if (tf->protocol == ATA_PROT_DMA && dev->dma_mode == 0)
2924                 goto invalid_fld;
2925
2926         /* sanity check for pio multi commands */
2927         if ((cdb[1] & 0xe0) && !is_multi_taskfile(tf))
2928                 goto invalid_fld;
2929
2930         if (is_multi_taskfile(tf)) {
2931                 unsigned int multi_count = 1 << (cdb[1] >> 5);
2932
2933                 /* compare the passed through multi_count
2934                  * with the cached multi_count of libata
2935                  */
2936                 if (multi_count != dev->multi_count)
2937                         ata_dev_printk(dev, KERN_WARNING,
2938                                        "invalid multi_count %u ignored\n",
2939                                        multi_count);
2940         }
2941
2942         /*
2943          * Filter SET_FEATURES - XFER MODE command -- otherwise,
2944          * SET_FEATURES - XFER MODE must be preceded/succeeded
2945          * by an update to hardware-specific registers for each
2946          * controller (i.e. the reason for ->set_piomode(),
2947          * ->set_dmamode(), and ->post_set_mode() hooks).
2948          */
2949         if (tf->command == ATA_CMD_SET_FEATURES &&
2950             tf->feature == SETFEATURES_XFER)
2951                 goto invalid_fld;
2952
2953         /*
2954          * Filter TPM commands by default. These provide an
2955          * essentially uncontrolled encrypted "back door" between
2956          * applications and the disk. Set libata.allow_tpm=1 if you
2957          * have a real reason for wanting to use them. This ensures
2958          * that installed software cannot easily mess stuff up without
2959          * user intent. DVR type users will probably ship with this enabled
2960          * for movie content management.
2961          *
2962          * Note that for ATA8 we can issue a DCS change and DCS freeze lock
2963          * for this and should do in future but that it is not sufficient as
2964          * DCS is an optional feature set. Thus we also do the software filter
2965          * so that we comply with the TC consortium stated goal that the user
2966          * can turn off TC features of their system.
2967          */
2968         if (tf->command >= 0x5C && tf->command <= 0x5F && !libata_allow_tpm)
2969                 goto invalid_fld;
2970
2971         return 0;
2972
2973  invalid_fld:
2974         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x00);
2975         /* "Invalid field in cdb" */
2976         return 1;
2977 }
2978
2979 static unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
2980 {
2981         struct ata_taskfile *tf = &qc->tf;
2982         struct scsi_cmnd *scmd = qc->scsicmd;
2983         struct ata_device *dev = qc->dev;
2984         const u8 *cdb = scmd->cmnd;
2985         u64 block;
2986         u32 n_block;
2987         u32 size;
2988         void *buf;
2989
2990         /* we may not issue DMA commands if no DMA mode is set */
2991         if (unlikely(!dev->dma_mode))
2992                 goto invalid_fld;
2993
2994         if (unlikely(scmd->cmd_len < 16))
2995                 goto invalid_fld;
2996         scsi_16_lba_len(cdb, &block, &n_block);
2997
2998         /* for now we only support WRITE SAME with the unmap bit set */
2999         if (unlikely(!(cdb[1] & 0x8)))
3000                 goto invalid_fld;
3001
3002         /*
3003          * WRITE SAME always has a sector sized buffer as payload, this
3004          * should never be a multiple entry S/G list.
3005          */
3006         if (!scsi_sg_count(scmd))
3007                 goto invalid_fld;
3008
3009         buf = page_address(sg_page(scsi_sglist(scmd)));
3010         size = ata_set_lba_range_entries(buf, 512, block, n_block);
3011
3012         tf->protocol = ATA_PROT_DMA;
3013         tf->hob_feature = 0;
3014         tf->feature = ATA_DSM_TRIM;
3015         tf->hob_nsect = (size / 512) >> 8;
3016         tf->nsect = size / 512;
3017         tf->command = ATA_CMD_DSM;
3018         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48 |
3019                      ATA_TFLAG_WRITE;
3020
3021         ata_qc_set_pc_nbytes(qc);
3022
3023         return 0;
3024
3025  invalid_fld:
3026         ata_scsi_set_sense(scmd, ILLEGAL_REQUEST, 0x24, 0x00);
3027         /* "Invalid field in cdb" */
3028         return 1;
3029 }
3030
3031 /**
3032  *      ata_get_xlat_func - check if SCSI to ATA translation is possible
3033  *      @dev: ATA device
3034  *      @cmd: SCSI command opcode to consider
3035  *
3036  *      Look up the SCSI command given, and determine whether the
3037  *      SCSI command is to be translated or simulated.
3038  *
3039  *      RETURNS:
3040  *      Pointer to translation function if possible, %NULL if not.
3041  */
3042
3043 static inline ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
3044 {
3045         switch (cmd) {
3046         case READ_6:
3047         case READ_10:
3048         case READ_16:
3049
3050         case WRITE_6:
3051         case WRITE_10:
3052         case WRITE_16:
3053                 return ata_scsi_rw_xlat;
3054
3055         case WRITE_SAME_16:
3056                 return ata_scsi_write_same_xlat;
3057
3058         case SYNCHRONIZE_CACHE:
3059                 if (ata_try_flush_cache(dev))
3060                         return ata_scsi_flush_xlat;
3061                 break;
3062
3063         case VERIFY:
3064         case VERIFY_16:
3065                 return ata_scsi_verify_xlat;
3066
3067         case ATA_12:
3068         case ATA_16:
3069                 return ata_scsi_pass_thru;
3070
3071         case START_STOP:
3072                 return ata_scsi_start_stop_xlat;
3073         }
3074
3075         return NULL;
3076 }
3077
3078 /**
3079  *      ata_scsi_dump_cdb - dump SCSI command contents to dmesg
3080  *      @ap: ATA port to which the command was being sent
3081  *      @cmd: SCSI command to dump
3082  *
3083  *      Prints the contents of a SCSI command via printk().
3084  */
3085
3086 static inline void ata_scsi_dump_cdb(struct ata_port *ap,
3087                                      struct scsi_cmnd *cmd)
3088 {
3089 #ifdef ATA_DEBUG
3090         struct scsi_device *scsidev = cmd->device;
3091         u8 *scsicmd = cmd->cmnd;
3092
3093         DPRINTK("CDB (%u:%d,%d,%d) %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
3094                 ap->print_id,
3095                 scsidev->channel, scsidev->id, scsidev->lun,
3096                 scsicmd[0], scsicmd[1], scsicmd[2], scsicmd[3],
3097                 scsicmd[4], scsicmd[5], scsicmd[6], scsicmd[7],
3098                 scsicmd[8]);
3099 #endif
3100 }
3101
3102 static inline int __ata_scsi_queuecmd(struct scsi_cmnd *scmd,
3103                                       void (*done)(struct scsi_cmnd *),
3104                                       struct ata_device *dev)
3105 {
3106         u8 scsi_op = scmd->cmnd[0];
3107         ata_xlat_func_t xlat_func;
3108         int rc = 0;
3109
3110         if (dev->class == ATA_DEV_ATA) {
3111                 if (unlikely(!scmd->cmd_len || scmd->cmd_len > dev->cdb_len))
3112                         goto bad_cdb_len;
3113
3114                 xlat_func = ata_get_xlat_func(dev, scsi_op);
3115         } else {
3116                 if (unlikely(!scmd->cmd_len))
3117                         goto bad_cdb_len;
3118
3119                 xlat_func = NULL;
3120                 if (likely((scsi_op != ATA_16) || !atapi_passthru16)) {
3121                         /* relay SCSI command to ATAPI device */
3122                         int len = COMMAND_SIZE(scsi_op);
3123                         if (unlikely(len > scmd->cmd_len || len > dev->cdb_len))
3124                                 goto bad_cdb_len;
3125
3126                         xlat_func = atapi_xlat;
3127                 } else {
3128                         /* ATA_16 passthru, treat as an ATA command */
3129                         if (unlikely(scmd->cmd_len > 16))
3130                                 goto bad_cdb_len;
3131
3132                         xlat_func = ata_get_xlat_func(dev, scsi_op);
3133                 }
3134         }
3135
3136         if (xlat_func)
3137                 rc = ata_scsi_translate(dev, scmd, done, xlat_func);
3138         else
3139                 ata_scsi_simulate(dev, scmd, done);
3140
3141         return rc;
3142
3143  bad_cdb_len:
3144         DPRINTK("bad CDB len=%u, scsi_op=0x%02x, max=%u\n",
3145                 scmd->cmd_len, scsi_op, dev->cdb_len);
3146         scmd->result = DID_ERROR << 16;
3147         done(scmd);
3148         return 0;
3149 }
3150
3151 /**
3152  *      ata_scsi_queuecmd - Issue SCSI cdb to libata-managed device
3153  *      @cmd: SCSI command to be sent
3154  *      @done: Completion function, called when command is complete
3155  *
3156  *      In some cases, this function translates SCSI commands into
3157  *      ATA taskfiles, and queues the taskfiles to be sent to
3158  *      hardware.  In other cases, this function simulates a
3159  *      SCSI device by evaluating and responding to certain
3160  *      SCSI commands.  This creates the overall effect of
3161  *      ATA and ATAPI devices appearing as SCSI devices.
3162  *
3163  *      LOCKING:
3164  *      Releases scsi-layer-held lock, and obtains host lock.
3165  *
3166  *      RETURNS:
3167  *      Return value from __ata_scsi_queuecmd() if @cmd can be queued,
3168  *      0 otherwise.
3169  */
3170 int ata_scsi_queuecmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
3171 {
3172         struct ata_port *ap;
3173         struct ata_device *dev;
3174         struct scsi_device *scsidev = cmd->device;
3175         struct Scsi_Host *shost = scsidev->host;
3176         int rc = 0;
3177
3178         ap = ata_shost_to_port(shost);
3179
3180         spin_unlock(shost->host_lock);
3181         spin_lock(ap->lock);
3182
3183         ata_scsi_dump_cdb(ap, cmd);
3184
3185         dev = ata_scsi_find_dev(ap, scsidev);
3186         if (likely(dev))
3187                 rc = __ata_scsi_queuecmd(cmd, done, dev);
3188         else {
3189                 cmd->result = (DID_BAD_TARGET << 16);
3190                 done(cmd);
3191         }
3192
3193         spin_unlock(ap->lock);
3194         spin_lock(shost->host_lock);
3195         return rc;
3196 }
3197
3198 /**
3199  *      ata_scsi_simulate - simulate SCSI command on ATA device
3200  *      @dev: the target device
3201  *      @cmd: SCSI command being sent to device.
3202  *      @done: SCSI command completion function.
3203  *
3204  *      Interprets and directly executes a select list of SCSI commands
3205  *      that can be handled internally.
3206  *
3207  *      LOCKING:
3208  *      spin_lock_irqsave(host lock)
3209  */
3210
3211 void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd,
3212                       void (*done)(struct scsi_cmnd *))
3213 {
3214         struct ata_scsi_args args;
3215         const u8 *scsicmd = cmd->cmnd;
3216         u8 tmp8;
3217
3218         args.dev = dev;
3219         args.id = dev->id;
3220         args.cmd = cmd;
3221         args.done = done;
3222
3223         switch(scsicmd[0]) {
3224         /* TODO: worth improving? */
3225         case FORMAT_UNIT:
3226                 ata_scsi_invalid_field(cmd, done);
3227                 break;
3228
3229         case INQUIRY:
3230                 if (scsicmd[1] & 2)                /* is CmdDt set?  */
3231                         ata_scsi_invalid_field(cmd, done);
3232                 else if ((scsicmd[1] & 1) == 0)    /* is EVPD clear? */
3233                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_std);
3234                 else switch (scsicmd[2]) {
3235                 case 0x00:
3236                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_00);
3237                         break;
3238                 case 0x80:
3239                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_80);
3240                         break;
3241                 case 0x83:
3242                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_83);
3243                         break;
3244                 case 0x89:
3245                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_89);
3246                         break;
3247                 case 0xb0:
3248                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b0);
3249                         break;
3250                 case 0xb1:
3251                         ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b1);
3252                         break;
3253                 default:
3254                         ata_scsi_invalid_field(cmd, done);
3255                         break;
3256                 }
3257                 break;
3258
3259         case MODE_SENSE:
3260         case MODE_SENSE_10:
3261                 ata_scsi_rbuf_fill(&args, ata_scsiop_mode_sense);
3262                 break;
3263
3264         case MODE_SELECT:       /* unconditionally return */
3265         case MODE_SELECT_10:    /* bad-field-in-cdb */
3266                 ata_scsi_invalid_field(cmd, done);
3267                 break;
3268
3269         case READ_CAPACITY:
3270                 ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
3271                 break;
3272
3273         case SERVICE_ACTION_IN:
3274                 if ((scsicmd[1] & 0x1f) == SAI_READ_CAPACITY_16)
3275                         ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
3276                 else
3277                         ata_scsi_invalid_field(cmd, done);
3278                 break;
3279
3280         case REPORT_LUNS:
3281                 ata_scsi_rbuf_fill(&args, ata_scsiop_report_luns);
3282                 break;
3283
3284         case REQUEST_SENSE:
3285                 ata_scsi_set_sense(cmd, 0, 0, 0);
3286                 cmd->result = (DRIVER_SENSE << 24);
3287                 done(cmd);
3288                 break;
3289
3290         /* if we reach this, then writeback caching is disabled,
3291          * turning this into a no-op.
3292          */
3293         case SYNCHRONIZE_CACHE:
3294                 /* fall through */
3295
3296         /* no-op's, complete with success */
3297         case REZERO_UNIT:
3298         case SEEK_6:
3299         case SEEK_10:
3300         case TEST_UNIT_READY:
3301                 ata_scsi_rbuf_fill(&args, ata_scsiop_noop);
3302                 break;
3303
3304         case SEND_DIAGNOSTIC:
3305                 tmp8 = scsicmd[1] & ~(1 << 3);
3306                 if ((tmp8 == 0x4) && (!scsicmd[3]) && (!scsicmd[4]))
3307                         ata_scsi_rbuf_fill(&args, ata_scsiop_noop);
3308                 else
3309                         ata_scsi_invalid_field(cmd, done);
3310                 break;
3311
3312         /* all other commands */
3313         default:
3314                 ata_scsi_set_sense(cmd, ILLEGAL_REQUEST, 0x20, 0x0);
3315                 /* "Invalid command operation code" */
3316                 done(cmd);
3317                 break;
3318         }
3319 }
3320
3321 int ata_scsi_add_hosts(struct ata_host *host, struct scsi_host_template *sht)
3322 {
3323         int i, rc;
3324
3325         for (i = 0; i < host->n_ports; i++) {
3326                 struct ata_port *ap = host->ports[i];
3327                 struct Scsi_Host *shost;
3328
3329                 rc = -ENOMEM;
3330                 shost = scsi_host_alloc(sht, sizeof(struct ata_port *));
3331                 if (!shost)
3332                         goto err_alloc;
3333
3334                 *(struct ata_port **)&shost->hostdata[0] = ap;
3335                 ap->scsi_host = shost;
3336
3337                 shost->transportt = &ata_scsi_transport_template;
3338                 shost->unique_id = ap->print_id;
3339                 shost->max_id = 16;
3340                 shost->max_lun = 1;
3341                 shost->max_channel = 1;
3342                 shost->max_cmd_len = 16;
3343
3344                 /* Schedule policy is determined by ->qc_defer()
3345                  * callback and it needs to see every deferred qc.
3346                  * Set host_blocked to 1 to prevent SCSI midlayer from
3347                  * automatically deferring requests.
3348                  */
3349                 shost->max_host_blocked = 1;
3350
3351                 rc = scsi_add_host(ap->scsi_host, ap->host->dev);
3352                 if (rc)
3353                         goto err_add;
3354         }
3355
3356         return 0;
3357
3358  err_add:
3359         scsi_host_put(host->ports[i]->scsi_host);
3360  err_alloc:
3361         while (--i >= 0) {
3362                 struct Scsi_Host *shost = host->ports[i]->scsi_host;
3363
3364                 scsi_remove_host(shost);
3365                 scsi_host_put(shost);
3366         }
3367         return rc;
3368 }
3369
3370 void ata_scsi_scan_host(struct ata_port *ap, int sync)
3371 {
3372         int tries = 5;
3373         struct ata_device *last_failed_dev = NULL;
3374         struct ata_link *link;
3375         struct ata_device *dev;
3376
3377  repeat:
3378         ata_for_each_link(link, ap, EDGE) {
3379                 ata_for_each_dev(dev, link, ENABLED) {
3380                         struct scsi_device *sdev;
3381                         int channel = 0, id = 0;
3382
3383                         if (dev->sdev)
3384                                 continue;
3385
3386                         if (ata_is_host_link(link))
3387                                 id = dev->devno;
3388                         else
3389                                 channel = link->pmp;
3390
3391                         sdev = __scsi_add_device(ap->scsi_host, channel, id, 0,
3392                                                  NULL);
3393                         if (!IS_ERR(sdev)) {
3394                                 dev->sdev = sdev;
3395                                 scsi_device_put(sdev);
3396                         }
3397                 }
3398         }
3399
3400         /* If we scanned while EH was in progress or allocation
3401          * failure occurred, scan would have failed silently.  Check
3402          * whether all devices are attached.
3403          */
3404         ata_for_each_link(link, ap, EDGE) {
3405                 ata_for_each_dev(dev, link, ENABLED) {
3406                         if (!dev->sdev)
3407                                 goto exit_loop;
3408                 }
3409         }
3410  exit_loop:
3411         if (!link)
3412                 return;
3413
3414         /* we're missing some SCSI devices */
3415         if (sync) {
3416                 /* If caller requested synchrnous scan && we've made
3417                  * any progress, sleep briefly and repeat.
3418                  */
3419                 if (dev != last_failed_dev) {
3420                         msleep(100);
3421                         last_failed_dev = dev;
3422                         goto repeat;
3423                 }
3424
3425                 /* We might be failing to detect boot device, give it
3426                  * a few more chances.
3427                  */
3428                 if (--tries) {
3429                         msleep(100);
3430                         goto repeat;
3431                 }
3432
3433                 ata_port_printk(ap, KERN_ERR, "WARNING: synchronous SCSI scan "
3434                                 "failed without making any progress,\n"
3435                                 "                  switching to async\n");
3436         }
3437
3438         queue_delayed_work(system_long_wq, &ap->hotplug_task,
3439                            round_jiffies_relative(HZ));
3440 }
3441
3442 /**
3443  *      ata_scsi_offline_dev - offline attached SCSI device
3444  *      @dev: ATA device to offline attached SCSI device for
3445  *
3446  *      This function is called from ata_eh_hotplug() and responsible
3447  *      for taking the SCSI device attached to @dev offline.  This
3448  *      function is called with host lock which protects dev->sdev
3449  *      against clearing.
3450  *
3451  *      LOCKING:
3452  *      spin_lock_irqsave(host lock)
3453  *
3454  *      RETURNS:
3455  *      1 if attached SCSI device exists, 0 otherwise.
3456  */
3457 int ata_scsi_offline_dev(struct ata_device *dev)
3458 {
3459         if (dev->sdev) {
3460                 scsi_device_set_state(dev->sdev, SDEV_OFFLINE);
3461                 return 1;
3462         }
3463         return 0;
3464 }
3465
3466 /**
3467  *      ata_scsi_remove_dev - remove attached SCSI device
3468  *      @dev: ATA device to remove attached SCSI device for
3469  *
3470  *      This function is called from ata_eh_scsi_hotplug() and
3471  *      responsible for removing the SCSI device attached to @dev.
3472  *
3473  *      LOCKING:
3474  *      Kernel thread context (may sleep).
3475  */
3476 static void ata_scsi_remove_dev(struct ata_device *dev)
3477 {
3478         struct ata_port *ap = dev->link->ap;
3479         struct scsi_device *sdev;
3480         unsigned long flags;
3481
3482         /* Alas, we need to grab scan_mutex to ensure SCSI device
3483          * state doesn't change underneath us and thus
3484          * scsi_device_get() always succeeds.  The mutex locking can
3485          * be removed if there is __scsi_device_get() interface which
3486          * increments reference counts regardless of device state.
3487          */
3488         mutex_lock(&ap->scsi_host->scan_mutex);
3489         spin_lock_irqsave(ap->lock, flags);
3490
3491         /* clearing dev->sdev is protected by host lock */
3492         sdev = dev->sdev;
3493         dev->sdev = NULL;
3494
3495         if (sdev) {
3496                 /* If user initiated unplug races with us, sdev can go
3497                  * away underneath us after the host lock and
3498                  * scan_mutex are released.  Hold onto it.
3499                  */
3500                 if (scsi_device_get(sdev) == 0) {
3501                         /* The following ensures the attached sdev is
3502                          * offline on return from ata_scsi_offline_dev()
3503                          * regardless it wins or loses the race
3504                          * against this function.
3505                          */
3506                         scsi_device_set_state(sdev, SDEV_OFFLINE);
3507                 } else {
3508                         WARN_ON(1);
3509                         sdev = NULL;
3510                 }
3511         }
3512
3513         spin_unlock_irqrestore(ap->lock, flags);
3514         mutex_unlock(&ap->scsi_host->scan_mutex);
3515
3516         if (sdev) {
3517                 ata_dev_printk(dev, KERN_INFO, "detaching (SCSI %s)\n",
3518                                dev_name(&sdev->sdev_gendev));
3519
3520                 scsi_remove_device(sdev);
3521                 scsi_device_put(sdev);
3522         }
3523 }
3524
3525 static void ata_scsi_handle_link_detach(struct ata_link *link)
3526 {
3527         struct ata_port *ap = link->ap;
3528         struct ata_device *dev;
3529
3530         ata_for_each_dev(dev, link, ALL) {
3531                 unsigned long flags;
3532
3533                 if (!(dev->flags & ATA_DFLAG_DETACHED))
3534                         continue;
3535
3536                 spin_lock_irqsave(ap->lock, flags);
3537                 dev->flags &= ~ATA_DFLAG_DETACHED;
3538                 spin_unlock_irqrestore(ap->lock, flags);
3539
3540                 ata_scsi_remove_dev(dev);
3541         }
3542 }
3543
3544 /**
3545  *      ata_scsi_media_change_notify - send media change event
3546  *      @dev: Pointer to the disk device with media change event
3547  *
3548  *      Tell the block layer to send a media change notification
3549  *      event.
3550  *
3551  *      LOCKING:
3552  *      spin_lock_irqsave(host lock)
3553  */
3554 void ata_scsi_media_change_notify(struct ata_device *dev)
3555 {
3556         if (dev->sdev)
3557                 sdev_evt_send_simple(dev->sdev, SDEV_EVT_MEDIA_CHANGE,
3558                                      GFP_ATOMIC);
3559 }
3560
3561 /**
3562  *      ata_scsi_hotplug - SCSI part of hotplug
3563  *      @work: Pointer to ATA port to perform SCSI hotplug on
3564  *
3565  *      Perform SCSI part of hotplug.  It's executed from a separate
3566  *      workqueue after EH completes.  This is necessary because SCSI
3567  *      hot plugging requires working EH and hot unplugging is
3568  *      synchronized with hot plugging with a mutex.
3569  *
3570  *      LOCKING:
3571  *      Kernel thread context (may sleep).
3572  */
3573 void ata_scsi_hotplug(struct work_struct *work)
3574 {
3575         struct ata_port *ap =
3576                 container_of(work, struct ata_port, hotplug_task.work);
3577         int i;
3578
3579         if (ap->pflags & ATA_PFLAG_UNLOADING) {
3580                 DPRINTK("ENTER/EXIT - unloading\n");
3581                 return;
3582         }
3583
3584         DPRINTK("ENTER\n");
3585         mutex_lock(&ap->scsi_scan_mutex);
3586
3587         /* Unplug detached devices.  We cannot use link iterator here
3588          * because PMP links have to be scanned even if PMP is
3589          * currently not attached.  Iterate manually.
3590          */
3591         ata_scsi_handle_link_detach(&ap->link);
3592         if (ap->pmp_link)
3593                 for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
3594                         ata_scsi_handle_link_detach(&ap->pmp_link[i]);
3595
3596         /* scan for new ones */
3597         ata_scsi_scan_host(ap, 0);
3598
3599         mutex_unlock(&ap->scsi_scan_mutex);
3600         DPRINTK("EXIT\n");
3601 }
3602
3603 /**
3604  *      ata_scsi_user_scan - indication for user-initiated bus scan
3605  *      @shost: SCSI host to scan
3606  *      @channel: Channel to scan
3607  *      @id: ID to scan
3608  *      @lun: LUN to scan
3609  *
3610  *      This function is called when user explicitly requests bus
3611  *      scan.  Set probe pending flag and invoke EH.
3612  *
3613  *      LOCKING:
3614  *      SCSI layer (we don't care)
3615  *
3616  *      RETURNS:
3617  *      Zero.
3618  */
3619 static int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel,
3620                               unsigned int id, unsigned int lun)
3621 {
3622         struct ata_port *ap = ata_shost_to_port(shost);
3623         unsigned long flags;
3624         int devno, rc = 0;
3625
3626         if (!ap->ops->error_handler)
3627                 return -EOPNOTSUPP;
3628
3629         if (lun != SCAN_WILD_CARD && lun)
3630                 return -EINVAL;
3631
3632         if (!sata_pmp_attached(ap)) {
3633                 if (channel != SCAN_WILD_CARD && channel)
3634                         return -EINVAL;
3635                 devno = id;
3636         } else {
3637                 if (id != SCAN_WILD_CARD && id)
3638                         return -EINVAL;
3639                 devno = channel;
3640         }
3641
3642         spin_lock_irqsave(ap->lock, flags);
3643
3644         if (devno == SCAN_WILD_CARD) {
3645                 struct ata_link *link;
3646
3647                 ata_for_each_link(link, ap, EDGE) {
3648                         struct ata_eh_info *ehi = &link->eh_info;
3649                         ehi->probe_mask |= ATA_ALL_DEVICES;
3650                         ehi->action |= ATA_EH_RESET;
3651                 }
3652         } else {
3653                 struct ata_device *dev = ata_find_dev(ap, devno);
3654
3655                 if (dev) {
3656                         struct ata_eh_info *ehi = &dev->link->eh_info;
3657                         ehi->probe_mask |= 1 << dev->devno;
3658                         ehi->action |= ATA_EH_RESET;
3659                 } else
3660                         rc = -EINVAL;
3661         }
3662
3663         if (rc == 0) {
3664                 ata_port_schedule_eh(ap);
3665                 spin_unlock_irqrestore(ap->lock, flags);
3666                 ata_port_wait_eh(ap);
3667         } else
3668                 spin_unlock_irqrestore(ap->lock, flags);
3669
3670         return rc;
3671 }
3672
3673 /**
3674  *      ata_scsi_dev_rescan - initiate scsi_rescan_device()
3675  *      @work: Pointer to ATA port to perform scsi_rescan_device()
3676  *
3677  *      After ATA pass thru (SAT) commands are executed successfully,
3678  *      libata need to propagate the changes to SCSI layer.
3679  *
3680  *      LOCKING:
3681  *      Kernel thread context (may sleep).
3682  */
3683 void ata_scsi_dev_rescan(struct work_struct *work)
3684 {
3685         struct ata_port *ap =
3686                 container_of(work, struct ata_port, scsi_rescan_task);
3687         struct ata_link *link;
3688         struct ata_device *dev;
3689         unsigned long flags;
3690
3691         mutex_lock(&ap->scsi_scan_mutex);
3692         spin_lock_irqsave(ap->lock, flags);
3693
3694         ata_for_each_link(link, ap, EDGE) {
3695                 ata_for_each_dev(dev, link, ENABLED) {
3696                         struct scsi_device *sdev = dev->sdev;
3697
3698                         if (!sdev)
3699                                 continue;
3700                         if (scsi_device_get(sdev))
3701                                 continue;
3702
3703                         spin_unlock_irqrestore(ap->lock, flags);
3704                         scsi_rescan_device(&(sdev->sdev_gendev));
3705                         scsi_device_put(sdev);
3706                         spin_lock_irqsave(ap->lock, flags);
3707                 }
3708         }
3709
3710         spin_unlock_irqrestore(ap->lock, flags);
3711         mutex_unlock(&ap->scsi_scan_mutex);
3712 }
3713
3714 /**
3715  *      ata_sas_port_alloc - Allocate port for a SAS attached SATA device
3716  *      @host: ATA host container for all SAS ports
3717  *      @port_info: Information from low-level host driver
3718  *      @shost: SCSI host that the scsi device is attached to
3719  *
3720  *      LOCKING:
3721  *      PCI/etc. bus probe sem.
3722  *
3723  *      RETURNS:
3724  *      ata_port pointer on success / NULL on failure.
3725  */
3726
3727 struct ata_port *ata_sas_port_alloc(struct ata_host *host,
3728                                     struct ata_port_info *port_info,
3729                                     struct Scsi_Host *shost)
3730 {
3731         struct ata_port *ap;
3732
3733         ap = ata_port_alloc(host);
3734         if (!ap)
3735                 return NULL;
3736
3737         ap->port_no = 0;
3738         ap->lock = shost->host_lock;
3739         ap->pio_mask = port_info->pio_mask;
3740         ap->mwdma_mask = port_info->mwdma_mask;
3741         ap->udma_mask = port_info->udma_mask;
3742         ap->flags |= port_info->flags;
3743         ap->ops = port_info->port_ops;
3744         ap->cbl = ATA_CBL_SATA;
3745
3746         return ap;
3747 }
3748 EXPORT_SYMBOL_GPL(ata_sas_port_alloc);
3749
3750 /**
3751  *      ata_sas_port_start - Set port up for dma.
3752  *      @ap: Port to initialize
3753  *
3754  *      Called just after data structures for each port are
3755  *      initialized.
3756  *
3757  *      May be used as the port_start() entry in ata_port_operations.
3758  *
3759  *      LOCKING:
3760  *      Inherited from caller.
3761  */
3762 int ata_sas_port_start(struct ata_port *ap)
3763 {
3764         return 0;
3765 }
3766 EXPORT_SYMBOL_GPL(ata_sas_port_start);
3767
3768 /**
3769  *      ata_port_stop - Undo ata_sas_port_start()
3770  *      @ap: Port to shut down
3771  *
3772  *      May be used as the port_stop() entry in ata_port_operations.
3773  *
3774  *      LOCKING:
3775  *      Inherited from caller.
3776  */
3777
3778 void ata_sas_port_stop(struct ata_port *ap)
3779 {
3780 }
3781 EXPORT_SYMBOL_GPL(ata_sas_port_stop);
3782
3783 /**
3784  *      ata_sas_port_init - Initialize a SATA device
3785  *      @ap: SATA port to initialize
3786  *
3787  *      LOCKING:
3788  *      PCI/etc. bus probe sem.
3789  *
3790  *      RETURNS:
3791  *      Zero on success, non-zero on error.
3792  */
3793
3794 int ata_sas_port_init(struct ata_port *ap)
3795 {
3796         int rc = ap->ops->port_start(ap);
3797
3798         if (!rc) {
3799                 ap->print_id = ata_print_id++;
3800                 rc = ata_bus_probe(ap);
3801         }
3802
3803         return rc;
3804 }
3805 EXPORT_SYMBOL_GPL(ata_sas_port_init);
3806
3807 /**
3808  *      ata_sas_port_destroy - Destroy a SATA port allocated by ata_sas_port_alloc
3809  *      @ap: SATA port to destroy
3810  *
3811  */
3812
3813 void ata_sas_port_destroy(struct ata_port *ap)
3814 {
3815         if (ap->ops->port_stop)
3816                 ap->ops->port_stop(ap);
3817         kfree(ap);
3818 }
3819 EXPORT_SYMBOL_GPL(ata_sas_port_destroy);
3820
3821 /**
3822  *      ata_sas_slave_configure - Default slave_config routine for libata devices
3823  *      @sdev: SCSI device to configure
3824  *      @ap: ATA port to which SCSI device is attached
3825  *
3826  *      RETURNS:
3827  *      Zero.
3828  */
3829
3830 int ata_sas_slave_configure(struct scsi_device *sdev, struct ata_port *ap)
3831 {
3832         ata_scsi_sdev_config(sdev);
3833         ata_scsi_dev_config(sdev, ap->link.device);
3834         return 0;
3835 }
3836 EXPORT_SYMBOL_GPL(ata_sas_slave_configure);
3837
3838 /**
3839  *      ata_sas_queuecmd - Issue SCSI cdb to libata-managed device
3840  *      @cmd: SCSI command to be sent
3841  *      @done: Completion function, called when command is complete
3842  *      @ap:    ATA port to which the command is being sent
3843  *
3844  *      RETURNS:
3845  *      Return value from __ata_scsi_queuecmd() if @cmd can be queued,
3846  *      0 otherwise.
3847  */
3848
3849 int ata_sas_queuecmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *),
3850                      struct ata_port *ap)
3851 {
3852         int rc = 0;
3853
3854         ata_scsi_dump_cdb(ap, cmd);
3855
3856         if (likely(ata_dev_enabled(ap->link.device)))
3857                 rc = __ata_scsi_queuecmd(cmd, done, ap->link.device);
3858         else {
3859                 cmd->result = (DID_BAD_TARGET << 16);
3860                 done(cmd);
3861         }
3862         return rc;
3863 }
3864 EXPORT_SYMBOL_GPL(ata_sas_queuecmd);