xref: /linux/drivers/ata/libata-scsi.c (revision c6f2e6b6eaaf883df482cb94f302acad9b80a2a4)
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 
1664 	/* For ATA pass thru (SAT) commands, generate a sense block if
1665 	 * user mandated it or if there's an error.  Note that if we
1666 	 * generate because the user forced us to [CK_COND =1], a check
1667 	 * condition is generated and the ATA register values are returned
1668 	 * whether the command completed successfully or not. If there
1669 	 * was no error, we use the following sense data:
1670 	 * sk = RECOVERED ERROR
1671 	 * asc,ascq = ATA PASS-THROUGH INFORMATION AVAILABLE
1672 	 */
1673 	if (((cdb[0] == ATA_16) || (cdb[0] == ATA_12)) &&
1674 	    ((cdb[2] & 0x20) || need_sense))
1675 		ata_gen_passthru_sense(qc);
1676 	else if (qc->flags & ATA_QCFLAG_SENSE_VALID)
1677 		cmd->result = SAM_STAT_CHECK_CONDITION;
1678 	else if (need_sense)
1679 		ata_gen_ata_sense(qc);
1680 	else
1681 		cmd->result = SAM_STAT_GOOD;
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  * We can turn this into a real blacklist if it's needed, for now just
2250  * blacklist any Maxtor BANC1G10 revision firmware
2251  */
2252 static int ata_dev_supports_fua(u16 *id)
2253 {
2254 	unsigned char model[ATA_ID_PROD_LEN + 1], fw[ATA_ID_FW_REV_LEN + 1];
2255 
2256 	if (!libata_fua)
2257 		return 0;
2258 	if (!ata_id_has_fua(id))
2259 		return 0;
2260 
2261 	ata_id_c_string(id, model, ATA_ID_PROD, sizeof(model));
2262 	ata_id_c_string(id, fw, ATA_ID_FW_REV, sizeof(fw));
2263 
2264 	if (strcmp(model, "Maxtor"))
2265 		return 1;
2266 	if (strcmp(fw, "BANC1G10"))
2267 		return 1;
2268 
2269 	return 0; /* blacklisted */
2270 }
2271 
2272 /**
2273  *	ata_scsiop_mode_sense - Simulate MODE SENSE 6, 10 commands
2274  *	@args: device IDENTIFY data / SCSI command of interest.
2275  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2276  *
2277  *	Simulate MODE SENSE commands. Assume this is invoked for direct
2278  *	access devices (e.g. disks) only. There should be no block
2279  *	descriptor for other device types.
2280  *
2281  *	LOCKING:
2282  *	spin_lock_irqsave(host lock)
2283  */
2284 static unsigned int ata_scsiop_mode_sense(struct ata_scsi_args *args, u8 *rbuf)
2285 {
2286 	struct ata_device *dev = args->dev;
2287 	u8 *scsicmd = args->cmd->cmnd, *p = rbuf;
2288 	static const u8 sat_blk_desc[] = {
2289 		0, 0, 0, 0,	/* number of blocks: sat unspecified */
2290 		0,
2291 		0, 0x2, 0x0	/* block length: 512 bytes */
2292 	};
2293 	u8 pg, spg;
2294 	unsigned int ebd, page_control, six_byte;
2295 	u8 dpofua, bp = 0xff;
2296 	u16 fp;
2297 
2298 	six_byte = (scsicmd[0] == MODE_SENSE);
2299 	ebd = !(scsicmd[1] & 0x8);      /* dbd bit inverted == edb */
2300 	/*
2301 	 * LLBA bit in msense(10) ignored (compliant)
2302 	 */
2303 
2304 	page_control = scsicmd[2] >> 6;
2305 	switch (page_control) {
2306 	case 0: /* current */
2307 	case 1: /* changeable */
2308 	case 2: /* defaults */
2309 		break;  /* supported */
2310 	case 3: /* saved */
2311 		goto saving_not_supp;
2312 	default:
2313 		fp = 2;
2314 		bp = 6;
2315 		goto invalid_fld;
2316 	}
2317 
2318 	if (six_byte)
2319 		p += 4 + (ebd ? 8 : 0);
2320 	else
2321 		p += 8 + (ebd ? 8 : 0);
2322 
2323 	pg = scsicmd[2] & 0x3f;
2324 	spg = scsicmd[3];
2325 	/*
2326 	 * No mode subpages supported (yet) but asking for _all_
2327 	 * subpages may be valid
2328 	 */
2329 	if (spg && (spg != ALL_SUB_MPAGES)) {
2330 		fp = 3;
2331 		goto invalid_fld;
2332 	}
2333 
2334 	switch(pg) {
2335 	case RW_RECOVERY_MPAGE:
2336 		p += ata_msense_rw_recovery(p, page_control == 1);
2337 		break;
2338 
2339 	case CACHE_MPAGE:
2340 		p += ata_msense_caching(args->id, p, page_control == 1);
2341 		break;
2342 
2343 	case CONTROL_MPAGE:
2344 		p += ata_msense_control(args->dev, p, page_control == 1);
2345 		break;
2346 
2347 	case ALL_MPAGES:
2348 		p += ata_msense_rw_recovery(p, page_control == 1);
2349 		p += ata_msense_caching(args->id, p, page_control == 1);
2350 		p += ata_msense_control(args->dev, p, page_control == 1);
2351 		break;
2352 
2353 	default:		/* invalid page code */
2354 		fp = 2;
2355 		goto invalid_fld;
2356 	}
2357 
2358 	dpofua = 0;
2359 	if (ata_dev_supports_fua(args->id) && (dev->flags & ATA_DFLAG_LBA48) &&
2360 	    (!(dev->flags & ATA_DFLAG_PIO) || dev->multi_count))
2361 		dpofua = 1 << 4;
2362 
2363 	if (six_byte) {
2364 		rbuf[0] = p - rbuf - 1;
2365 		rbuf[2] |= dpofua;
2366 		if (ebd) {
2367 			rbuf[3] = sizeof(sat_blk_desc);
2368 			memcpy(rbuf + 4, sat_blk_desc, sizeof(sat_blk_desc));
2369 		}
2370 	} else {
2371 		unsigned int output_len = p - rbuf - 2;
2372 
2373 		rbuf[0] = output_len >> 8;
2374 		rbuf[1] = output_len;
2375 		rbuf[3] |= dpofua;
2376 		if (ebd) {
2377 			rbuf[7] = sizeof(sat_blk_desc);
2378 			memcpy(rbuf + 8, sat_blk_desc, sizeof(sat_blk_desc));
2379 		}
2380 	}
2381 	return 0;
2382 
2383 invalid_fld:
2384 	ata_scsi_set_invalid_field(dev, args->cmd, fp, bp);
2385 	return 1;
2386 
2387 saving_not_supp:
2388 	ata_scsi_set_sense(dev, args->cmd, ILLEGAL_REQUEST, 0x39, 0x0);
2389 	 /* "Saving parameters not supported" */
2390 	return 1;
2391 }
2392 
2393 /**
2394  *	ata_scsiop_read_cap - Simulate READ CAPACITY[ 16] commands
2395  *	@args: device IDENTIFY data / SCSI command of interest.
2396  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2397  *
2398  *	Simulate READ CAPACITY commands.
2399  *
2400  *	LOCKING:
2401  *	None.
2402  */
2403 static unsigned int ata_scsiop_read_cap(struct ata_scsi_args *args, u8 *rbuf)
2404 {
2405 	struct ata_device *dev = args->dev;
2406 	u64 last_lba = dev->n_sectors - 1; /* LBA of the last block */
2407 	u32 sector_size; /* physical sector size in bytes */
2408 	u8 log2_per_phys;
2409 	u16 lowest_aligned;
2410 
2411 	sector_size = ata_id_logical_sector_size(dev->id);
2412 	log2_per_phys = ata_id_log2_per_physical_sector(dev->id);
2413 	lowest_aligned = ata_id_logical_sector_offset(dev->id, log2_per_phys);
2414 
2415 	if (args->cmd->cmnd[0] == READ_CAPACITY) {
2416 		if (last_lba >= 0xffffffffULL)
2417 			last_lba = 0xffffffff;
2418 
2419 		/* sector count, 32-bit */
2420 		rbuf[0] = last_lba >> (8 * 3);
2421 		rbuf[1] = last_lba >> (8 * 2);
2422 		rbuf[2] = last_lba >> (8 * 1);
2423 		rbuf[3] = last_lba;
2424 
2425 		/* sector size */
2426 		rbuf[4] = sector_size >> (8 * 3);
2427 		rbuf[5] = sector_size >> (8 * 2);
2428 		rbuf[6] = sector_size >> (8 * 1);
2429 		rbuf[7] = sector_size;
2430 	} else {
2431 		/* sector count, 64-bit */
2432 		rbuf[0] = last_lba >> (8 * 7);
2433 		rbuf[1] = last_lba >> (8 * 6);
2434 		rbuf[2] = last_lba >> (8 * 5);
2435 		rbuf[3] = last_lba >> (8 * 4);
2436 		rbuf[4] = last_lba >> (8 * 3);
2437 		rbuf[5] = last_lba >> (8 * 2);
2438 		rbuf[6] = last_lba >> (8 * 1);
2439 		rbuf[7] = last_lba;
2440 
2441 		/* sector size */
2442 		rbuf[ 8] = sector_size >> (8 * 3);
2443 		rbuf[ 9] = sector_size >> (8 * 2);
2444 		rbuf[10] = sector_size >> (8 * 1);
2445 		rbuf[11] = sector_size;
2446 
2447 		rbuf[12] = 0;
2448 		rbuf[13] = log2_per_phys;
2449 		rbuf[14] = (lowest_aligned >> 8) & 0x3f;
2450 		rbuf[15] = lowest_aligned;
2451 
2452 		if (ata_id_has_trim(args->id) &&
2453 		    !(dev->horkage & ATA_HORKAGE_NOTRIM)) {
2454 			rbuf[14] |= 0x80; /* LBPME */
2455 
2456 			if (ata_id_has_zero_after_trim(args->id) &&
2457 			    dev->horkage & ATA_HORKAGE_ZERO_AFTER_TRIM) {
2458 				ata_dev_info(dev, "Enabling discard_zeroes_data\n");
2459 				rbuf[14] |= 0x40; /* LBPRZ */
2460 			}
2461 		}
2462 		if (ata_id_zoned_cap(args->id) ||
2463 		    args->dev->class == ATA_DEV_ZAC)
2464 			rbuf[12] = (1 << 4); /* RC_BASIS */
2465 	}
2466 	return 0;
2467 }
2468 
2469 /**
2470  *	ata_scsiop_report_luns - Simulate REPORT LUNS command
2471  *	@args: device IDENTIFY data / SCSI command of interest.
2472  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2473  *
2474  *	Simulate REPORT LUNS command.
2475  *
2476  *	LOCKING:
2477  *	spin_lock_irqsave(host lock)
2478  */
2479 static unsigned int ata_scsiop_report_luns(struct ata_scsi_args *args, u8 *rbuf)
2480 {
2481 	rbuf[3] = 8;	/* just one lun, LUN 0, size 8 bytes */
2482 
2483 	return 0;
2484 }
2485 
2486 static void atapi_sense_complete(struct ata_queued_cmd *qc)
2487 {
2488 	if (qc->err_mask && ((qc->err_mask & AC_ERR_DEV) == 0)) {
2489 		/* FIXME: not quite right; we don't want the
2490 		 * translation of taskfile registers into
2491 		 * a sense descriptors, since that's only
2492 		 * correct for ATA, not ATAPI
2493 		 */
2494 		ata_gen_passthru_sense(qc);
2495 	}
2496 
2497 	ata_qc_done(qc);
2498 }
2499 
2500 /* is it pointless to prefer PIO for "safety reasons"? */
2501 static inline int ata_pio_use_silly(struct ata_port *ap)
2502 {
2503 	return (ap->flags & ATA_FLAG_PIO_DMA);
2504 }
2505 
2506 static void atapi_request_sense(struct ata_queued_cmd *qc)
2507 {
2508 	struct ata_port *ap = qc->ap;
2509 	struct scsi_cmnd *cmd = qc->scsicmd;
2510 
2511 	memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
2512 
2513 #ifdef CONFIG_ATA_SFF
2514 	if (ap->ops->sff_tf_read)
2515 		ap->ops->sff_tf_read(ap, &qc->tf);
2516 #endif
2517 
2518 	/* fill these in, for the case where they are -not- overwritten */
2519 	cmd->sense_buffer[0] = 0x70;
2520 	cmd->sense_buffer[2] = qc->tf.error >> 4;
2521 
2522 	ata_qc_reinit(qc);
2523 
2524 	/* setup sg table and init transfer direction */
2525 	sg_init_one(&qc->sgent, cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
2526 	ata_sg_init(qc, &qc->sgent, 1);
2527 	qc->dma_dir = DMA_FROM_DEVICE;
2528 
2529 	memset(&qc->cdb, 0, qc->dev->cdb_len);
2530 	qc->cdb[0] = REQUEST_SENSE;
2531 	qc->cdb[4] = SCSI_SENSE_BUFFERSIZE;
2532 
2533 	qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2534 	qc->tf.command = ATA_CMD_PACKET;
2535 
2536 	if (ata_pio_use_silly(ap)) {
2537 		qc->tf.protocol = ATAPI_PROT_DMA;
2538 		qc->tf.feature |= ATAPI_PKT_DMA;
2539 	} else {
2540 		qc->tf.protocol = ATAPI_PROT_PIO;
2541 		qc->tf.lbam = SCSI_SENSE_BUFFERSIZE;
2542 		qc->tf.lbah = 0;
2543 	}
2544 	qc->nbytes = SCSI_SENSE_BUFFERSIZE;
2545 
2546 	qc->complete_fn = atapi_sense_complete;
2547 
2548 	ata_qc_issue(qc);
2549 }
2550 
2551 /*
2552  * ATAPI devices typically report zero for their SCSI version, and sometimes
2553  * deviate from the spec WRT response data format.  If SCSI version is
2554  * reported as zero like normal, then we make the following fixups:
2555  *   1) Fake MMC-5 version, to indicate to the Linux scsi midlayer this is a
2556  *	modern device.
2557  *   2) Ensure response data format / ATAPI information are always correct.
2558  */
2559 static void atapi_fixup_inquiry(struct scsi_cmnd *cmd)
2560 {
2561 	u8 buf[4];
2562 
2563 	sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, 4);
2564 	if (buf[2] == 0) {
2565 		buf[2] = 0x5;
2566 		buf[3] = 0x32;
2567 	}
2568 	sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, 4);
2569 }
2570 
2571 static void atapi_qc_complete(struct ata_queued_cmd *qc)
2572 {
2573 	struct scsi_cmnd *cmd = qc->scsicmd;
2574 	unsigned int err_mask = qc->err_mask;
2575 
2576 	/* handle completion from new EH */
2577 	if (unlikely(qc->ap->ops->error_handler &&
2578 		     (err_mask || qc->flags & ATA_QCFLAG_SENSE_VALID))) {
2579 
2580 		if (!(qc->flags & ATA_QCFLAG_SENSE_VALID)) {
2581 			/* FIXME: not quite right; we don't want the
2582 			 * translation of taskfile registers into a
2583 			 * sense descriptors, since that's only
2584 			 * correct for ATA, not ATAPI
2585 			 */
2586 			ata_gen_passthru_sense(qc);
2587 		}
2588 
2589 		/* SCSI EH automatically locks door if sdev->locked is
2590 		 * set.  Sometimes door lock request continues to
2591 		 * fail, for example, when no media is present.  This
2592 		 * creates a loop - SCSI EH issues door lock which
2593 		 * fails and gets invoked again to acquire sense data
2594 		 * for the failed command.
2595 		 *
2596 		 * If door lock fails, always clear sdev->locked to
2597 		 * avoid this infinite loop.
2598 		 *
2599 		 * This may happen before SCSI scan is complete.  Make
2600 		 * sure qc->dev->sdev isn't NULL before dereferencing.
2601 		 */
2602 		if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL && qc->dev->sdev)
2603 			qc->dev->sdev->locked = 0;
2604 
2605 		qc->scsicmd->result = SAM_STAT_CHECK_CONDITION;
2606 		ata_qc_done(qc);
2607 		return;
2608 	}
2609 
2610 	/* successful completion or old EH failure path */
2611 	if (unlikely(err_mask & AC_ERR_DEV)) {
2612 		cmd->result = SAM_STAT_CHECK_CONDITION;
2613 		atapi_request_sense(qc);
2614 		return;
2615 	} else if (unlikely(err_mask)) {
2616 		/* FIXME: not quite right; we don't want the
2617 		 * translation of taskfile registers into
2618 		 * a sense descriptors, since that's only
2619 		 * correct for ATA, not ATAPI
2620 		 */
2621 		ata_gen_passthru_sense(qc);
2622 	} else {
2623 		if (cmd->cmnd[0] == INQUIRY && (cmd->cmnd[1] & 0x03) == 0)
2624 			atapi_fixup_inquiry(cmd);
2625 		cmd->result = SAM_STAT_GOOD;
2626 	}
2627 
2628 	ata_qc_done(qc);
2629 }
2630 /**
2631  *	atapi_xlat - Initialize PACKET taskfile
2632  *	@qc: command structure to be initialized
2633  *
2634  *	LOCKING:
2635  *	spin_lock_irqsave(host lock)
2636  *
2637  *	RETURNS:
2638  *	Zero on success, non-zero on failure.
2639  */
2640 static unsigned int atapi_xlat(struct ata_queued_cmd *qc)
2641 {
2642 	struct scsi_cmnd *scmd = qc->scsicmd;
2643 	struct ata_device *dev = qc->dev;
2644 	int nodata = (scmd->sc_data_direction == DMA_NONE);
2645 	int using_pio = !nodata && (dev->flags & ATA_DFLAG_PIO);
2646 	unsigned int nbytes;
2647 
2648 	memset(qc->cdb, 0, dev->cdb_len);
2649 	memcpy(qc->cdb, scmd->cmnd, scmd->cmd_len);
2650 
2651 	qc->complete_fn = atapi_qc_complete;
2652 
2653 	qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2654 	if (scmd->sc_data_direction == DMA_TO_DEVICE) {
2655 		qc->tf.flags |= ATA_TFLAG_WRITE;
2656 	}
2657 
2658 	qc->tf.command = ATA_CMD_PACKET;
2659 	ata_qc_set_pc_nbytes(qc);
2660 
2661 	/* check whether ATAPI DMA is safe */
2662 	if (!nodata && !using_pio && atapi_check_dma(qc))
2663 		using_pio = 1;
2664 
2665 	/* Some controller variants snoop this value for Packet
2666 	 * transfers to do state machine and FIFO management.  Thus we
2667 	 * want to set it properly, and for DMA where it is
2668 	 * effectively meaningless.
2669 	 */
2670 	nbytes = min(ata_qc_raw_nbytes(qc), (unsigned int)63 * 1024);
2671 
2672 	/* Most ATAPI devices which honor transfer chunk size don't
2673 	 * behave according to the spec when odd chunk size which
2674 	 * matches the transfer length is specified.  If the number of
2675 	 * bytes to transfer is 2n+1.  According to the spec, what
2676 	 * should happen is to indicate that 2n+1 is going to be
2677 	 * transferred and transfer 2n+2 bytes where the last byte is
2678 	 * padding.
2679 	 *
2680 	 * In practice, this doesn't happen.  ATAPI devices first
2681 	 * indicate and transfer 2n bytes and then indicate and
2682 	 * transfer 2 bytes where the last byte is padding.
2683 	 *
2684 	 * This inconsistency confuses several controllers which
2685 	 * perform PIO using DMA such as Intel AHCIs and sil3124/32.
2686 	 * These controllers use actual number of transferred bytes to
2687 	 * update DMA pointer and transfer of 4n+2 bytes make those
2688 	 * controller push DMA pointer by 4n+4 bytes because SATA data
2689 	 * FISes are aligned to 4 bytes.  This causes data corruption
2690 	 * and buffer overrun.
2691 	 *
2692 	 * Always setting nbytes to even number solves this problem
2693 	 * because then ATAPI devices don't have to split data at 2n
2694 	 * boundaries.
2695 	 */
2696 	if (nbytes & 0x1)
2697 		nbytes++;
2698 
2699 	qc->tf.lbam = (nbytes & 0xFF);
2700 	qc->tf.lbah = (nbytes >> 8);
2701 
2702 	if (nodata)
2703 		qc->tf.protocol = ATAPI_PROT_NODATA;
2704 	else if (using_pio)
2705 		qc->tf.protocol = ATAPI_PROT_PIO;
2706 	else {
2707 		/* DMA data xfer */
2708 		qc->tf.protocol = ATAPI_PROT_DMA;
2709 		qc->tf.feature |= ATAPI_PKT_DMA;
2710 
2711 		if ((dev->flags & ATA_DFLAG_DMADIR) &&
2712 		    (scmd->sc_data_direction != DMA_TO_DEVICE))
2713 			/* some SATA bridges need us to indicate data xfer direction */
2714 			qc->tf.feature |= ATAPI_DMADIR;
2715 	}
2716 
2717 
2718 	/* FIXME: We need to translate 0x05 READ_BLOCK_LIMITS to a MODE_SENSE
2719 	   as ATAPI tape drives don't get this right otherwise */
2720 	return 0;
2721 }
2722 
2723 static struct ata_device *ata_find_dev(struct ata_port *ap, int devno)
2724 {
2725 	if (!sata_pmp_attached(ap)) {
2726 		if (likely(devno >= 0 &&
2727 			   devno < ata_link_max_devices(&ap->link)))
2728 			return &ap->link.device[devno];
2729 	} else {
2730 		if (likely(devno >= 0 &&
2731 			   devno < ap->nr_pmp_links))
2732 			return &ap->pmp_link[devno].device[0];
2733 	}
2734 
2735 	return NULL;
2736 }
2737 
2738 static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
2739 					      const struct scsi_device *scsidev)
2740 {
2741 	int devno;
2742 
2743 	/* skip commands not addressed to targets we simulate */
2744 	if (!sata_pmp_attached(ap)) {
2745 		if (unlikely(scsidev->channel || scsidev->lun))
2746 			return NULL;
2747 		devno = scsidev->id;
2748 	} else {
2749 		if (unlikely(scsidev->id || scsidev->lun))
2750 			return NULL;
2751 		devno = scsidev->channel;
2752 	}
2753 
2754 	return ata_find_dev(ap, devno);
2755 }
2756 
2757 /**
2758  *	ata_scsi_find_dev - lookup ata_device from scsi_cmnd
2759  *	@ap: ATA port to which the device is attached
2760  *	@scsidev: SCSI device from which we derive the ATA device
2761  *
2762  *	Given various information provided in struct scsi_cmnd,
2763  *	map that onto an ATA bus, and using that mapping
2764  *	determine which ata_device is associated with the
2765  *	SCSI command to be sent.
2766  *
2767  *	LOCKING:
2768  *	spin_lock_irqsave(host lock)
2769  *
2770  *	RETURNS:
2771  *	Associated ATA device, or %NULL if not found.
2772  */
2773 struct ata_device *
2774 ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
2775 {
2776 	struct ata_device *dev = __ata_scsi_find_dev(ap, scsidev);
2777 
2778 	if (unlikely(!dev || !ata_dev_enabled(dev)))
2779 		return NULL;
2780 
2781 	return dev;
2782 }
2783 
2784 /*
2785  *	ata_scsi_map_proto - Map pass-thru protocol value to taskfile value.
2786  *	@byte1: Byte 1 from pass-thru CDB.
2787  *
2788  *	RETURNS:
2789  *	ATA_PROT_UNKNOWN if mapping failed/unimplemented, protocol otherwise.
2790  */
2791 static u8
2792 ata_scsi_map_proto(u8 byte1)
2793 {
2794 	switch((byte1 & 0x1e) >> 1) {
2795 	case 3:		/* Non-data */
2796 		return ATA_PROT_NODATA;
2797 
2798 	case 6:		/* DMA */
2799 	case 10:	/* UDMA Data-in */
2800 	case 11:	/* UDMA Data-Out */
2801 		return ATA_PROT_DMA;
2802 
2803 	case 4:		/* PIO Data-in */
2804 	case 5:		/* PIO Data-out */
2805 		return ATA_PROT_PIO;
2806 
2807 	case 12:	/* FPDMA */
2808 		return ATA_PROT_NCQ;
2809 
2810 	case 0:		/* Hard Reset */
2811 	case 1:		/* SRST */
2812 	case 8:		/* Device Diagnostic */
2813 	case 9:		/* Device Reset */
2814 	case 7:		/* DMA Queued */
2815 	case 15:	/* Return Response Info */
2816 	default:	/* Reserved */
2817 		break;
2818 	}
2819 
2820 	return ATA_PROT_UNKNOWN;
2821 }
2822 
2823 /**
2824  *	ata_scsi_pass_thru - convert ATA pass-thru CDB to taskfile
2825  *	@qc: command structure to be initialized
2826  *
2827  *	Handles either 12, 16, or 32-byte versions of the CDB.
2828  *
2829  *	RETURNS:
2830  *	Zero on success, non-zero on failure.
2831  */
2832 static unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
2833 {
2834 	struct ata_taskfile *tf = &(qc->tf);
2835 	struct scsi_cmnd *scmd = qc->scsicmd;
2836 	struct ata_device *dev = qc->dev;
2837 	const u8 *cdb = scmd->cmnd;
2838 	u16 fp;
2839 	u16 cdb_offset = 0;
2840 
2841 	/* 7Fh variable length cmd means a ata pass-thru(32) */
2842 	if (cdb[0] == VARIABLE_LENGTH_CMD)
2843 		cdb_offset = 9;
2844 
2845 	tf->protocol = ata_scsi_map_proto(cdb[1 + cdb_offset]);
2846 	if (tf->protocol == ATA_PROT_UNKNOWN) {
2847 		fp = 1;
2848 		goto invalid_fld;
2849 	}
2850 
2851 	if ((cdb[2 + cdb_offset] & 0x3) == 0) {
2852 		/*
2853 		 * When T_LENGTH is zero (No data is transferred), dir should
2854 		 * be DMA_NONE.
2855 		 */
2856 		if (scmd->sc_data_direction != DMA_NONE) {
2857 			fp = 2 + cdb_offset;
2858 			goto invalid_fld;
2859 		}
2860 
2861 		if (ata_is_ncq(tf->protocol))
2862 			tf->protocol = ATA_PROT_NCQ_NODATA;
2863 	}
2864 
2865 	/* enable LBA */
2866 	tf->flags |= ATA_TFLAG_LBA;
2867 
2868 	/*
2869 	 * 12 and 16 byte CDBs use different offsets to
2870 	 * provide the various register values.
2871 	 */
2872 	switch (cdb[0]) {
2873 	case ATA_16:
2874 		/*
2875 		 * 16-byte CDB - may contain extended commands.
2876 		 *
2877 		 * If that is the case, copy the upper byte register values.
2878 		 */
2879 		if (cdb[1] & 0x01) {
2880 			tf->hob_feature = cdb[3];
2881 			tf->hob_nsect = cdb[5];
2882 			tf->hob_lbal = cdb[7];
2883 			tf->hob_lbam = cdb[9];
2884 			tf->hob_lbah = cdb[11];
2885 			tf->flags |= ATA_TFLAG_LBA48;
2886 		} else
2887 			tf->flags &= ~ATA_TFLAG_LBA48;
2888 
2889 		/*
2890 		 * Always copy low byte, device and command registers.
2891 		 */
2892 		tf->feature = cdb[4];
2893 		tf->nsect = cdb[6];
2894 		tf->lbal = cdb[8];
2895 		tf->lbam = cdb[10];
2896 		tf->lbah = cdb[12];
2897 		tf->device = cdb[13];
2898 		tf->command = cdb[14];
2899 		break;
2900 	case ATA_12:
2901 		/*
2902 		 * 12-byte CDB - incapable of extended commands.
2903 		 */
2904 		tf->flags &= ~ATA_TFLAG_LBA48;
2905 
2906 		tf->feature = cdb[3];
2907 		tf->nsect = cdb[4];
2908 		tf->lbal = cdb[5];
2909 		tf->lbam = cdb[6];
2910 		tf->lbah = cdb[7];
2911 		tf->device = cdb[8];
2912 		tf->command = cdb[9];
2913 		break;
2914 	default:
2915 		/*
2916 		 * 32-byte CDB - may contain extended command fields.
2917 		 *
2918 		 * If that is the case, copy the upper byte register values.
2919 		 */
2920 		if (cdb[10] & 0x01) {
2921 			tf->hob_feature = cdb[20];
2922 			tf->hob_nsect = cdb[22];
2923 			tf->hob_lbal = cdb[16];
2924 			tf->hob_lbam = cdb[15];
2925 			tf->hob_lbah = cdb[14];
2926 			tf->flags |= ATA_TFLAG_LBA48;
2927 		} else
2928 			tf->flags &= ~ATA_TFLAG_LBA48;
2929 
2930 		tf->feature = cdb[21];
2931 		tf->nsect = cdb[23];
2932 		tf->lbal = cdb[19];
2933 		tf->lbam = cdb[18];
2934 		tf->lbah = cdb[17];
2935 		tf->device = cdb[24];
2936 		tf->command = cdb[25];
2937 		tf->auxiliary = get_unaligned_be32(&cdb[28]);
2938 		break;
2939 	}
2940 
2941 	/* For NCQ commands copy the tag value */
2942 	if (ata_is_ncq(tf->protocol))
2943 		tf->nsect = qc->hw_tag << 3;
2944 
2945 	/* enforce correct master/slave bit */
2946 	tf->device = dev->devno ?
2947 		tf->device | ATA_DEV1 : tf->device & ~ATA_DEV1;
2948 
2949 	switch (tf->command) {
2950 	/* READ/WRITE LONG use a non-standard sect_size */
2951 	case ATA_CMD_READ_LONG:
2952 	case ATA_CMD_READ_LONG_ONCE:
2953 	case ATA_CMD_WRITE_LONG:
2954 	case ATA_CMD_WRITE_LONG_ONCE:
2955 		if (tf->protocol != ATA_PROT_PIO || tf->nsect != 1) {
2956 			fp = 1;
2957 			goto invalid_fld;
2958 		}
2959 		qc->sect_size = scsi_bufflen(scmd);
2960 		break;
2961 
2962 	/* commands using reported Logical Block size (e.g. 512 or 4K) */
2963 	case ATA_CMD_CFA_WRITE_NE:
2964 	case ATA_CMD_CFA_TRANS_SECT:
2965 	case ATA_CMD_CFA_WRITE_MULT_NE:
2966 	/* XXX: case ATA_CMD_CFA_WRITE_SECTORS_WITHOUT_ERASE: */
2967 	case ATA_CMD_READ:
2968 	case ATA_CMD_READ_EXT:
2969 	case ATA_CMD_READ_QUEUED:
2970 	/* XXX: case ATA_CMD_READ_QUEUED_EXT: */
2971 	case ATA_CMD_FPDMA_READ:
2972 	case ATA_CMD_READ_MULTI:
2973 	case ATA_CMD_READ_MULTI_EXT:
2974 	case ATA_CMD_PIO_READ:
2975 	case ATA_CMD_PIO_READ_EXT:
2976 	case ATA_CMD_READ_STREAM_DMA_EXT:
2977 	case ATA_CMD_READ_STREAM_EXT:
2978 	case ATA_CMD_VERIFY:
2979 	case ATA_CMD_VERIFY_EXT:
2980 	case ATA_CMD_WRITE:
2981 	case ATA_CMD_WRITE_EXT:
2982 	case ATA_CMD_WRITE_FUA_EXT:
2983 	case ATA_CMD_WRITE_QUEUED:
2984 	case ATA_CMD_WRITE_QUEUED_FUA_EXT:
2985 	case ATA_CMD_FPDMA_WRITE:
2986 	case ATA_CMD_WRITE_MULTI:
2987 	case ATA_CMD_WRITE_MULTI_EXT:
2988 	case ATA_CMD_WRITE_MULTI_FUA_EXT:
2989 	case ATA_CMD_PIO_WRITE:
2990 	case ATA_CMD_PIO_WRITE_EXT:
2991 	case ATA_CMD_WRITE_STREAM_DMA_EXT:
2992 	case ATA_CMD_WRITE_STREAM_EXT:
2993 		qc->sect_size = scmd->device->sector_size;
2994 		break;
2995 
2996 	/* Everything else uses 512 byte "sectors" */
2997 	default:
2998 		qc->sect_size = ATA_SECT_SIZE;
2999 	}
3000 
3001 	/*
3002 	 * Set flags so that all registers will be written, pass on
3003 	 * write indication (used for PIO/DMA setup), result TF is
3004 	 * copied back and we don't whine too much about its failure.
3005 	 */
3006 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3007 	if (scmd->sc_data_direction == DMA_TO_DEVICE)
3008 		tf->flags |= ATA_TFLAG_WRITE;
3009 
3010 	qc->flags |= ATA_QCFLAG_RESULT_TF | ATA_QCFLAG_QUIET;
3011 
3012 	/*
3013 	 * Set transfer length.
3014 	 *
3015 	 * TODO: find out if we need to do more here to
3016 	 *       cover scatter/gather case.
3017 	 */
3018 	ata_qc_set_pc_nbytes(qc);
3019 
3020 	/* We may not issue DMA commands if no DMA mode is set */
3021 	if (tf->protocol == ATA_PROT_DMA && !ata_dma_enabled(dev)) {
3022 		fp = 1;
3023 		goto invalid_fld;
3024 	}
3025 
3026 	/* We may not issue NCQ commands to devices not supporting NCQ */
3027 	if (ata_is_ncq(tf->protocol) && !ata_ncq_enabled(dev)) {
3028 		fp = 1;
3029 		goto invalid_fld;
3030 	}
3031 
3032 	/* sanity check for pio multi commands */
3033 	if ((cdb[1] & 0xe0) && !is_multi_taskfile(tf)) {
3034 		fp = 1;
3035 		goto invalid_fld;
3036 	}
3037 
3038 	if (is_multi_taskfile(tf)) {
3039 		unsigned int multi_count = 1 << (cdb[1] >> 5);
3040 
3041 		/* compare the passed through multi_count
3042 		 * with the cached multi_count of libata
3043 		 */
3044 		if (multi_count != dev->multi_count)
3045 			ata_dev_warn(dev, "invalid multi_count %u ignored\n",
3046 				     multi_count);
3047 	}
3048 
3049 	/*
3050 	 * Filter SET_FEATURES - XFER MODE command -- otherwise,
3051 	 * SET_FEATURES - XFER MODE must be preceded/succeeded
3052 	 * by an update to hardware-specific registers for each
3053 	 * controller (i.e. the reason for ->set_piomode(),
3054 	 * ->set_dmamode(), and ->post_set_mode() hooks).
3055 	 */
3056 	if (tf->command == ATA_CMD_SET_FEATURES &&
3057 	    tf->feature == SETFEATURES_XFER) {
3058 		fp = (cdb[0] == ATA_16) ? 4 : 3;
3059 		goto invalid_fld;
3060 	}
3061 
3062 	/*
3063 	 * Filter TPM commands by default. These provide an
3064 	 * essentially uncontrolled encrypted "back door" between
3065 	 * applications and the disk. Set libata.allow_tpm=1 if you
3066 	 * have a real reason for wanting to use them. This ensures
3067 	 * that installed software cannot easily mess stuff up without
3068 	 * user intent. DVR type users will probably ship with this enabled
3069 	 * for movie content management.
3070 	 *
3071 	 * Note that for ATA8 we can issue a DCS change and DCS freeze lock
3072 	 * for this and should do in future but that it is not sufficient as
3073 	 * DCS is an optional feature set. Thus we also do the software filter
3074 	 * so that we comply with the TC consortium stated goal that the user
3075 	 * can turn off TC features of their system.
3076 	 */
3077 	if (tf->command >= 0x5C && tf->command <= 0x5F && !libata_allow_tpm) {
3078 		fp = (cdb[0] == ATA_16) ? 14 : 9;
3079 		goto invalid_fld;
3080 	}
3081 
3082 	return 0;
3083 
3084  invalid_fld:
3085 	ata_scsi_set_invalid_field(dev, scmd, fp, 0xff);
3086 	return 1;
3087 }
3088 
3089 /**
3090  * ata_format_dsm_trim_descr() - SATL Write Same to DSM Trim
3091  * @cmd: SCSI command being translated
3092  * @trmax: Maximum number of entries that will fit in sector_size bytes.
3093  * @sector: Starting sector
3094  * @count: Total Range of request in logical sectors
3095  *
3096  * Rewrite the WRITE SAME descriptor to be a DSM TRIM little-endian formatted
3097  * descriptor.
3098  *
3099  * Upto 64 entries of the format:
3100  *   63:48 Range Length
3101  *   47:0  LBA
3102  *
3103  *  Range Length of 0 is ignored.
3104  *  LBA's should be sorted order and not overlap.
3105  *
3106  * NOTE: this is the same format as ADD LBA(S) TO NV CACHE PINNED SET
3107  *
3108  * Return: Number of bytes copied into sglist.
3109  */
3110 static size_t ata_format_dsm_trim_descr(struct scsi_cmnd *cmd, u32 trmax,
3111 					u64 sector, u32 count)
3112 {
3113 	struct scsi_device *sdp = cmd->device;
3114 	size_t len = sdp->sector_size;
3115 	size_t r;
3116 	__le64 *buf;
3117 	u32 i = 0;
3118 	unsigned long flags;
3119 
3120 	WARN_ON(len > ATA_SCSI_RBUF_SIZE);
3121 
3122 	if (len > ATA_SCSI_RBUF_SIZE)
3123 		len = ATA_SCSI_RBUF_SIZE;
3124 
3125 	spin_lock_irqsave(&ata_scsi_rbuf_lock, flags);
3126 	buf = ((void *)ata_scsi_rbuf);
3127 	memset(buf, 0, len);
3128 	while (i < trmax) {
3129 		u64 entry = sector |
3130 			((u64)(count > 0xffff ? 0xffff : count) << 48);
3131 		buf[i++] = __cpu_to_le64(entry);
3132 		if (count <= 0xffff)
3133 			break;
3134 		count -= 0xffff;
3135 		sector += 0xffff;
3136 	}
3137 	r = sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, len);
3138 	spin_unlock_irqrestore(&ata_scsi_rbuf_lock, flags);
3139 
3140 	return r;
3141 }
3142 
3143 /**
3144  * ata_scsi_write_same_xlat() - SATL Write Same to ATA SCT Write Same
3145  * @qc: Command to be translated
3146  *
3147  * Translate a SCSI WRITE SAME command to be either a DSM TRIM command or
3148  * an SCT Write Same command.
3149  * Based on WRITE SAME has the UNMAP flag:
3150  *
3151  *   - When set translate to DSM TRIM
3152  *   - When clear translate to SCT Write Same
3153  */
3154 static unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
3155 {
3156 	struct ata_taskfile *tf = &qc->tf;
3157 	struct scsi_cmnd *scmd = qc->scsicmd;
3158 	struct scsi_device *sdp = scmd->device;
3159 	size_t len = sdp->sector_size;
3160 	struct ata_device *dev = qc->dev;
3161 	const u8 *cdb = scmd->cmnd;
3162 	u64 block;
3163 	u32 n_block;
3164 	const u32 trmax = len >> 3;
3165 	u32 size;
3166 	u16 fp;
3167 	u8 bp = 0xff;
3168 	u8 unmap = cdb[1] & 0x8;
3169 
3170 	/* we may not issue DMA commands if no DMA mode is set */
3171 	if (unlikely(!ata_dma_enabled(dev)))
3172 		goto invalid_opcode;
3173 
3174 	/*
3175 	 * We only allow sending this command through the block layer,
3176 	 * as it modifies the DATA OUT buffer, which would corrupt user
3177 	 * memory for SG_IO commands.
3178 	 */
3179 	if (unlikely(blk_rq_is_passthrough(scsi_cmd_to_rq(scmd))))
3180 		goto invalid_opcode;
3181 
3182 	if (unlikely(scmd->cmd_len < 16)) {
3183 		fp = 15;
3184 		goto invalid_fld;
3185 	}
3186 	scsi_16_lba_len(cdb, &block, &n_block);
3187 
3188 	if (!unmap ||
3189 	    (dev->horkage & ATA_HORKAGE_NOTRIM) ||
3190 	    !ata_id_has_trim(dev->id)) {
3191 		fp = 1;
3192 		bp = 3;
3193 		goto invalid_fld;
3194 	}
3195 	/* If the request is too large the cmd is invalid */
3196 	if (n_block > 0xffff * trmax) {
3197 		fp = 2;
3198 		goto invalid_fld;
3199 	}
3200 
3201 	/*
3202 	 * WRITE SAME always has a sector sized buffer as payload, this
3203 	 * should never be a multiple entry S/G list.
3204 	 */
3205 	if (!scsi_sg_count(scmd))
3206 		goto invalid_param_len;
3207 
3208 	/*
3209 	 * size must match sector size in bytes
3210 	 * For DATA SET MANAGEMENT TRIM in ACS-2 nsect (aka count)
3211 	 * is defined as number of 512 byte blocks to be transferred.
3212 	 */
3213 
3214 	size = ata_format_dsm_trim_descr(scmd, trmax, block, n_block);
3215 	if (size != len)
3216 		goto invalid_param_len;
3217 
3218 	if (ata_ncq_enabled(dev) && ata_fpdma_dsm_supported(dev)) {
3219 		/* Newer devices support queued TRIM commands */
3220 		tf->protocol = ATA_PROT_NCQ;
3221 		tf->command = ATA_CMD_FPDMA_SEND;
3222 		tf->hob_nsect = ATA_SUBCMD_FPDMA_SEND_DSM & 0x1f;
3223 		tf->nsect = qc->hw_tag << 3;
3224 		tf->hob_feature = (size / 512) >> 8;
3225 		tf->feature = size / 512;
3226 
3227 		tf->auxiliary = 1;
3228 	} else {
3229 		tf->protocol = ATA_PROT_DMA;
3230 		tf->hob_feature = 0;
3231 		tf->feature = ATA_DSM_TRIM;
3232 		tf->hob_nsect = (size / 512) >> 8;
3233 		tf->nsect = size / 512;
3234 		tf->command = ATA_CMD_DSM;
3235 	}
3236 
3237 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48 |
3238 		     ATA_TFLAG_WRITE;
3239 
3240 	ata_qc_set_pc_nbytes(qc);
3241 
3242 	return 0;
3243 
3244 invalid_fld:
3245 	ata_scsi_set_invalid_field(dev, scmd, fp, bp);
3246 	return 1;
3247 invalid_param_len:
3248 	/* "Parameter list length error" */
3249 	ata_scsi_set_sense(dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3250 	return 1;
3251 invalid_opcode:
3252 	/* "Invalid command operation code" */
3253 	ata_scsi_set_sense(dev, scmd, ILLEGAL_REQUEST, 0x20, 0x0);
3254 	return 1;
3255 }
3256 
3257 /**
3258  *	ata_scsiop_maint_in - Simulate a subset of MAINTENANCE_IN
3259  *	@args: device MAINTENANCE_IN data / SCSI command of interest.
3260  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
3261  *
3262  *	Yields a subset to satisfy scsi_report_opcode()
3263  *
3264  *	LOCKING:
3265  *	spin_lock_irqsave(host lock)
3266  */
3267 static unsigned int ata_scsiop_maint_in(struct ata_scsi_args *args, u8 *rbuf)
3268 {
3269 	struct ata_device *dev = args->dev;
3270 	u8 *cdb = args->cmd->cmnd;
3271 	u8 supported = 0;
3272 	unsigned int err = 0;
3273 
3274 	if (cdb[2] != 1) {
3275 		ata_dev_warn(dev, "invalid command format %d\n", cdb[2]);
3276 		err = 2;
3277 		goto out;
3278 	}
3279 	switch (cdb[3]) {
3280 	case INQUIRY:
3281 	case MODE_SENSE:
3282 	case MODE_SENSE_10:
3283 	case READ_CAPACITY:
3284 	case SERVICE_ACTION_IN_16:
3285 	case REPORT_LUNS:
3286 	case REQUEST_SENSE:
3287 	case SYNCHRONIZE_CACHE:
3288 	case SYNCHRONIZE_CACHE_16:
3289 	case REZERO_UNIT:
3290 	case SEEK_6:
3291 	case SEEK_10:
3292 	case TEST_UNIT_READY:
3293 	case SEND_DIAGNOSTIC:
3294 	case MAINTENANCE_IN:
3295 	case READ_6:
3296 	case READ_10:
3297 	case READ_16:
3298 	case WRITE_6:
3299 	case WRITE_10:
3300 	case WRITE_16:
3301 	case ATA_12:
3302 	case ATA_16:
3303 	case VERIFY:
3304 	case VERIFY_16:
3305 	case MODE_SELECT:
3306 	case MODE_SELECT_10:
3307 	case START_STOP:
3308 		supported = 3;
3309 		break;
3310 	case ZBC_IN:
3311 	case ZBC_OUT:
3312 		if (ata_id_zoned_cap(dev->id) ||
3313 		    dev->class == ATA_DEV_ZAC)
3314 			supported = 3;
3315 		break;
3316 	case SECURITY_PROTOCOL_IN:
3317 	case SECURITY_PROTOCOL_OUT:
3318 		if (dev->flags & ATA_DFLAG_TRUSTED)
3319 			supported = 3;
3320 		break;
3321 	default:
3322 		break;
3323 	}
3324 out:
3325 	rbuf[1] = supported; /* supported */
3326 	return err;
3327 }
3328 
3329 /**
3330  *	ata_scsi_report_zones_complete - convert ATA output
3331  *	@qc: command structure returning the data
3332  *
3333  *	Convert T-13 little-endian field representation into
3334  *	T-10 big-endian field representation.
3335  *	What a mess.
3336  */
3337 static void ata_scsi_report_zones_complete(struct ata_queued_cmd *qc)
3338 {
3339 	struct scsi_cmnd *scmd = qc->scsicmd;
3340 	struct sg_mapping_iter miter;
3341 	unsigned long flags;
3342 	unsigned int bytes = 0;
3343 
3344 	sg_miter_start(&miter, scsi_sglist(scmd), scsi_sg_count(scmd),
3345 		       SG_MITER_TO_SG | SG_MITER_ATOMIC);
3346 
3347 	local_irq_save(flags);
3348 	while (sg_miter_next(&miter)) {
3349 		unsigned int offset = 0;
3350 
3351 		if (bytes == 0) {
3352 			char *hdr;
3353 			u32 list_length;
3354 			u64 max_lba, opt_lba;
3355 			u16 same;
3356 
3357 			/* Swizzle header */
3358 			hdr = miter.addr;
3359 			list_length = get_unaligned_le32(&hdr[0]);
3360 			same = get_unaligned_le16(&hdr[4]);
3361 			max_lba = get_unaligned_le64(&hdr[8]);
3362 			opt_lba = get_unaligned_le64(&hdr[16]);
3363 			put_unaligned_be32(list_length, &hdr[0]);
3364 			hdr[4] = same & 0xf;
3365 			put_unaligned_be64(max_lba, &hdr[8]);
3366 			put_unaligned_be64(opt_lba, &hdr[16]);
3367 			offset += 64;
3368 			bytes += 64;
3369 		}
3370 		while (offset < miter.length) {
3371 			char *rec;
3372 			u8 cond, type, non_seq, reset;
3373 			u64 size, start, wp;
3374 
3375 			/* Swizzle zone descriptor */
3376 			rec = miter.addr + offset;
3377 			type = rec[0] & 0xf;
3378 			cond = (rec[1] >> 4) & 0xf;
3379 			non_seq = (rec[1] & 2);
3380 			reset = (rec[1] & 1);
3381 			size = get_unaligned_le64(&rec[8]);
3382 			start = get_unaligned_le64(&rec[16]);
3383 			wp = get_unaligned_le64(&rec[24]);
3384 			rec[0] = type;
3385 			rec[1] = (cond << 4) | non_seq | reset;
3386 			put_unaligned_be64(size, &rec[8]);
3387 			put_unaligned_be64(start, &rec[16]);
3388 			put_unaligned_be64(wp, &rec[24]);
3389 			WARN_ON(offset + 64 > miter.length);
3390 			offset += 64;
3391 			bytes += 64;
3392 		}
3393 	}
3394 	sg_miter_stop(&miter);
3395 	local_irq_restore(flags);
3396 
3397 	ata_scsi_qc_complete(qc);
3398 }
3399 
3400 static unsigned int ata_scsi_zbc_in_xlat(struct ata_queued_cmd *qc)
3401 {
3402 	struct ata_taskfile *tf = &qc->tf;
3403 	struct scsi_cmnd *scmd = qc->scsicmd;
3404 	const u8 *cdb = scmd->cmnd;
3405 	u16 sect, fp = (u16)-1;
3406 	u8 sa, options, bp = 0xff;
3407 	u64 block;
3408 	u32 n_block;
3409 
3410 	if (unlikely(scmd->cmd_len < 16)) {
3411 		ata_dev_warn(qc->dev, "invalid cdb length %d\n",
3412 			     scmd->cmd_len);
3413 		fp = 15;
3414 		goto invalid_fld;
3415 	}
3416 	scsi_16_lba_len(cdb, &block, &n_block);
3417 	if (n_block != scsi_bufflen(scmd)) {
3418 		ata_dev_warn(qc->dev, "non-matching transfer count (%d/%d)\n",
3419 			     n_block, scsi_bufflen(scmd));
3420 		goto invalid_param_len;
3421 	}
3422 	sa = cdb[1] & 0x1f;
3423 	if (sa != ZI_REPORT_ZONES) {
3424 		ata_dev_warn(qc->dev, "invalid service action %d\n", sa);
3425 		fp = 1;
3426 		goto invalid_fld;
3427 	}
3428 	/*
3429 	 * ZAC allows only for transfers in 512 byte blocks,
3430 	 * and uses a 16 bit value for the transfer count.
3431 	 */
3432 	if ((n_block / 512) > 0xffff || n_block < 512 || (n_block % 512)) {
3433 		ata_dev_warn(qc->dev, "invalid transfer count %d\n", n_block);
3434 		goto invalid_param_len;
3435 	}
3436 	sect = n_block / 512;
3437 	options = cdb[14] & 0xbf;
3438 
3439 	if (ata_ncq_enabled(qc->dev) &&
3440 	    ata_fpdma_zac_mgmt_in_supported(qc->dev)) {
3441 		tf->protocol = ATA_PROT_NCQ;
3442 		tf->command = ATA_CMD_FPDMA_RECV;
3443 		tf->hob_nsect = ATA_SUBCMD_FPDMA_RECV_ZAC_MGMT_IN & 0x1f;
3444 		tf->nsect = qc->hw_tag << 3;
3445 		tf->feature = sect & 0xff;
3446 		tf->hob_feature = (sect >> 8) & 0xff;
3447 		tf->auxiliary = ATA_SUBCMD_ZAC_MGMT_IN_REPORT_ZONES | (options << 8);
3448 	} else {
3449 		tf->command = ATA_CMD_ZAC_MGMT_IN;
3450 		tf->feature = ATA_SUBCMD_ZAC_MGMT_IN_REPORT_ZONES;
3451 		tf->protocol = ATA_PROT_DMA;
3452 		tf->hob_feature = options;
3453 		tf->hob_nsect = (sect >> 8) & 0xff;
3454 		tf->nsect = sect & 0xff;
3455 	}
3456 	tf->device = ATA_LBA;
3457 	tf->lbah = (block >> 16) & 0xff;
3458 	tf->lbam = (block >> 8) & 0xff;
3459 	tf->lbal = block & 0xff;
3460 	tf->hob_lbah = (block >> 40) & 0xff;
3461 	tf->hob_lbam = (block >> 32) & 0xff;
3462 	tf->hob_lbal = (block >> 24) & 0xff;
3463 
3464 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48;
3465 	qc->flags |= ATA_QCFLAG_RESULT_TF;
3466 
3467 	ata_qc_set_pc_nbytes(qc);
3468 
3469 	qc->complete_fn = ata_scsi_report_zones_complete;
3470 
3471 	return 0;
3472 
3473 invalid_fld:
3474 	ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
3475 	return 1;
3476 
3477 invalid_param_len:
3478 	/* "Parameter list length error" */
3479 	ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3480 	return 1;
3481 }
3482 
3483 static unsigned int ata_scsi_zbc_out_xlat(struct ata_queued_cmd *qc)
3484 {
3485 	struct ata_taskfile *tf = &qc->tf;
3486 	struct scsi_cmnd *scmd = qc->scsicmd;
3487 	struct ata_device *dev = qc->dev;
3488 	const u8 *cdb = scmd->cmnd;
3489 	u8 all, sa;
3490 	u64 block;
3491 	u32 n_block;
3492 	u16 fp = (u16)-1;
3493 
3494 	if (unlikely(scmd->cmd_len < 16)) {
3495 		fp = 15;
3496 		goto invalid_fld;
3497 	}
3498 
3499 	sa = cdb[1] & 0x1f;
3500 	if ((sa != ZO_CLOSE_ZONE) && (sa != ZO_FINISH_ZONE) &&
3501 	    (sa != ZO_OPEN_ZONE) && (sa != ZO_RESET_WRITE_POINTER)) {
3502 		fp = 1;
3503 		goto invalid_fld;
3504 	}
3505 
3506 	scsi_16_lba_len(cdb, &block, &n_block);
3507 	if (n_block) {
3508 		/*
3509 		 * ZAC MANAGEMENT OUT doesn't define any length
3510 		 */
3511 		goto invalid_param_len;
3512 	}
3513 
3514 	all = cdb[14] & 0x1;
3515 	if (all) {
3516 		/*
3517 		 * Ignore the block address (zone ID) as defined by ZBC.
3518 		 */
3519 		block = 0;
3520 	} else if (block >= dev->n_sectors) {
3521 		/*
3522 		 * Block must be a valid zone ID (a zone start LBA).
3523 		 */
3524 		fp = 2;
3525 		goto invalid_fld;
3526 	}
3527 
3528 	if (ata_ncq_enabled(qc->dev) &&
3529 	    ata_fpdma_zac_mgmt_out_supported(qc->dev)) {
3530 		tf->protocol = ATA_PROT_NCQ_NODATA;
3531 		tf->command = ATA_CMD_NCQ_NON_DATA;
3532 		tf->feature = ATA_SUBCMD_NCQ_NON_DATA_ZAC_MGMT_OUT;
3533 		tf->nsect = qc->hw_tag << 3;
3534 		tf->auxiliary = sa | ((u16)all << 8);
3535 	} else {
3536 		tf->protocol = ATA_PROT_NODATA;
3537 		tf->command = ATA_CMD_ZAC_MGMT_OUT;
3538 		tf->feature = sa;
3539 		tf->hob_feature = all;
3540 	}
3541 	tf->lbah = (block >> 16) & 0xff;
3542 	tf->lbam = (block >> 8) & 0xff;
3543 	tf->lbal = block & 0xff;
3544 	tf->hob_lbah = (block >> 40) & 0xff;
3545 	tf->hob_lbam = (block >> 32) & 0xff;
3546 	tf->hob_lbal = (block >> 24) & 0xff;
3547 	tf->device = ATA_LBA;
3548 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48;
3549 
3550 	return 0;
3551 
3552  invalid_fld:
3553 	ata_scsi_set_invalid_field(qc->dev, scmd, fp, 0xff);
3554 	return 1;
3555 invalid_param_len:
3556 	/* "Parameter list length error" */
3557 	ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3558 	return 1;
3559 }
3560 
3561 /**
3562  *	ata_mselect_caching - Simulate MODE SELECT for caching info page
3563  *	@qc: Storage for translated ATA taskfile
3564  *	@buf: input buffer
3565  *	@len: number of valid bytes in the input buffer
3566  *	@fp: out parameter for the failed field on error
3567  *
3568  *	Prepare a taskfile to modify caching information for the device.
3569  *
3570  *	LOCKING:
3571  *	None.
3572  */
3573 static int ata_mselect_caching(struct ata_queued_cmd *qc,
3574 			       const u8 *buf, int len, u16 *fp)
3575 {
3576 	struct ata_taskfile *tf = &qc->tf;
3577 	struct ata_device *dev = qc->dev;
3578 	u8 mpage[CACHE_MPAGE_LEN];
3579 	u8 wce;
3580 	int i;
3581 
3582 	/*
3583 	 * The first two bytes of def_cache_mpage are a header, so offsets
3584 	 * in mpage are off by 2 compared to buf.  Same for len.
3585 	 */
3586 
3587 	if (len != CACHE_MPAGE_LEN - 2) {
3588 		*fp = min(len, CACHE_MPAGE_LEN - 2);
3589 		return -EINVAL;
3590 	}
3591 
3592 	wce = buf[0] & (1 << 2);
3593 
3594 	/*
3595 	 * Check that read-only bits are not modified.
3596 	 */
3597 	ata_msense_caching(dev->id, mpage, false);
3598 	for (i = 0; i < CACHE_MPAGE_LEN - 2; i++) {
3599 		if (i == 0)
3600 			continue;
3601 		if (mpage[i + 2] != buf[i]) {
3602 			*fp = i;
3603 			return -EINVAL;
3604 		}
3605 	}
3606 
3607 	tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
3608 	tf->protocol = ATA_PROT_NODATA;
3609 	tf->nsect = 0;
3610 	tf->command = ATA_CMD_SET_FEATURES;
3611 	tf->feature = wce ? SETFEATURES_WC_ON : SETFEATURES_WC_OFF;
3612 	return 0;
3613 }
3614 
3615 /**
3616  *	ata_mselect_control - Simulate MODE SELECT for control page
3617  *	@qc: Storage for translated ATA taskfile
3618  *	@buf: input buffer
3619  *	@len: number of valid bytes in the input buffer
3620  *	@fp: out parameter for the failed field on error
3621  *
3622  *	Prepare a taskfile to modify caching information for the device.
3623  *
3624  *	LOCKING:
3625  *	None.
3626  */
3627 static int ata_mselect_control(struct ata_queued_cmd *qc,
3628 			       const u8 *buf, int len, u16 *fp)
3629 {
3630 	struct ata_device *dev = qc->dev;
3631 	u8 mpage[CONTROL_MPAGE_LEN];
3632 	u8 d_sense;
3633 	int i;
3634 
3635 	/*
3636 	 * The first two bytes of def_control_mpage are a header, so offsets
3637 	 * in mpage are off by 2 compared to buf.  Same for len.
3638 	 */
3639 
3640 	if (len != CONTROL_MPAGE_LEN - 2) {
3641 		*fp = min(len, CONTROL_MPAGE_LEN - 2);
3642 		return -EINVAL;
3643 	}
3644 
3645 	d_sense = buf[0] & (1 << 2);
3646 
3647 	/*
3648 	 * Check that read-only bits are not modified.
3649 	 */
3650 	ata_msense_control(dev, mpage, false);
3651 	for (i = 0; i < CONTROL_MPAGE_LEN - 2; i++) {
3652 		if (i == 0)
3653 			continue;
3654 		if (mpage[2 + i] != buf[i]) {
3655 			*fp = i;
3656 			return -EINVAL;
3657 		}
3658 	}
3659 	if (d_sense & (1 << 2))
3660 		dev->flags |= ATA_DFLAG_D_SENSE;
3661 	else
3662 		dev->flags &= ~ATA_DFLAG_D_SENSE;
3663 	return 0;
3664 }
3665 
3666 /**
3667  *	ata_scsi_mode_select_xlat - Simulate MODE SELECT 6, 10 commands
3668  *	@qc: Storage for translated ATA taskfile
3669  *
3670  *	Converts a MODE SELECT command to an ATA SET FEATURES taskfile.
3671  *	Assume this is invoked for direct access devices (e.g. disks) only.
3672  *	There should be no block descriptor for other device types.
3673  *
3674  *	LOCKING:
3675  *	spin_lock_irqsave(host lock)
3676  */
3677 static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc)
3678 {
3679 	struct scsi_cmnd *scmd = qc->scsicmd;
3680 	const u8 *cdb = scmd->cmnd;
3681 	u8 pg, spg;
3682 	unsigned six_byte, pg_len, hdr_len, bd_len;
3683 	int len;
3684 	u16 fp = (u16)-1;
3685 	u8 bp = 0xff;
3686 	u8 buffer[64];
3687 	const u8 *p = buffer;
3688 
3689 	six_byte = (cdb[0] == MODE_SELECT);
3690 	if (six_byte) {
3691 		if (scmd->cmd_len < 5) {
3692 			fp = 4;
3693 			goto invalid_fld;
3694 		}
3695 
3696 		len = cdb[4];
3697 		hdr_len = 4;
3698 	} else {
3699 		if (scmd->cmd_len < 9) {
3700 			fp = 8;
3701 			goto invalid_fld;
3702 		}
3703 
3704 		len = get_unaligned_be16(&cdb[7]);
3705 		hdr_len = 8;
3706 	}
3707 
3708 	/* We only support PF=1, SP=0.  */
3709 	if ((cdb[1] & 0x11) != 0x10) {
3710 		fp = 1;
3711 		bp = (cdb[1] & 0x01) ? 1 : 5;
3712 		goto invalid_fld;
3713 	}
3714 
3715 	/* Test early for possible overrun.  */
3716 	if (!scsi_sg_count(scmd) || scsi_sglist(scmd)->length < len)
3717 		goto invalid_param_len;
3718 
3719 	/* Move past header and block descriptors.  */
3720 	if (len < hdr_len)
3721 		goto invalid_param_len;
3722 
3723 	if (!sg_copy_to_buffer(scsi_sglist(scmd), scsi_sg_count(scmd),
3724 			       buffer, sizeof(buffer)))
3725 		goto invalid_param_len;
3726 
3727 	if (six_byte)
3728 		bd_len = p[3];
3729 	else
3730 		bd_len = get_unaligned_be16(&p[6]);
3731 
3732 	len -= hdr_len;
3733 	p += hdr_len;
3734 	if (len < bd_len)
3735 		goto invalid_param_len;
3736 	if (bd_len != 0 && bd_len != 8) {
3737 		fp = (six_byte) ? 3 : 6;
3738 		fp += bd_len + hdr_len;
3739 		goto invalid_param;
3740 	}
3741 
3742 	len -= bd_len;
3743 	p += bd_len;
3744 	if (len == 0)
3745 		goto skip;
3746 
3747 	/* Parse both possible formats for the mode page headers.  */
3748 	pg = p[0] & 0x3f;
3749 	if (p[0] & 0x40) {
3750 		if (len < 4)
3751 			goto invalid_param_len;
3752 
3753 		spg = p[1];
3754 		pg_len = get_unaligned_be16(&p[2]);
3755 		p += 4;
3756 		len -= 4;
3757 	} else {
3758 		if (len < 2)
3759 			goto invalid_param_len;
3760 
3761 		spg = 0;
3762 		pg_len = p[1];
3763 		p += 2;
3764 		len -= 2;
3765 	}
3766 
3767 	/*
3768 	 * No mode subpages supported (yet) but asking for _all_
3769 	 * subpages may be valid
3770 	 */
3771 	if (spg && (spg != ALL_SUB_MPAGES)) {
3772 		fp = (p[0] & 0x40) ? 1 : 0;
3773 		fp += hdr_len + bd_len;
3774 		goto invalid_param;
3775 	}
3776 	if (pg_len > len)
3777 		goto invalid_param_len;
3778 
3779 	switch (pg) {
3780 	case CACHE_MPAGE:
3781 		if (ata_mselect_caching(qc, p, pg_len, &fp) < 0) {
3782 			fp += hdr_len + bd_len;
3783 			goto invalid_param;
3784 		}
3785 		break;
3786 	case CONTROL_MPAGE:
3787 		if (ata_mselect_control(qc, p, pg_len, &fp) < 0) {
3788 			fp += hdr_len + bd_len;
3789 			goto invalid_param;
3790 		} else {
3791 			goto skip; /* No ATA command to send */
3792 		}
3793 		break;
3794 	default:		/* invalid page code */
3795 		fp = bd_len + hdr_len;
3796 		goto invalid_param;
3797 	}
3798 
3799 	/*
3800 	 * Only one page has changeable data, so we only support setting one
3801 	 * page at a time.
3802 	 */
3803 	if (len > pg_len)
3804 		goto invalid_param;
3805 
3806 	return 0;
3807 
3808  invalid_fld:
3809 	ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
3810 	return 1;
3811 
3812  invalid_param:
3813 	ata_scsi_set_invalid_parameter(qc->dev, scmd, fp);
3814 	return 1;
3815 
3816  invalid_param_len:
3817 	/* "Parameter list length error" */
3818 	ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3819 	return 1;
3820 
3821  skip:
3822 	scmd->result = SAM_STAT_GOOD;
3823 	return 1;
3824 }
3825 
3826 static u8 ata_scsi_trusted_op(u32 len, bool send, bool dma)
3827 {
3828 	if (len == 0)
3829 		return ATA_CMD_TRUSTED_NONDATA;
3830 	else if (send)
3831 		return dma ? ATA_CMD_TRUSTED_SND_DMA : ATA_CMD_TRUSTED_SND;
3832 	else
3833 		return dma ? ATA_CMD_TRUSTED_RCV_DMA : ATA_CMD_TRUSTED_RCV;
3834 }
3835 
3836 static unsigned int ata_scsi_security_inout_xlat(struct ata_queued_cmd *qc)
3837 {
3838 	struct scsi_cmnd *scmd = qc->scsicmd;
3839 	const u8 *cdb = scmd->cmnd;
3840 	struct ata_taskfile *tf = &qc->tf;
3841 	u8 secp = cdb[1];
3842 	bool send = (cdb[0] == SECURITY_PROTOCOL_OUT);
3843 	u16 spsp = get_unaligned_be16(&cdb[2]);
3844 	u32 len = get_unaligned_be32(&cdb[6]);
3845 	bool dma = !(qc->dev->flags & ATA_DFLAG_PIO);
3846 
3847 	/*
3848 	 * We don't support the ATA "security" protocol.
3849 	 */
3850 	if (secp == 0xef) {
3851 		ata_scsi_set_invalid_field(qc->dev, scmd, 1, 0);
3852 		return 1;
3853 	}
3854 
3855 	if (cdb[4] & 7) { /* INC_512 */
3856 		if (len > 0xffff) {
3857 			ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0);
3858 			return 1;
3859 		}
3860 	} else {
3861 		if (len > 0x01fffe00) {
3862 			ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0);
3863 			return 1;
3864 		}
3865 
3866 		/* convert to the sector-based ATA addressing */
3867 		len = (len + 511) / 512;
3868 	}
3869 
3870 	tf->protocol = dma ? ATA_PROT_DMA : ATA_PROT_PIO;
3871 	tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR | ATA_TFLAG_LBA;
3872 	if (send)
3873 		tf->flags |= ATA_TFLAG_WRITE;
3874 	tf->command = ata_scsi_trusted_op(len, send, dma);
3875 	tf->feature = secp;
3876 	tf->lbam = spsp & 0xff;
3877 	tf->lbah = spsp >> 8;
3878 
3879 	if (len) {
3880 		tf->nsect = len & 0xff;
3881 		tf->lbal = len >> 8;
3882 	} else {
3883 		if (!send)
3884 			tf->lbah = (1 << 7);
3885 	}
3886 
3887 	ata_qc_set_pc_nbytes(qc);
3888 	return 0;
3889 }
3890 
3891 /**
3892  *	ata_scsi_var_len_cdb_xlat - SATL variable length CDB to Handler
3893  *	@qc: Command to be translated
3894  *
3895  *	Translate a SCSI variable length CDB to specified commands.
3896  *	It checks a service action value in CDB to call corresponding handler.
3897  *
3898  *	RETURNS:
3899  *	Zero on success, non-zero on failure
3900  *
3901  */
3902 static unsigned int ata_scsi_var_len_cdb_xlat(struct ata_queued_cmd *qc)
3903 {
3904 	struct scsi_cmnd *scmd = qc->scsicmd;
3905 	const u8 *cdb = scmd->cmnd;
3906 	const u16 sa = get_unaligned_be16(&cdb[8]);
3907 
3908 	/*
3909 	 * if service action represents a ata pass-thru(32) command,
3910 	 * then pass it to ata_scsi_pass_thru handler.
3911 	 */
3912 	if (sa == ATA_32)
3913 		return ata_scsi_pass_thru(qc);
3914 
3915 	/* unsupported service action */
3916 	return 1;
3917 }
3918 
3919 /**
3920  *	ata_get_xlat_func - check if SCSI to ATA translation is possible
3921  *	@dev: ATA device
3922  *	@cmd: SCSI command opcode to consider
3923  *
3924  *	Look up the SCSI command given, and determine whether the
3925  *	SCSI command is to be translated or simulated.
3926  *
3927  *	RETURNS:
3928  *	Pointer to translation function if possible, %NULL if not.
3929  */
3930 
3931 static inline ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
3932 {
3933 	switch (cmd) {
3934 	case READ_6:
3935 	case READ_10:
3936 	case READ_16:
3937 
3938 	case WRITE_6:
3939 	case WRITE_10:
3940 	case WRITE_16:
3941 		return ata_scsi_rw_xlat;
3942 
3943 	case WRITE_SAME_16:
3944 		return ata_scsi_write_same_xlat;
3945 
3946 	case SYNCHRONIZE_CACHE:
3947 	case SYNCHRONIZE_CACHE_16:
3948 		if (ata_try_flush_cache(dev))
3949 			return ata_scsi_flush_xlat;
3950 		break;
3951 
3952 	case VERIFY:
3953 	case VERIFY_16:
3954 		return ata_scsi_verify_xlat;
3955 
3956 	case ATA_12:
3957 	case ATA_16:
3958 		return ata_scsi_pass_thru;
3959 
3960 	case VARIABLE_LENGTH_CMD:
3961 		return ata_scsi_var_len_cdb_xlat;
3962 
3963 	case MODE_SELECT:
3964 	case MODE_SELECT_10:
3965 		return ata_scsi_mode_select_xlat;
3966 
3967 	case ZBC_IN:
3968 		return ata_scsi_zbc_in_xlat;
3969 
3970 	case ZBC_OUT:
3971 		return ata_scsi_zbc_out_xlat;
3972 
3973 	case SECURITY_PROTOCOL_IN:
3974 	case SECURITY_PROTOCOL_OUT:
3975 		if (!(dev->flags & ATA_DFLAG_TRUSTED))
3976 			break;
3977 		return ata_scsi_security_inout_xlat;
3978 
3979 	case START_STOP:
3980 		return ata_scsi_start_stop_xlat;
3981 	}
3982 
3983 	return NULL;
3984 }
3985 
3986 int __ata_scsi_queuecmd(struct scsi_cmnd *scmd, struct ata_device *dev)
3987 {
3988 	struct ata_port *ap = dev->link->ap;
3989 	u8 scsi_op = scmd->cmnd[0];
3990 	ata_xlat_func_t xlat_func;
3991 
3992 	/*
3993 	 * scsi_queue_rq() will defer commands if scsi_host_in_recovery().
3994 	 * However, this check is done without holding the ap->lock (a libata
3995 	 * specific lock), so we can have received an error irq since then,
3996 	 * therefore we must check if EH is pending, while holding ap->lock.
3997 	 */
3998 	if (ap->pflags & (ATA_PFLAG_EH_PENDING | ATA_PFLAG_EH_IN_PROGRESS))
3999 		return SCSI_MLQUEUE_DEVICE_BUSY;
4000 
4001 	if (unlikely(!scmd->cmd_len))
4002 		goto bad_cdb_len;
4003 
4004 	if (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ZAC) {
4005 		if (unlikely(scmd->cmd_len > dev->cdb_len))
4006 			goto bad_cdb_len;
4007 
4008 		xlat_func = ata_get_xlat_func(dev, scsi_op);
4009 	} else if (likely((scsi_op != ATA_16) || !atapi_passthru16)) {
4010 		/* relay SCSI command to ATAPI device */
4011 		int len = COMMAND_SIZE(scsi_op);
4012 
4013 		if (unlikely(len > scmd->cmd_len ||
4014 			     len > dev->cdb_len ||
4015 			     scmd->cmd_len > ATAPI_CDB_LEN))
4016 			goto bad_cdb_len;
4017 
4018 		xlat_func = atapi_xlat;
4019 	} else {
4020 		/* ATA_16 passthru, treat as an ATA command */
4021 		if (unlikely(scmd->cmd_len > 16))
4022 			goto bad_cdb_len;
4023 
4024 		xlat_func = ata_get_xlat_func(dev, scsi_op);
4025 	}
4026 
4027 	if (xlat_func)
4028 		return ata_scsi_translate(dev, scmd, xlat_func);
4029 
4030 	ata_scsi_simulate(dev, scmd);
4031 
4032 	return 0;
4033 
4034  bad_cdb_len:
4035 	scmd->result = DID_ERROR << 16;
4036 	scsi_done(scmd);
4037 	return 0;
4038 }
4039 
4040 /**
4041  *	ata_scsi_queuecmd - Issue SCSI cdb to libata-managed device
4042  *	@shost: SCSI host of command to be sent
4043  *	@cmd: SCSI command to be sent
4044  *
4045  *	In some cases, this function translates SCSI commands into
4046  *	ATA taskfiles, and queues the taskfiles to be sent to
4047  *	hardware.  In other cases, this function simulates a
4048  *	SCSI device by evaluating and responding to certain
4049  *	SCSI commands.  This creates the overall effect of
4050  *	ATA and ATAPI devices appearing as SCSI devices.
4051  *
4052  *	LOCKING:
4053  *	ATA host lock
4054  *
4055  *	RETURNS:
4056  *	Return value from __ata_scsi_queuecmd() if @cmd can be queued,
4057  *	0 otherwise.
4058  */
4059 int ata_scsi_queuecmd(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
4060 {
4061 	struct ata_port *ap;
4062 	struct ata_device *dev;
4063 	struct scsi_device *scsidev = cmd->device;
4064 	int rc = 0;
4065 	unsigned long irq_flags;
4066 
4067 	ap = ata_shost_to_port(shost);
4068 
4069 	spin_lock_irqsave(ap->lock, irq_flags);
4070 
4071 	dev = ata_scsi_find_dev(ap, scsidev);
4072 	if (likely(dev))
4073 		rc = __ata_scsi_queuecmd(cmd, dev);
4074 	else {
4075 		cmd->result = (DID_BAD_TARGET << 16);
4076 		scsi_done(cmd);
4077 	}
4078 
4079 	spin_unlock_irqrestore(ap->lock, irq_flags);
4080 
4081 	return rc;
4082 }
4083 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
4084 
4085 /**
4086  *	ata_scsi_simulate - simulate SCSI command on ATA device
4087  *	@dev: the target device
4088  *	@cmd: SCSI command being sent to device.
4089  *
4090  *	Interprets and directly executes a select list of SCSI commands
4091  *	that can be handled internally.
4092  *
4093  *	LOCKING:
4094  *	spin_lock_irqsave(host lock)
4095  */
4096 
4097 void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd)
4098 {
4099 	struct ata_scsi_args args;
4100 	const u8 *scsicmd = cmd->cmnd;
4101 	u8 tmp8;
4102 
4103 	args.dev = dev;
4104 	args.id = dev->id;
4105 	args.cmd = cmd;
4106 
4107 	switch(scsicmd[0]) {
4108 	case INQUIRY:
4109 		if (scsicmd[1] & 2)		   /* is CmdDt set?  */
4110 			ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4111 		else if ((scsicmd[1] & 1) == 0)    /* is EVPD clear? */
4112 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_std);
4113 		else switch (scsicmd[2]) {
4114 		case 0x00:
4115 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_00);
4116 			break;
4117 		case 0x80:
4118 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_80);
4119 			break;
4120 		case 0x83:
4121 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_83);
4122 			break;
4123 		case 0x89:
4124 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_89);
4125 			break;
4126 		case 0xb0:
4127 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b0);
4128 			break;
4129 		case 0xb1:
4130 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b1);
4131 			break;
4132 		case 0xb2:
4133 			ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b2);
4134 			break;
4135 		case 0xb6:
4136 			if (dev->flags & ATA_DFLAG_ZAC)
4137 				ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b6);
4138 			else
4139 				ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
4140 			break;
4141 		case 0xb9:
4142 			if (dev->cpr_log)
4143 				ata_scsi_rbuf_fill(&args, ata_scsiop_inq_b9);
4144 			else
4145 				ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
4146 			break;
4147 		default:
4148 			ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
4149 			break;
4150 		}
4151 		break;
4152 
4153 	case MODE_SENSE:
4154 	case MODE_SENSE_10:
4155 		ata_scsi_rbuf_fill(&args, ata_scsiop_mode_sense);
4156 		break;
4157 
4158 	case READ_CAPACITY:
4159 		ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
4160 		break;
4161 
4162 	case SERVICE_ACTION_IN_16:
4163 		if ((scsicmd[1] & 0x1f) == SAI_READ_CAPACITY_16)
4164 			ata_scsi_rbuf_fill(&args, ata_scsiop_read_cap);
4165 		else
4166 			ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4167 		break;
4168 
4169 	case REPORT_LUNS:
4170 		ata_scsi_rbuf_fill(&args, ata_scsiop_report_luns);
4171 		break;
4172 
4173 	case REQUEST_SENSE:
4174 		ata_scsi_set_sense(dev, cmd, 0, 0, 0);
4175 		break;
4176 
4177 	/* if we reach this, then writeback caching is disabled,
4178 	 * turning this into a no-op.
4179 	 */
4180 	case SYNCHRONIZE_CACHE:
4181 	case SYNCHRONIZE_CACHE_16:
4182 		fallthrough;
4183 
4184 	/* no-op's, complete with success */
4185 	case REZERO_UNIT:
4186 	case SEEK_6:
4187 	case SEEK_10:
4188 	case TEST_UNIT_READY:
4189 		break;
4190 
4191 	case SEND_DIAGNOSTIC:
4192 		tmp8 = scsicmd[1] & ~(1 << 3);
4193 		if (tmp8 != 0x4 || scsicmd[3] || scsicmd[4])
4194 			ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4195 		break;
4196 
4197 	case MAINTENANCE_IN:
4198 		if (scsicmd[1] == MI_REPORT_SUPPORTED_OPERATION_CODES)
4199 			ata_scsi_rbuf_fill(&args, ata_scsiop_maint_in);
4200 		else
4201 			ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4202 		break;
4203 
4204 	/* all other commands */
4205 	default:
4206 		ata_scsi_set_sense(dev, cmd, ILLEGAL_REQUEST, 0x20, 0x0);
4207 		/* "Invalid command operation code" */
4208 		break;
4209 	}
4210 
4211 	scsi_done(cmd);
4212 }
4213 
4214 int ata_scsi_add_hosts(struct ata_host *host, struct scsi_host_template *sht)
4215 {
4216 	int i, rc;
4217 
4218 	for (i = 0; i < host->n_ports; i++) {
4219 		struct ata_port *ap = host->ports[i];
4220 		struct Scsi_Host *shost;
4221 
4222 		rc = -ENOMEM;
4223 		shost = scsi_host_alloc(sht, sizeof(struct ata_port *));
4224 		if (!shost)
4225 			goto err_alloc;
4226 
4227 		shost->eh_noresume = 1;
4228 		*(struct ata_port **)&shost->hostdata[0] = ap;
4229 		ap->scsi_host = shost;
4230 
4231 		shost->transportt = ata_scsi_transport_template;
4232 		shost->unique_id = ap->print_id;
4233 		shost->max_id = 16;
4234 		shost->max_lun = 1;
4235 		shost->max_channel = 1;
4236 		shost->max_cmd_len = 32;
4237 
4238 		/* Schedule policy is determined by ->qc_defer()
4239 		 * callback and it needs to see every deferred qc.
4240 		 * Set host_blocked to 1 to prevent SCSI midlayer from
4241 		 * automatically deferring requests.
4242 		 */
4243 		shost->max_host_blocked = 1;
4244 
4245 		rc = scsi_add_host_with_dma(shost, &ap->tdev, ap->host->dev);
4246 		if (rc)
4247 			goto err_alloc;
4248 	}
4249 
4250 	return 0;
4251 
4252  err_alloc:
4253 	while (--i >= 0) {
4254 		struct Scsi_Host *shost = host->ports[i]->scsi_host;
4255 
4256 		/* scsi_host_put() is in ata_devres_release() */
4257 		scsi_remove_host(shost);
4258 	}
4259 	return rc;
4260 }
4261 
4262 #ifdef CONFIG_OF
4263 static void ata_scsi_assign_ofnode(struct ata_device *dev, struct ata_port *ap)
4264 {
4265 	struct scsi_device *sdev = dev->sdev;
4266 	struct device *d = ap->host->dev;
4267 	struct device_node *np = d->of_node;
4268 	struct device_node *child;
4269 
4270 	for_each_available_child_of_node(np, child) {
4271 		int ret;
4272 		u32 val;
4273 
4274 		ret = of_property_read_u32(child, "reg", &val);
4275 		if (ret)
4276 			continue;
4277 		if (val == dev->devno) {
4278 			dev_dbg(d, "found matching device node\n");
4279 			sdev->sdev_gendev.of_node = child;
4280 			return;
4281 		}
4282 	}
4283 }
4284 #else
4285 static void ata_scsi_assign_ofnode(struct ata_device *dev, struct ata_port *ap)
4286 {
4287 }
4288 #endif
4289 
4290 void ata_scsi_scan_host(struct ata_port *ap, int sync)
4291 {
4292 	int tries = 5;
4293 	struct ata_device *last_failed_dev = NULL;
4294 	struct ata_link *link;
4295 	struct ata_device *dev;
4296 
4297  repeat:
4298 	ata_for_each_link(link, ap, EDGE) {
4299 		ata_for_each_dev(dev, link, ENABLED) {
4300 			struct scsi_device *sdev;
4301 			int channel = 0, id = 0;
4302 
4303 			if (dev->sdev)
4304 				continue;
4305 
4306 			if (ata_is_host_link(link))
4307 				id = dev->devno;
4308 			else
4309 				channel = link->pmp;
4310 
4311 			sdev = __scsi_add_device(ap->scsi_host, channel, id, 0,
4312 						 NULL);
4313 			if (!IS_ERR(sdev)) {
4314 				dev->sdev = sdev;
4315 				ata_scsi_assign_ofnode(dev, ap);
4316 				scsi_device_put(sdev);
4317 			} else {
4318 				dev->sdev = NULL;
4319 			}
4320 		}
4321 	}
4322 
4323 	/* If we scanned while EH was in progress or allocation
4324 	 * failure occurred, scan would have failed silently.  Check
4325 	 * whether all devices are attached.
4326 	 */
4327 	ata_for_each_link(link, ap, EDGE) {
4328 		ata_for_each_dev(dev, link, ENABLED) {
4329 			if (!dev->sdev)
4330 				goto exit_loop;
4331 		}
4332 	}
4333  exit_loop:
4334 	if (!link)
4335 		return;
4336 
4337 	/* we're missing some SCSI devices */
4338 	if (sync) {
4339 		/* If caller requested synchrnous scan && we've made
4340 		 * any progress, sleep briefly and repeat.
4341 		 */
4342 		if (dev != last_failed_dev) {
4343 			msleep(100);
4344 			last_failed_dev = dev;
4345 			goto repeat;
4346 		}
4347 
4348 		/* We might be failing to detect boot device, give it
4349 		 * a few more chances.
4350 		 */
4351 		if (--tries) {
4352 			msleep(100);
4353 			goto repeat;
4354 		}
4355 
4356 		ata_port_err(ap,
4357 			     "WARNING: synchronous SCSI scan failed without making any progress, switching to async\n");
4358 	}
4359 
4360 	queue_delayed_work(system_long_wq, &ap->hotplug_task,
4361 			   round_jiffies_relative(HZ));
4362 }
4363 
4364 /**
4365  *	ata_scsi_offline_dev - offline attached SCSI device
4366  *	@dev: ATA device to offline attached SCSI device for
4367  *
4368  *	This function is called from ata_eh_hotplug() and responsible
4369  *	for taking the SCSI device attached to @dev offline.  This
4370  *	function is called with host lock which protects dev->sdev
4371  *	against clearing.
4372  *
4373  *	LOCKING:
4374  *	spin_lock_irqsave(host lock)
4375  *
4376  *	RETURNS:
4377  *	1 if attached SCSI device exists, 0 otherwise.
4378  */
4379 int ata_scsi_offline_dev(struct ata_device *dev)
4380 {
4381 	if (dev->sdev) {
4382 		scsi_device_set_state(dev->sdev, SDEV_OFFLINE);
4383 		return 1;
4384 	}
4385 	return 0;
4386 }
4387 
4388 /**
4389  *	ata_scsi_remove_dev - remove attached SCSI device
4390  *	@dev: ATA device to remove attached SCSI device for
4391  *
4392  *	This function is called from ata_eh_scsi_hotplug() and
4393  *	responsible for removing the SCSI device attached to @dev.
4394  *
4395  *	LOCKING:
4396  *	Kernel thread context (may sleep).
4397  */
4398 static void ata_scsi_remove_dev(struct ata_device *dev)
4399 {
4400 	struct ata_port *ap = dev->link->ap;
4401 	struct scsi_device *sdev;
4402 	unsigned long flags;
4403 
4404 	/* Alas, we need to grab scan_mutex to ensure SCSI device
4405 	 * state doesn't change underneath us and thus
4406 	 * scsi_device_get() always succeeds.  The mutex locking can
4407 	 * be removed if there is __scsi_device_get() interface which
4408 	 * increments reference counts regardless of device state.
4409 	 */
4410 	mutex_lock(&ap->scsi_host->scan_mutex);
4411 	spin_lock_irqsave(ap->lock, flags);
4412 
4413 	/* clearing dev->sdev is protected by host lock */
4414 	sdev = dev->sdev;
4415 	dev->sdev = NULL;
4416 
4417 	if (sdev) {
4418 		/* If user initiated unplug races with us, sdev can go
4419 		 * away underneath us after the host lock and
4420 		 * scan_mutex are released.  Hold onto it.
4421 		 */
4422 		if (scsi_device_get(sdev) == 0) {
4423 			/* The following ensures the attached sdev is
4424 			 * offline on return from ata_scsi_offline_dev()
4425 			 * regardless it wins or loses the race
4426 			 * against this function.
4427 			 */
4428 			scsi_device_set_state(sdev, SDEV_OFFLINE);
4429 		} else {
4430 			WARN_ON(1);
4431 			sdev = NULL;
4432 		}
4433 	}
4434 
4435 	spin_unlock_irqrestore(ap->lock, flags);
4436 	mutex_unlock(&ap->scsi_host->scan_mutex);
4437 
4438 	if (sdev) {
4439 		ata_dev_info(dev, "detaching (SCSI %s)\n",
4440 			     dev_name(&sdev->sdev_gendev));
4441 
4442 		scsi_remove_device(sdev);
4443 		scsi_device_put(sdev);
4444 	}
4445 }
4446 
4447 static void ata_scsi_handle_link_detach(struct ata_link *link)
4448 {
4449 	struct ata_port *ap = link->ap;
4450 	struct ata_device *dev;
4451 
4452 	ata_for_each_dev(dev, link, ALL) {
4453 		unsigned long flags;
4454 
4455 		if (!(dev->flags & ATA_DFLAG_DETACHED))
4456 			continue;
4457 
4458 		spin_lock_irqsave(ap->lock, flags);
4459 		dev->flags &= ~ATA_DFLAG_DETACHED;
4460 		spin_unlock_irqrestore(ap->lock, flags);
4461 
4462 		if (zpodd_dev_enabled(dev))
4463 			zpodd_exit(dev);
4464 
4465 		ata_scsi_remove_dev(dev);
4466 	}
4467 }
4468 
4469 /**
4470  *	ata_scsi_media_change_notify - send media change event
4471  *	@dev: Pointer to the disk device with media change event
4472  *
4473  *	Tell the block layer to send a media change notification
4474  *	event.
4475  *
4476  * 	LOCKING:
4477  * 	spin_lock_irqsave(host lock)
4478  */
4479 void ata_scsi_media_change_notify(struct ata_device *dev)
4480 {
4481 	if (dev->sdev)
4482 		sdev_evt_send_simple(dev->sdev, SDEV_EVT_MEDIA_CHANGE,
4483 				     GFP_ATOMIC);
4484 }
4485 
4486 /**
4487  *	ata_scsi_hotplug - SCSI part of hotplug
4488  *	@work: Pointer to ATA port to perform SCSI hotplug on
4489  *
4490  *	Perform SCSI part of hotplug.  It's executed from a separate
4491  *	workqueue after EH completes.  This is necessary because SCSI
4492  *	hot plugging requires working EH and hot unplugging is
4493  *	synchronized with hot plugging with a mutex.
4494  *
4495  *	LOCKING:
4496  *	Kernel thread context (may sleep).
4497  */
4498 void ata_scsi_hotplug(struct work_struct *work)
4499 {
4500 	struct ata_port *ap =
4501 		container_of(work, struct ata_port, hotplug_task.work);
4502 	int i;
4503 
4504 	if (ap->pflags & ATA_PFLAG_UNLOADING)
4505 		return;
4506 
4507 	mutex_lock(&ap->scsi_scan_mutex);
4508 
4509 	/* Unplug detached devices.  We cannot use link iterator here
4510 	 * because PMP links have to be scanned even if PMP is
4511 	 * currently not attached.  Iterate manually.
4512 	 */
4513 	ata_scsi_handle_link_detach(&ap->link);
4514 	if (ap->pmp_link)
4515 		for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
4516 			ata_scsi_handle_link_detach(&ap->pmp_link[i]);
4517 
4518 	/* scan for new ones */
4519 	ata_scsi_scan_host(ap, 0);
4520 
4521 	mutex_unlock(&ap->scsi_scan_mutex);
4522 }
4523 
4524 /**
4525  *	ata_scsi_user_scan - indication for user-initiated bus scan
4526  *	@shost: SCSI host to scan
4527  *	@channel: Channel to scan
4528  *	@id: ID to scan
4529  *	@lun: LUN to scan
4530  *
4531  *	This function is called when user explicitly requests bus
4532  *	scan.  Set probe pending flag and invoke EH.
4533  *
4534  *	LOCKING:
4535  *	SCSI layer (we don't care)
4536  *
4537  *	RETURNS:
4538  *	Zero.
4539  */
4540 int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel,
4541 		       unsigned int id, u64 lun)
4542 {
4543 	struct ata_port *ap = ata_shost_to_port(shost);
4544 	unsigned long flags;
4545 	int devno, rc = 0;
4546 
4547 	if (!ap->ops->error_handler)
4548 		return -EOPNOTSUPP;
4549 
4550 	if (lun != SCAN_WILD_CARD && lun)
4551 		return -EINVAL;
4552 
4553 	if (!sata_pmp_attached(ap)) {
4554 		if (channel != SCAN_WILD_CARD && channel)
4555 			return -EINVAL;
4556 		devno = id;
4557 	} else {
4558 		if (id != SCAN_WILD_CARD && id)
4559 			return -EINVAL;
4560 		devno = channel;
4561 	}
4562 
4563 	spin_lock_irqsave(ap->lock, flags);
4564 
4565 	if (devno == SCAN_WILD_CARD) {
4566 		struct ata_link *link;
4567 
4568 		ata_for_each_link(link, ap, EDGE) {
4569 			struct ata_eh_info *ehi = &link->eh_info;
4570 			ehi->probe_mask |= ATA_ALL_DEVICES;
4571 			ehi->action |= ATA_EH_RESET;
4572 		}
4573 	} else {
4574 		struct ata_device *dev = ata_find_dev(ap, devno);
4575 
4576 		if (dev) {
4577 			struct ata_eh_info *ehi = &dev->link->eh_info;
4578 			ehi->probe_mask |= 1 << dev->devno;
4579 			ehi->action |= ATA_EH_RESET;
4580 		} else
4581 			rc = -EINVAL;
4582 	}
4583 
4584 	if (rc == 0) {
4585 		ata_port_schedule_eh(ap);
4586 		spin_unlock_irqrestore(ap->lock, flags);
4587 		ata_port_wait_eh(ap);
4588 	} else
4589 		spin_unlock_irqrestore(ap->lock, flags);
4590 
4591 	return rc;
4592 }
4593 
4594 /**
4595  *	ata_scsi_dev_rescan - initiate scsi_rescan_device()
4596  *	@work: Pointer to ATA port to perform scsi_rescan_device()
4597  *
4598  *	After ATA pass thru (SAT) commands are executed successfully,
4599  *	libata need to propagate the changes to SCSI layer.
4600  *
4601  *	LOCKING:
4602  *	Kernel thread context (may sleep).
4603  */
4604 void ata_scsi_dev_rescan(struct work_struct *work)
4605 {
4606 	struct ata_port *ap =
4607 		container_of(work, struct ata_port, scsi_rescan_task);
4608 	struct ata_link *link;
4609 	struct ata_device *dev;
4610 	unsigned long flags;
4611 
4612 	mutex_lock(&ap->scsi_scan_mutex);
4613 	spin_lock_irqsave(ap->lock, flags);
4614 
4615 	ata_for_each_link(link, ap, EDGE) {
4616 		ata_for_each_dev(dev, link, ENABLED) {
4617 			struct scsi_device *sdev = dev->sdev;
4618 
4619 			if (!sdev)
4620 				continue;
4621 			if (scsi_device_get(sdev))
4622 				continue;
4623 
4624 			spin_unlock_irqrestore(ap->lock, flags);
4625 			scsi_rescan_device(&(sdev->sdev_gendev));
4626 			scsi_device_put(sdev);
4627 			spin_lock_irqsave(ap->lock, flags);
4628 		}
4629 	}
4630 
4631 	spin_unlock_irqrestore(ap->lock, flags);
4632 	mutex_unlock(&ap->scsi_scan_mutex);
4633 }
4634