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