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