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