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