xref: /linux/drivers/ata/libata-scsi.c (revision 5a69195686d5b874ac5a4c7f809ecb75fbc535ef)
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 
ata_scsi_park_show(struct device * device,struct device_attribute * attr,char * buf)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 
ata_scsi_park_store(struct device * device,struct device_attribute * attr,const char * buf,size_t len)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 
ata_scsi_sense_is_valid(u8 sk,u8 asc,u8 ascq)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 
ata_scsi_set_sense(struct ata_device * dev,struct scsi_cmnd * cmd,u8 sk,u8 asc,u8 ascq)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 
ata_scsi_set_sense_information(struct ata_queued_cmd * qc)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  */
ata_scsi_set_passthru_sense_fields(struct ata_queued_cmd * qc)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 
ata_scsi_set_invalid_field(struct ata_device * dev,struct scsi_cmnd * cmd,u16 field,u8 bit)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 
ata_scsi_set_invalid_parameter(struct ata_device * dev,struct scsi_cmnd * cmd,u16 field)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  */
ata_std_bios_param(struct scsi_device * sdev,struct gendisk * unused,sector_t capacity,int geom[])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  */
ata_scsi_unlock_native_capacity(struct scsi_device * sdev)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  */
ata_get_identity(struct ata_port * ap,struct scsi_device * sdev,void __user * arg)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  */
ata_cmd_ioctl(struct scsi_device * scsidev,void __user * arg)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  */
ata_task_ioctl(struct scsi_device * scsidev,void __user * arg)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 
ata_ioc32(struct ata_port * ap)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  */
ata_sas_scsi_ioctl(struct ata_port * ap,struct scsi_device * scsidev,unsigned int cmd,void __user * arg)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 
ata_scsi_ioctl(struct scsi_device * scsidev,unsigned int cmd,void __user * arg)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  */
ata_scsi_qc_new(struct ata_device * dev,struct scsi_cmnd * cmd)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 
ata_qc_set_pc_nbytes(struct ata_queued_cmd * qc)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  */
ata_to_sense_error(u8 drv_stat,u8 drv_err,u8 * sk,u8 * asc,u8 * ascq)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  */
ata_gen_passthru_sense(struct ata_queued_cmd * qc)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  */
ata_gen_ata_sense(struct ata_queued_cmd * qc)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 
ata_scsi_sdev_config(struct scsi_device * sdev)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  */
ata_scsi_dma_need_drain(struct request * rq)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 
ata_scsi_dev_config(struct scsi_device * sdev,struct queue_limits * lim,struct ata_device * dev)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 
ata_scsi_sdev_init(struct scsi_device * sdev)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 
ata_scsi_sdev_configure(struct scsi_device * sdev,struct queue_limits * lim)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  */
ata_scsi_sdev_destroy(struct scsi_device * sdev)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  */
ata_scsi_start_stop_xlat(struct ata_queued_cmd * qc)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  */
ata_scsi_flush_xlat(struct ata_queued_cmd * qc)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  */
scsi_6_lba_len(const u8 * cdb,u64 * plba,u32 * plen)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  */
scsi_10_lba_len(const u8 * cdb,u64 * plba,u32 * plen)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  */
scsi_16_lba_len(const u8 * cdb,u64 * plba,u32 * plen)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  */
scsi_dld(const u8 * cdb)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  */
ata_scsi_verify_xlat(struct ata_queued_cmd * qc)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 
ata_check_nblocks(struct scsi_cmnd * scmd,u32 n_blocks)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  */
ata_scsi_rw_xlat(struct ata_queued_cmd * qc)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 
ata_scsi_qc_done(struct ata_queued_cmd * qc,bool set_result,u32 scmd_result)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 
ata_scsi_deferred_qc_work(struct work_struct * work)1665 void ata_scsi_deferred_qc_work(struct work_struct *work)
1666 {
1667 	struct ata_port *ap =
1668 		container_of(work, struct ata_port, deferred_qc_work);
1669 	struct ata_queued_cmd *qc;
1670 	unsigned long flags;
1671 
1672 	spin_lock_irqsave(ap->lock, flags);
1673 
1674 	/*
1675 	 * If we still have a deferred qc and we are not in EH, issue it. In
1676 	 * such case, we should not need any more deferring the qc, so warn if
1677 	 * qc_defer() says otherwise.
1678 	 */
1679 	qc = ap->deferred_qc;
1680 	if (qc && !ata_port_eh_scheduled(ap)) {
1681 		WARN_ON_ONCE(ap->ops->qc_defer(qc));
1682 		ap->deferred_qc = NULL;
1683 		ata_qc_issue(qc);
1684 	}
1685 
1686 	spin_unlock_irqrestore(ap->lock, flags);
1687 }
1688 
ata_scsi_requeue_deferred_qc(struct ata_port * ap)1689 void ata_scsi_requeue_deferred_qc(struct ata_port *ap)
1690 {
1691 	struct ata_queued_cmd *qc = ap->deferred_qc;
1692 
1693 	lockdep_assert_held(ap->lock);
1694 
1695 	/*
1696 	 * If we have a deferred qc when a reset occurs or NCQ commands fail,
1697 	 * do not try to be smart about what to do with this deferred command
1698 	 * and simply requeue it by completing it with DID_REQUEUE.
1699 	 */
1700 	if (qc) {
1701 		ap->deferred_qc = NULL;
1702 		cancel_work(&ap->deferred_qc_work);
1703 		ata_scsi_qc_done(qc, true, DID_REQUEUE << 16);
1704 	}
1705 }
1706 
ata_scsi_schedule_deferred_qc(struct ata_port * ap)1707 static void ata_scsi_schedule_deferred_qc(struct ata_port *ap)
1708 {
1709 	struct ata_queued_cmd *qc = ap->deferred_qc;
1710 
1711 	lockdep_assert_held(ap->lock);
1712 
1713 	/*
1714 	 * If we have a deferred qc, then qc_defer() is defined and we can use
1715 	 * this callback to determine if this qc is good to go, unless EH has
1716 	 * been scheduled.
1717 	 */
1718 	if (!qc)
1719 		return;
1720 
1721 	if (ata_port_eh_scheduled(ap)) {
1722 		ata_scsi_requeue_deferred_qc(ap);
1723 		return;
1724 	}
1725 	if (!ap->ops->qc_defer(qc))
1726 		queue_work(system_highpri_wq, &ap->deferred_qc_work);
1727 }
1728 
ata_scsi_qc_complete(struct ata_queued_cmd * qc)1729 static void ata_scsi_qc_complete(struct ata_queued_cmd *qc)
1730 {
1731 	struct ata_port *ap = qc->ap;
1732 	struct scsi_cmnd *cmd = qc->scsicmd;
1733 	u8 *cdb = cmd->cmnd;
1734 	bool have_sense = qc->flags & ATA_QCFLAG_SENSE_VALID;
1735 	bool is_ata_passthru = cdb[0] == ATA_16 || cdb[0] == ATA_12;
1736 	bool is_ck_cond_request = cdb[2] & 0x20;
1737 	bool is_error = qc->err_mask != 0;
1738 
1739 	/* For ATA pass thru (SAT) commands, generate a sense block if
1740 	 * user mandated it or if there's an error.  Note that if we
1741 	 * generate because the user forced us to [CK_COND=1], a check
1742 	 * condition is generated and the ATA register values are returned
1743 	 * whether the command completed successfully or not. If there
1744 	 * was no error, and CK_COND=1, we use the following sense data:
1745 	 * sk = RECOVERED ERROR
1746 	 * asc,ascq = ATA PASS-THROUGH INFORMATION AVAILABLE
1747 	 */
1748 	if (is_ata_passthru && (is_ck_cond_request || is_error || have_sense)) {
1749 		if (!have_sense)
1750 			ata_gen_passthru_sense(qc);
1751 		ata_scsi_set_passthru_sense_fields(qc);
1752 		if (is_ck_cond_request)
1753 			set_status_byte(qc->scsicmd, SAM_STAT_CHECK_CONDITION);
1754 	} else if (is_error) {
1755 		if (!have_sense)
1756 			ata_gen_ata_sense(qc);
1757 		ata_scsi_set_sense_information(qc);
1758 	}
1759 
1760 	ata_scsi_qc_done(qc, false, 0);
1761 
1762 	ata_scsi_schedule_deferred_qc(ap);
1763 }
1764 
ata_scsi_qc_issue(struct ata_port * ap,struct ata_queued_cmd * qc)1765 static int ata_scsi_qc_issue(struct ata_port *ap, struct ata_queued_cmd *qc)
1766 {
1767 	int ret;
1768 
1769 	if (!ap->ops->qc_defer)
1770 		goto issue;
1771 
1772 	/*
1773 	 * If we already have a deferred qc, then rely on the SCSI layer to
1774 	 * requeue and defer all incoming commands until the deferred qc is
1775 	 * processed, once all on-going commands complete.
1776 	 */
1777 	if (ap->deferred_qc) {
1778 		ata_qc_free(qc);
1779 		return SCSI_MLQUEUE_DEVICE_BUSY;
1780 	}
1781 
1782 	/* Check if the command needs to be deferred. */
1783 	ret = ap->ops->qc_defer(qc);
1784 	switch (ret) {
1785 	case 0:
1786 		break;
1787 	case ATA_DEFER_LINK:
1788 		ret = SCSI_MLQUEUE_DEVICE_BUSY;
1789 		break;
1790 	case ATA_DEFER_PORT:
1791 		ret = SCSI_MLQUEUE_HOST_BUSY;
1792 		break;
1793 	default:
1794 		WARN_ON_ONCE(1);
1795 		ret = SCSI_MLQUEUE_HOST_BUSY;
1796 		break;
1797 	}
1798 
1799 	if (ret) {
1800 		/*
1801 		 * We must defer this qc: if this is not an NCQ command, keep
1802 		 * this qc as a deferred one and report to the SCSI layer that
1803 		 * we issued it so that it is not requeued. The deferred qc will
1804 		 * be issued with the port deferred_qc_work once all on-going
1805 		 * commands complete.
1806 		 */
1807 		if (!ata_is_ncq(qc->tf.protocol)) {
1808 			ap->deferred_qc = qc;
1809 			return 0;
1810 		}
1811 
1812 		/* Force a requeue of the command to defer its execution. */
1813 		ata_qc_free(qc);
1814 		return ret;
1815 	}
1816 
1817 issue:
1818 	ata_qc_issue(qc);
1819 
1820 	return 0;
1821 }
1822 
1823 /**
1824  *	ata_scsi_translate - Translate then issue SCSI command to ATA device
1825  *	@dev: ATA device to which the command is addressed
1826  *	@cmd: SCSI command to execute
1827  *	@xlat_func: Actor which translates @cmd to an ATA taskfile
1828  *
1829  *	Our ->queuecommand() function has decided that the SCSI
1830  *	command issued can be directly translated into an ATA
1831  *	command, rather than handled internally.
1832  *
1833  *	This function sets up an ata_queued_cmd structure for the
1834  *	SCSI command, and sends that ata_queued_cmd to the hardware.
1835  *
1836  *	The xlat_func argument (actor) returns 0 if ready to execute
1837  *	ATA command, else 1 to finish translation. If 1 is returned
1838  *	then cmd->result (and possibly cmd->sense_buffer) are assumed
1839  *	to be set reflecting an error condition or clean (early)
1840  *	termination.
1841  *
1842  *	LOCKING:
1843  *	spin_lock_irqsave(host lock)
1844  *
1845  *	RETURNS:
1846  *	0 on success, SCSI_ML_QUEUE_DEVICE_BUSY or SCSI_MLQUEUE_HOST_BUSY if the
1847  *	command needs to be deferred.
1848  */
ata_scsi_translate(struct ata_device * dev,struct scsi_cmnd * cmd,ata_xlat_func_t xlat_func)1849 static int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd,
1850 			      ata_xlat_func_t xlat_func)
1851 {
1852 	struct ata_port *ap = dev->link->ap;
1853 	struct ata_queued_cmd *qc;
1854 
1855 	lockdep_assert_held(ap->lock);
1856 
1857 	/*
1858 	 * ata_scsi_qc_new() calls scsi_done(cmd) in case of failure. So we
1859 	 * have nothing further to do when allocating a qc fails.
1860 	 */
1861 	qc = ata_scsi_qc_new(dev, cmd);
1862 	if (!qc)
1863 		return 0;
1864 
1865 	/* data is present; dma-map it */
1866 	if (cmd->sc_data_direction == DMA_FROM_DEVICE ||
1867 	    cmd->sc_data_direction == DMA_TO_DEVICE) {
1868 		if (unlikely(scsi_bufflen(cmd) < 1)) {
1869 			ata_dev_warn(dev, "WARNING: zero len r/w req\n");
1870 			cmd->result = (DID_ERROR << 16);
1871 			goto done;
1872 		}
1873 
1874 		ata_sg_init(qc, scsi_sglist(cmd), scsi_sg_count(cmd));
1875 		qc->dma_dir = cmd->sc_data_direction;
1876 	}
1877 
1878 	qc->complete_fn = ata_scsi_qc_complete;
1879 
1880 	if (xlat_func(qc))
1881 		goto done;
1882 
1883 	return ata_scsi_qc_issue(ap, qc);
1884 
1885 done:
1886 	ata_qc_free(qc);
1887 	scsi_done(cmd);
1888 	return 0;
1889 }
1890 
1891 /**
1892  *	ata_scsi_rbuf_fill - wrapper for SCSI command simulators
1893  *	@dev: Target device.
1894  *	@cmd: SCSI command of interest.
1895  *	@actor: Callback hook for desired SCSI command simulator
1896  *
1897  *	Takes care of the hard work of simulating a SCSI command...
1898  *	Mapping the response buffer, calling the command's handler,
1899  *	and handling the handler's return value.  This return value
1900  *	indicates whether the handler wishes the SCSI command to be
1901  *	completed successfully (0), or not (in which case cmd->result
1902  *	and sense buffer are assumed to be set).
1903  *
1904  *	LOCKING:
1905  *	spin_lock_irqsave(host lock)
1906  */
ata_scsi_rbuf_fill(struct ata_device * dev,struct scsi_cmnd * cmd,unsigned int (* actor)(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf))1907 static void ata_scsi_rbuf_fill(struct ata_device *dev, struct scsi_cmnd *cmd,
1908 		unsigned int (*actor)(struct ata_device *dev,
1909 				      struct scsi_cmnd *cmd, u8 *rbuf))
1910 {
1911 	unsigned long flags;
1912 	unsigned int len;
1913 
1914 	spin_lock_irqsave(&ata_scsi_rbuf_lock, flags);
1915 
1916 	memset(ata_scsi_rbuf, 0, ATA_SCSI_RBUF_SIZE);
1917 	len = actor(dev, cmd, ata_scsi_rbuf);
1918 	if (len) {
1919 		sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd),
1920 				    ata_scsi_rbuf, ATA_SCSI_RBUF_SIZE);
1921 		cmd->result = SAM_STAT_GOOD;
1922 		if (scsi_bufflen(cmd) > len)
1923 			scsi_set_resid(cmd, scsi_bufflen(cmd) - len);
1924 	}
1925 
1926 	spin_unlock_irqrestore(&ata_scsi_rbuf_lock, flags);
1927 }
1928 
1929 /**
1930  *	ata_scsiop_inq_std - Simulate standard INQUIRY command
1931  *	@dev: Target device.
1932  *	@cmd: SCSI command of interest.
1933  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
1934  *
1935  *	Returns standard device identification data associated
1936  *	with non-VPD INQUIRY command output.
1937  *
1938  *	LOCKING:
1939  *	spin_lock_irqsave(host lock)
1940  */
ata_scsiop_inq_std(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)1941 static unsigned int ata_scsiop_inq_std(struct ata_device *dev,
1942 				       struct scsi_cmnd *cmd, u8 *rbuf)
1943 {
1944 	static const u8 versions[] = {
1945 		0x00,
1946 		0x60,	/* SAM-3 (no version claimed) */
1947 
1948 		0x03,
1949 		0x20,	/* SBC-2 (no version claimed) */
1950 
1951 		0x03,
1952 		0x00	/* SPC-3 (no version claimed) */
1953 	};
1954 	static const u8 versions_zbc[] = {
1955 		0x00,
1956 		0xA0,	/* SAM-5 (no version claimed) */
1957 
1958 		0x06,
1959 		0x00,	/* SBC-4 (no version claimed) */
1960 
1961 		0x05,
1962 		0xC0,	/* SPC-5 (no version claimed) */
1963 
1964 		0x60,
1965 		0x24,   /* ZBC r05 */
1966 	};
1967 
1968 	u8 hdr[] = {
1969 		TYPE_DISK,
1970 		0,
1971 		0x5,	/* claim SPC-3 version compatibility */
1972 		2,
1973 		95 - 4,
1974 		0,
1975 		0,
1976 		2
1977 	};
1978 
1979 	/*
1980 	 * Set the SCSI Removable Media Bit (RMB) if the ATA removable media
1981 	 * device bit (obsolete since ATA-8 ACS) is set.
1982 	 */
1983 	if (ata_id_removable(dev->id))
1984 		hdr[1] |= (1 << 7);
1985 
1986 	if (dev->class == ATA_DEV_ZAC) {
1987 		hdr[0] = TYPE_ZBC;
1988 		hdr[2] = 0x7; /* claim SPC-5 version compatibility */
1989 	}
1990 
1991 	if (dev->flags & ATA_DFLAG_CDL)
1992 		hdr[2] = 0xd; /* claim SPC-6 version compatibility */
1993 
1994 	memcpy(rbuf, hdr, sizeof(hdr));
1995 	memcpy(&rbuf[8], "ATA     ", 8);
1996 	ata_id_string(dev->id, &rbuf[16], ATA_ID_PROD, 16);
1997 
1998 	/* From SAT, use last 2 words from fw rev unless they are spaces */
1999 	ata_id_string(dev->id, &rbuf[32], ATA_ID_FW_REV + 2, 4);
2000 	if (strncmp(&rbuf[32], "    ", 4) == 0)
2001 		ata_id_string(dev->id, &rbuf[32], ATA_ID_FW_REV, 4);
2002 
2003 	if (rbuf[32] == 0 || rbuf[32] == ' ')
2004 		memcpy(&rbuf[32], "n/a ", 4);
2005 
2006 	if (ata_id_zoned_cap(dev->id) || dev->class == ATA_DEV_ZAC)
2007 		memcpy(rbuf + 58, versions_zbc, sizeof(versions_zbc));
2008 	else
2009 		memcpy(rbuf + 58, versions, sizeof(versions));
2010 
2011 	/*
2012 	 * Include all 8 possible version descriptors, even if not all of
2013 	 * them are popoulated.
2014 	 */
2015 	return 96;
2016 }
2017 
2018 /**
2019  *	ata_scsiop_inq_00 - Simulate INQUIRY VPD page 0, list of pages
2020  *	@dev: Target device.
2021  *	@cmd: SCSI command of interest.
2022  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2023  *
2024  *	Returns list of inquiry VPD pages available.
2025  *
2026  *	LOCKING:
2027  *	spin_lock_irqsave(host lock)
2028  */
ata_scsiop_inq_00(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2029 static unsigned int ata_scsiop_inq_00(struct ata_device *dev,
2030 				      struct scsi_cmnd *cmd, u8 *rbuf)
2031 {
2032 	int i, num_pages = 0;
2033 	static const u8 pages[] = {
2034 		0x00,	/* page 0x00, this page */
2035 		0x80,	/* page 0x80, unit serial no page */
2036 		0x83,	/* page 0x83, device ident page */
2037 		0x89,	/* page 0x89, ata info page */
2038 		0xb0,	/* page 0xb0, block limits page */
2039 		0xb1,	/* page 0xb1, block device characteristics page */
2040 		0xb2,	/* page 0xb2, thin provisioning page */
2041 		0xb6,	/* page 0xb6, zoned block device characteristics */
2042 		0xb9,	/* page 0xb9, concurrent positioning ranges */
2043 	};
2044 
2045 	for (i = 0; i < sizeof(pages); i++) {
2046 		if (pages[i] == 0xb6 && !ata_dev_is_zac(dev))
2047 			continue;
2048 		rbuf[num_pages + 4] = pages[i];
2049 		num_pages++;
2050 	}
2051 	rbuf[3] = num_pages;	/* number of supported VPD pages */
2052 
2053 	return get_unaligned_be16(&rbuf[2]) + 4;
2054 }
2055 
2056 /**
2057  *	ata_scsiop_inq_80 - Simulate INQUIRY VPD page 80, device serial number
2058  *	@dev: Target device.
2059  *	@cmd: SCSI command of interest.
2060  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2061  *
2062  *	Returns ATA device serial number.
2063  *
2064  *	LOCKING:
2065  *	spin_lock_irqsave(host lock)
2066  */
ata_scsiop_inq_80(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2067 static unsigned int ata_scsiop_inq_80(struct ata_device *dev,
2068 				      struct scsi_cmnd *cmd, u8 *rbuf)
2069 {
2070 	static const u8 hdr[] = {
2071 		0,
2072 		0x80,			/* this page code */
2073 		0,
2074 		ATA_ID_SERNO_LEN,	/* page len */
2075 	};
2076 
2077 	memcpy(rbuf, hdr, sizeof(hdr));
2078 	ata_id_string(dev->id, (unsigned char *) &rbuf[4],
2079 		      ATA_ID_SERNO, ATA_ID_SERNO_LEN);
2080 
2081 	return get_unaligned_be16(&rbuf[2]) + 4;
2082 }
2083 
2084 /**
2085  *	ata_scsiop_inq_83 - Simulate INQUIRY VPD page 83, device identity
2086  *	@dev: Target device.
2087  *	@cmd: SCSI command of interest.
2088  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2089  *
2090  *	Yields two logical unit device identification designators:
2091  *	 - vendor specific ASCII containing the ATA serial number
2092  *	 - SAT defined "t10 vendor id based" containing ASCII vendor
2093  *	   name ("ATA     "), model and serial numbers.
2094  *
2095  *	LOCKING:
2096  *	spin_lock_irqsave(host lock)
2097  */
ata_scsiop_inq_83(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2098 static unsigned int ata_scsiop_inq_83(struct ata_device *dev,
2099 				      struct scsi_cmnd *cmd, u8 *rbuf)
2100 {
2101 	const int sat_model_serial_desc_len = 68;
2102 	int num;
2103 
2104 	rbuf[1] = 0x83;			/* this page code */
2105 	num = 4;
2106 
2107 	/* piv=0, assoc=lu, code_set=ACSII, designator=vendor */
2108 	rbuf[num + 0] = 2;
2109 	rbuf[num + 3] = ATA_ID_SERNO_LEN;
2110 	num += 4;
2111 	ata_id_string(dev->id, (unsigned char *) rbuf + num,
2112 		      ATA_ID_SERNO, ATA_ID_SERNO_LEN);
2113 	num += ATA_ID_SERNO_LEN;
2114 
2115 	/* SAT defined lu model and serial numbers descriptor */
2116 	/* piv=0, assoc=lu, code_set=ACSII, designator=t10 vendor id */
2117 	rbuf[num + 0] = 2;
2118 	rbuf[num + 1] = 1;
2119 	rbuf[num + 3] = sat_model_serial_desc_len;
2120 	num += 4;
2121 	memcpy(rbuf + num, "ATA     ", 8);
2122 	num += 8;
2123 	ata_id_string(dev->id, (unsigned char *) rbuf + num, ATA_ID_PROD,
2124 		      ATA_ID_PROD_LEN);
2125 	num += ATA_ID_PROD_LEN;
2126 	ata_id_string(dev->id, (unsigned char *) rbuf + num, ATA_ID_SERNO,
2127 		      ATA_ID_SERNO_LEN);
2128 	num += ATA_ID_SERNO_LEN;
2129 
2130 	if (ata_id_has_wwn(dev->id)) {
2131 		/* SAT defined lu world wide name */
2132 		/* piv=0, assoc=lu, code_set=binary, designator=NAA */
2133 		rbuf[num + 0] = 1;
2134 		rbuf[num + 1] = 3;
2135 		rbuf[num + 3] = ATA_ID_WWN_LEN;
2136 		num += 4;
2137 		ata_id_string(dev->id, (unsigned char *) rbuf + num,
2138 			      ATA_ID_WWN, ATA_ID_WWN_LEN);
2139 		num += ATA_ID_WWN_LEN;
2140 	}
2141 	rbuf[3] = num - 4;    /* page len (assume less than 256 bytes) */
2142 
2143 	return get_unaligned_be16(&rbuf[2]) + 4;
2144 }
2145 
2146 /**
2147  *	ata_scsiop_inq_89 - Simulate INQUIRY VPD page 89, ATA info
2148  *	@dev: Target device.
2149  *	@cmd: SCSI command of interest.
2150  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2151  *
2152  *	Yields SAT-specified ATA VPD page.
2153  *
2154  *	LOCKING:
2155  *	spin_lock_irqsave(host lock)
2156  */
ata_scsiop_inq_89(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2157 static unsigned int ata_scsiop_inq_89(struct ata_device *dev,
2158 				      struct scsi_cmnd *cmd, u8 *rbuf)
2159 {
2160 	rbuf[1] = 0x89;			/* our page code */
2161 	rbuf[2] = (0x238 >> 8);		/* page size fixed at 238h */
2162 	rbuf[3] = (0x238 & 0xff);
2163 
2164 	memcpy(&rbuf[8], "linux   ", 8);
2165 	memcpy(&rbuf[16], "libata          ", 16);
2166 	memcpy(&rbuf[32], DRV_VERSION, 4);
2167 
2168 	rbuf[36] = 0x34;		/* force D2H Reg FIS (34h) */
2169 	rbuf[37] = (1 << 7);		/* bit 7 indicates Command FIS */
2170 					/* TODO: PMP? */
2171 
2172 	/* we don't store the ATA device signature, so we fake it */
2173 	rbuf[38] = ATA_DRDY;		/* really, this is Status reg */
2174 	rbuf[40] = 0x1;
2175 	rbuf[48] = 0x1;
2176 
2177 	rbuf[56] = ATA_CMD_ID_ATA;
2178 
2179 	memcpy(&rbuf[60], &dev->id[0], 512);
2180 
2181 	return get_unaligned_be16(&rbuf[2]) + 4;
2182 }
2183 
2184 /**
2185  *	ata_scsiop_inq_b0 - Simulate INQUIRY VPD page B0, Block Limits
2186  *	@dev: Target device.
2187  *	@cmd: SCSI command of interest.
2188  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2189  *
2190  *	Return data for the VPD page B0h (Block Limits).
2191  *
2192  *	LOCKING:
2193  *	spin_lock_irqsave(host lock)
2194  */
ata_scsiop_inq_b0(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2195 static unsigned int ata_scsiop_inq_b0(struct ata_device *dev,
2196 				      struct scsi_cmnd *cmd, u8 *rbuf)
2197 {
2198 	u16 min_io_sectors;
2199 
2200 	rbuf[1] = 0xb0;
2201 	rbuf[3] = 0x3c;		/* required VPD size with unmap support */
2202 
2203 	/*
2204 	 * Optimal transfer length granularity.
2205 	 *
2206 	 * This is always one physical block, but for disks with a smaller
2207 	 * logical than physical sector size we need to figure out what the
2208 	 * latter is.
2209 	 */
2210 	min_io_sectors = 1 << ata_id_log2_per_physical_sector(dev->id);
2211 	put_unaligned_be16(min_io_sectors, &rbuf[6]);
2212 
2213 	/*
2214 	 * Optimal unmap granularity.
2215 	 *
2216 	 * The ATA spec doesn't even know about a granularity or alignment
2217 	 * for the TRIM command.  We can leave away most of the unmap related
2218 	 * VPD page entries, but we have specifify a granularity to signal
2219 	 * that we support some form of unmap - in thise case via WRITE SAME
2220 	 * with the unmap bit set.
2221 	 */
2222 	if (ata_id_has_trim(dev->id)) {
2223 		u64 max_blocks = 65535 * ATA_MAX_TRIM_RNUM;
2224 
2225 		if (dev->quirks & ATA_QUIRK_MAX_TRIM_128M)
2226 			max_blocks = 128 << (20 - SECTOR_SHIFT);
2227 
2228 		put_unaligned_be64(max_blocks, &rbuf[36]);
2229 		put_unaligned_be32(1, &rbuf[28]);
2230 	}
2231 
2232 	return get_unaligned_be16(&rbuf[2]) + 4;
2233 }
2234 
2235 /**
2236  *	ata_scsiop_inq_b1 - Simulate INQUIRY VPD page B1, Block Device
2237  *			    Characteristics
2238  *	@dev: Target device.
2239  *	@cmd: SCSI command of interest.
2240  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2241  *
2242  *	Return data for the VPD page B1h (Block Device Characteristics).
2243  *
2244  *	LOCKING:
2245  *	spin_lock_irqsave(host lock)
2246  */
ata_scsiop_inq_b1(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2247 static unsigned int ata_scsiop_inq_b1(struct ata_device *dev,
2248 				      struct scsi_cmnd *cmd, u8 *rbuf)
2249 {
2250 	int form_factor = ata_id_form_factor(dev->id);
2251 	int media_rotation_rate = ata_id_rotation_rate(dev->id);
2252 	u8 zoned = ata_id_zoned_cap(dev->id);
2253 
2254 	rbuf[1] = 0xb1;
2255 	rbuf[3] = 0x3c;
2256 	rbuf[4] = media_rotation_rate >> 8;
2257 	rbuf[5] = media_rotation_rate;
2258 	rbuf[7] = form_factor;
2259 	if (zoned)
2260 		rbuf[8] = (zoned << 4);
2261 
2262 	return get_unaligned_be16(&rbuf[2]) + 4;
2263 }
2264 
2265 /**
2266  *	ata_scsiop_inq_b2 - Simulate INQUIRY VPD page B2, Logical Block
2267  *			    Provisioning
2268  *	@dev: Target device.
2269  *	@cmd: SCSI command of interest.
2270  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2271  *
2272  *	Return data for the VPD page B2h (Logical Block Provisioning).
2273  *
2274  *	LOCKING:
2275  *	spin_lock_irqsave(host lock)
2276  */
ata_scsiop_inq_b2(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2277 static unsigned int ata_scsiop_inq_b2(struct ata_device *dev,
2278 				      struct scsi_cmnd *cmd, u8 *rbuf)
2279 {
2280 	/* SCSI Thin Provisioning VPD page: SBC-3 rev 22 or later */
2281 	rbuf[1] = 0xb2;
2282 	rbuf[3] = 0x4;
2283 	rbuf[5] = 1 << 6;	/* TPWS */
2284 
2285 	return get_unaligned_be16(&rbuf[2]) + 4;
2286 }
2287 
2288 /**
2289  *	ata_scsiop_inq_b6 - Simulate INQUIRY VPD page B6, Zoned Block Device
2290  *			    Characteristics
2291  *	@dev: Target device.
2292  *	@cmd: SCSI command of interest.
2293  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2294  *
2295  *	Return data for the VPD page B2h (Zoned Block Device Characteristics).
2296  *
2297  *	LOCKING:
2298  *	spin_lock_irqsave(host lock)
2299  */
ata_scsiop_inq_b6(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2300 static unsigned int ata_scsiop_inq_b6(struct ata_device *dev,
2301 				      struct scsi_cmnd *cmd, u8 *rbuf)
2302 {
2303 	if (!ata_dev_is_zac(dev)) {
2304 		ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
2305 		return 0;
2306 	}
2307 
2308 	/*
2309 	 * zbc-r05 SCSI Zoned Block device characteristics VPD page
2310 	 */
2311 	rbuf[1] = 0xb6;
2312 	rbuf[3] = 0x3C;
2313 
2314 	/*
2315 	 * URSWRZ bit is only meaningful for host-managed ZAC drives
2316 	 */
2317 	if (dev->zac_zoned_cap & 1)
2318 		rbuf[4] |= 1;
2319 	put_unaligned_be32(dev->zac_zones_optimal_open, &rbuf[8]);
2320 	put_unaligned_be32(dev->zac_zones_optimal_nonseq, &rbuf[12]);
2321 	put_unaligned_be32(dev->zac_zones_max_open, &rbuf[16]);
2322 
2323 	return get_unaligned_be16(&rbuf[2]) + 4;
2324 }
2325 
2326 /**
2327  *	ata_scsiop_inq_b9 - Simulate INQUIRY VPD page B9, Concurrent Positioning
2328  *			    Ranges
2329  *	@dev: Target device.
2330  *	@cmd: SCSI command of interest.
2331  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2332  *
2333  *	Return data for the VPD page B9h (Concurrent Positioning Ranges).
2334  *
2335  *	LOCKING:
2336  *	spin_lock_irqsave(host lock)
2337  */
ata_scsiop_inq_b9(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2338 static unsigned int ata_scsiop_inq_b9(struct ata_device *dev,
2339 				      struct scsi_cmnd *cmd, u8 *rbuf)
2340 {
2341 	struct ata_cpr_log *cpr_log = dev->cpr_log;
2342 	u8 *desc = &rbuf[64];
2343 	int i;
2344 
2345 	if (!cpr_log) {
2346 		ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
2347 		return 0;
2348 	}
2349 
2350 	/* SCSI Concurrent Positioning Ranges VPD page: SBC-5 rev 1 or later */
2351 	rbuf[1] = 0xb9;
2352 	put_unaligned_be16(64 + (int)cpr_log->nr_cpr * 32 - 4, &rbuf[2]);
2353 
2354 	for (i = 0; i < cpr_log->nr_cpr; i++, desc += 32) {
2355 		desc[0] = cpr_log->cpr[i].num;
2356 		desc[1] = cpr_log->cpr[i].num_storage_elements;
2357 		put_unaligned_be64(cpr_log->cpr[i].start_lba, &desc[8]);
2358 		put_unaligned_be64(cpr_log->cpr[i].num_lbas, &desc[16]);
2359 	}
2360 
2361 	return get_unaligned_be16(&rbuf[2]) + 4;
2362 }
2363 
2364 /**
2365  *	ata_scsiop_inquiry - Simulate INQUIRY command
2366  *	@dev: Target device.
2367  *	@cmd: SCSI command of interest.
2368  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2369  *
2370  *	Returns data associated with an INQUIRY command output.
2371  *
2372  *	LOCKING:
2373  *	spin_lock_irqsave(host lock)
2374  */
ata_scsiop_inquiry(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2375 static unsigned int ata_scsiop_inquiry(struct ata_device *dev,
2376 				       struct scsi_cmnd *cmd, u8 *rbuf)
2377 {
2378 	const u8 *scsicmd = cmd->cmnd;
2379 
2380 	/* is CmdDt set?  */
2381 	if (scsicmd[1] & 2) {
2382 		ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
2383 		return 0;
2384 	}
2385 
2386 	/* Is EVPD clear? */
2387 	if ((scsicmd[1] & 1) == 0)
2388 		return ata_scsiop_inq_std(dev, cmd, rbuf);
2389 
2390 	switch (scsicmd[2]) {
2391 	case 0x00:
2392 		return ata_scsiop_inq_00(dev, cmd, rbuf);
2393 	case 0x80:
2394 		return ata_scsiop_inq_80(dev, cmd, rbuf);
2395 	case 0x83:
2396 		return ata_scsiop_inq_83(dev, cmd, rbuf);
2397 	case 0x89:
2398 		return ata_scsiop_inq_89(dev, cmd, rbuf);
2399 	case 0xb0:
2400 		return ata_scsiop_inq_b0(dev, cmd, rbuf);
2401 	case 0xb1:
2402 		return ata_scsiop_inq_b1(dev, cmd, rbuf);
2403 	case 0xb2:
2404 		return ata_scsiop_inq_b2(dev, cmd, rbuf);
2405 	case 0xb6:
2406 		return ata_scsiop_inq_b6(dev, cmd, rbuf);
2407 	case 0xb9:
2408 		return ata_scsiop_inq_b9(dev, cmd, rbuf);
2409 	default:
2410 		ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
2411 		return 0;
2412 	}
2413 }
2414 
2415 /**
2416  *	modecpy - Prepare response for MODE SENSE
2417  *	@dest: output buffer
2418  *	@src: data being copied
2419  *	@n: length of mode page
2420  *	@changeable: whether changeable parameters are requested
2421  *
2422  *	Generate a generic MODE SENSE page for either current or changeable
2423  *	parameters.
2424  *
2425  *	LOCKING:
2426  *	None.
2427  */
modecpy(u8 * dest,const u8 * src,int n,bool changeable)2428 static void modecpy(u8 *dest, const u8 *src, int n, bool changeable)
2429 {
2430 	if (changeable) {
2431 		memcpy(dest, src, 2);
2432 		memset(dest + 2, 0, n - 2);
2433 	} else {
2434 		memcpy(dest, src, n);
2435 	}
2436 }
2437 
2438 /**
2439  *	ata_msense_caching - Simulate MODE SENSE caching info page
2440  *	@id: device IDENTIFY data
2441  *	@buf: output buffer
2442  *	@changeable: whether changeable parameters are requested
2443  *
2444  *	Generate a caching info page, which conditionally indicates
2445  *	write caching to the SCSI layer, depending on device
2446  *	capabilities.
2447  *
2448  *	LOCKING:
2449  *	None.
2450  */
ata_msense_caching(u16 * id,u8 * buf,bool changeable)2451 static unsigned int ata_msense_caching(u16 *id, u8 *buf, bool changeable)
2452 {
2453 	modecpy(buf, def_cache_mpage, sizeof(def_cache_mpage), changeable);
2454 	if (changeable) {
2455 		buf[2] |= (1 << 2);	/* ata_mselect_caching() */
2456 	} else {
2457 		buf[2] |= (ata_id_wcache_enabled(id) << 2);	/* write cache enable */
2458 		buf[12] |= (!ata_id_rahead_enabled(id) << 5);	/* disable read ahead */
2459 	}
2460 	return sizeof(def_cache_mpage);
2461 }
2462 
2463 /*
2464  * Simulate MODE SENSE control mode page, sub-page 0.
2465  */
ata_msense_control_spg0(struct ata_device * dev,u8 * buf,bool changeable)2466 static unsigned int ata_msense_control_spg0(struct ata_device *dev, u8 *buf,
2467 					    bool changeable)
2468 {
2469 	modecpy(buf, def_control_mpage,
2470 		sizeof(def_control_mpage), changeable);
2471 	if (changeable) {
2472 		/* ata_mselect_control() */
2473 		buf[2] |= (1 << 2);
2474 	} else {
2475 		bool d_sense = (dev->flags & ATA_DFLAG_D_SENSE);
2476 
2477 		/* descriptor format sense data */
2478 		buf[2] |= (d_sense << 2);
2479 	}
2480 
2481 	return sizeof(def_control_mpage);
2482 }
2483 
2484 /*
2485  * Translate an ATA duration limit in microseconds to a SCSI duration limit
2486  * using the t2cdlunits 0xa (10ms). Since the SCSI duration limits are 2-bytes
2487  * only, take care of overflows.
2488  */
ata_xlat_cdl_limit(u8 * buf)2489 static inline u16 ata_xlat_cdl_limit(u8 *buf)
2490 {
2491 	u32 limit = get_unaligned_le32(buf);
2492 
2493 	return min_t(u32, limit / 10000, 65535);
2494 }
2495 
2496 /*
2497  * Simulate MODE SENSE control mode page, sub-pages 07h and 08h
2498  * (command duration limits T2A and T2B mode pages).
2499  */
ata_msense_control_spgt2(struct ata_device * dev,u8 * buf,u8 spg)2500 static unsigned int ata_msense_control_spgt2(struct ata_device *dev, u8 *buf,
2501 					     u8 spg)
2502 {
2503 	u8 *b, *cdl, *desc;
2504 	u32 policy;
2505 	int i;
2506 
2507 	if (!(dev->flags & ATA_DFLAG_CDL) || !dev->cdl)
2508 		return 0;
2509 
2510 	cdl = dev->cdl->desc_log_buf;
2511 
2512 	/*
2513 	 * Fill the subpage. The first four bytes of the T2A/T2B mode pages
2514 	 * are a header. The PAGE LENGTH field is the size of the page
2515 	 * excluding the header.
2516 	 */
2517 	buf[0] = CONTROL_MPAGE;
2518 	buf[1] = spg;
2519 	put_unaligned_be16(CDL_T2_SUB_MPAGE_LEN - 4, &buf[2]);
2520 	if (spg == CDL_T2A_SUB_MPAGE) {
2521 		/*
2522 		 * Read descriptors map to the T2A page:
2523 		 * set perf_vs_duration_guidleine.
2524 		 */
2525 		buf[7] = (cdl[0] & 0x03) << 4;
2526 		desc = cdl + 64;
2527 	} else {
2528 		/* Write descriptors map to the T2B page */
2529 		desc = cdl + 288;
2530 	}
2531 
2532 	/* Fill the T2 page descriptors */
2533 	b = &buf[8];
2534 	policy = get_unaligned_le32(&cdl[0]);
2535 	for (i = 0; i < 7; i++, b += 32, desc += 32) {
2536 		/* t2cdlunits: fixed to 10ms */
2537 		b[0] = 0x0a;
2538 
2539 		/* Max inactive time and its policy */
2540 		put_unaligned_be16(ata_xlat_cdl_limit(&desc[8]), &b[2]);
2541 		b[6] = ((policy >> 8) & 0x0f) << 4;
2542 
2543 		/* Max active time and its policy */
2544 		put_unaligned_be16(ata_xlat_cdl_limit(&desc[4]), &b[4]);
2545 		b[6] |= (policy >> 4) & 0x0f;
2546 
2547 		/* Command duration guideline and its policy */
2548 		put_unaligned_be16(ata_xlat_cdl_limit(&desc[16]), &b[10]);
2549 		b[14] = policy & 0x0f;
2550 	}
2551 
2552 	return CDL_T2_SUB_MPAGE_LEN;
2553 }
2554 
2555 /*
2556  * Simulate MODE SENSE control mode page, sub-page f2h
2557  * (ATA feature control mode page).
2558  */
ata_msense_control_ata_feature(struct ata_device * dev,u8 * buf)2559 static unsigned int ata_msense_control_ata_feature(struct ata_device *dev,
2560 						   u8 *buf)
2561 {
2562 	/* PS=0, SPF=1 */
2563 	buf[0] = CONTROL_MPAGE | (1 << 6);
2564 	buf[1] = ATA_FEATURE_SUB_MPAGE;
2565 
2566 	/*
2567 	 * The first four bytes of ATA Feature Control mode page are a header.
2568 	 * The PAGE LENGTH field is the size of the page excluding the header.
2569 	 */
2570 	put_unaligned_be16(ATA_FEATURE_SUB_MPAGE_LEN - 4, &buf[2]);
2571 
2572 	if (dev->flags & ATA_DFLAG_CDL_ENABLED)
2573 		buf[4] = 0x02; /* T2A and T2B pages enabled */
2574 	else
2575 		buf[4] = 0;
2576 
2577 	return ATA_FEATURE_SUB_MPAGE_LEN;
2578 }
2579 
2580 /**
2581  *	ata_msense_control - Simulate MODE SENSE control mode page
2582  *	@dev: ATA device of interest
2583  *	@buf: output buffer
2584  *	@spg: sub-page code
2585  *	@changeable: whether changeable parameters are requested
2586  *
2587  *	Generate a generic MODE SENSE control mode page.
2588  *
2589  *	LOCKING:
2590  *	None.
2591  */
ata_msense_control(struct ata_device * dev,u8 * buf,u8 spg,bool changeable)2592 static unsigned int ata_msense_control(struct ata_device *dev, u8 *buf,
2593 				       u8 spg, bool changeable)
2594 {
2595 	unsigned int n;
2596 
2597 	switch (spg) {
2598 	case 0:
2599 		return ata_msense_control_spg0(dev, buf, changeable);
2600 	case CDL_T2A_SUB_MPAGE:
2601 	case CDL_T2B_SUB_MPAGE:
2602 		return ata_msense_control_spgt2(dev, buf, spg);
2603 	case ATA_FEATURE_SUB_MPAGE:
2604 		return ata_msense_control_ata_feature(dev, buf);
2605 	case ALL_SUB_MPAGES:
2606 		n = ata_msense_control_spg0(dev, buf, changeable);
2607 		n += ata_msense_control_spgt2(dev, buf + n, CDL_T2A_SUB_MPAGE);
2608 		n += ata_msense_control_spgt2(dev, buf + n, CDL_T2B_SUB_MPAGE);
2609 		n += ata_msense_control_ata_feature(dev, buf + n);
2610 		return n;
2611 	default:
2612 		return 0;
2613 	}
2614 }
2615 
2616 /**
2617  *	ata_msense_rw_recovery - Simulate MODE SENSE r/w error recovery page
2618  *	@buf: output buffer
2619  *	@changeable: whether changeable parameters are requested
2620  *
2621  *	Generate a generic MODE SENSE r/w error recovery page.
2622  *
2623  *	LOCKING:
2624  *	None.
2625  */
ata_msense_rw_recovery(u8 * buf,bool changeable)2626 static unsigned int ata_msense_rw_recovery(u8 *buf, bool changeable)
2627 {
2628 	modecpy(buf, def_rw_recovery_mpage, sizeof(def_rw_recovery_mpage),
2629 		changeable);
2630 	return sizeof(def_rw_recovery_mpage);
2631 }
2632 
2633 /**
2634  *	ata_scsiop_mode_sense - Simulate MODE SENSE 6, 10 commands
2635  *	@dev: Target device.
2636  *	@cmd: SCSI command of interest.
2637  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2638  *
2639  *	Simulate MODE SENSE commands. Assume this is invoked for direct
2640  *	access devices (e.g. disks) only. There should be no block
2641  *	descriptor for other device types.
2642  *
2643  *	LOCKING:
2644  *	spin_lock_irqsave(host lock)
2645  */
ata_scsiop_mode_sense(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2646 static unsigned int ata_scsiop_mode_sense(struct ata_device *dev,
2647 					  struct scsi_cmnd *cmd, u8 *rbuf)
2648 {
2649 	u8 *scsicmd = cmd->cmnd, *p = rbuf;
2650 	static const u8 sat_blk_desc[] = {
2651 		0, 0, 0, 0,	/* number of blocks: sat unspecified */
2652 		0,
2653 		0, 0x2, 0x0	/* block length: 512 bytes */
2654 	};
2655 	u8 pg, spg;
2656 	unsigned int ebd, page_control, six_byte;
2657 	u8 dpofua = 0, bp = 0xff;
2658 	u16 fp;
2659 
2660 	six_byte = (scsicmd[0] == MODE_SENSE);
2661 	ebd = !(scsicmd[1] & 0x8);      /* dbd bit inverted == edb */
2662 	/*
2663 	 * LLBA bit in msense(10) ignored (compliant)
2664 	 */
2665 
2666 	page_control = scsicmd[2] >> 6;
2667 	switch (page_control) {
2668 	case 0: /* current */
2669 	case 1: /* changeable */
2670 	case 2: /* defaults */
2671 		break;  /* supported */
2672 	case 3: /* saved */
2673 		goto saving_not_supp;
2674 	default:
2675 		fp = 2;
2676 		bp = 6;
2677 		goto invalid_fld;
2678 	}
2679 
2680 	if (six_byte)
2681 		p += 4 + (ebd ? 8 : 0);
2682 	else
2683 		p += 8 + (ebd ? 8 : 0);
2684 
2685 	pg = scsicmd[2] & 0x3f;
2686 	spg = scsicmd[3];
2687 
2688 	/*
2689 	 * Supported subpages: all subpages and sub-pages 07h, 08h and f2h of
2690 	 * the control page.
2691 	 */
2692 	if (spg) {
2693 		switch (spg) {
2694 		case ALL_SUB_MPAGES:
2695 			break;
2696 		case CDL_T2A_SUB_MPAGE:
2697 		case CDL_T2B_SUB_MPAGE:
2698 		case ATA_FEATURE_SUB_MPAGE:
2699 			if (dev->flags & ATA_DFLAG_CDL && pg == CONTROL_MPAGE)
2700 				break;
2701 			fallthrough;
2702 		default:
2703 			fp = 3;
2704 			goto invalid_fld;
2705 		}
2706 	}
2707 
2708 	switch(pg) {
2709 	case RW_RECOVERY_MPAGE:
2710 		p += ata_msense_rw_recovery(p, page_control == 1);
2711 		break;
2712 
2713 	case CACHE_MPAGE:
2714 		p += ata_msense_caching(dev->id, p, page_control == 1);
2715 		break;
2716 
2717 	case CONTROL_MPAGE:
2718 		p += ata_msense_control(dev, p, spg, page_control == 1);
2719 		break;
2720 
2721 	case ALL_MPAGES:
2722 		p += ata_msense_rw_recovery(p, page_control == 1);
2723 		p += ata_msense_caching(dev->id, p, page_control == 1);
2724 		p += ata_msense_control(dev, p, spg, page_control == 1);
2725 		break;
2726 
2727 	default:		/* invalid page code */
2728 		fp = 2;
2729 		goto invalid_fld;
2730 	}
2731 
2732 	if (dev->flags & ATA_DFLAG_FUA)
2733 		dpofua = 1 << 4;
2734 
2735 	if (six_byte) {
2736 		rbuf[0] = p - rbuf - 1;
2737 		rbuf[2] |= dpofua;
2738 		if (ebd) {
2739 			rbuf[3] = sizeof(sat_blk_desc);
2740 			memcpy(rbuf + 4, sat_blk_desc, sizeof(sat_blk_desc));
2741 		}
2742 
2743 		return rbuf[0] + 1;
2744 	}
2745 
2746 	put_unaligned_be16(p - rbuf - 2, &rbuf[0]);
2747 	rbuf[3] |= dpofua;
2748 	if (ebd) {
2749 		rbuf[7] = sizeof(sat_blk_desc);
2750 		memcpy(rbuf + 8, sat_blk_desc, sizeof(sat_blk_desc));
2751 	}
2752 
2753 	return get_unaligned_be16(&rbuf[0]) + 2;
2754 
2755 invalid_fld:
2756 	ata_scsi_set_invalid_field(dev, cmd, fp, bp);
2757 	return 0;
2758 
2759 saving_not_supp:
2760 	ata_scsi_set_sense(dev, cmd, ILLEGAL_REQUEST, 0x39, 0x0);
2761 	 /* "Saving parameters not supported" */
2762 	return 0;
2763 }
2764 
2765 /**
2766  *	ata_scsiop_read_cap - Simulate READ CAPACITY[ 16] commands
2767  *	@dev: Target device.
2768  *	@cmd: SCSI command of interest.
2769  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2770  *
2771  *	Simulate READ CAPACITY commands.
2772  *
2773  *	LOCKING:
2774  *	None.
2775  */
ata_scsiop_read_cap(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2776 static unsigned int ata_scsiop_read_cap(struct ata_device *dev,
2777 					struct scsi_cmnd *cmd, u8 *rbuf)
2778 {
2779 	u8 *scsicmd = cmd->cmnd;
2780 	u64 last_lba = dev->n_sectors - 1; /* LBA of the last block */
2781 	u32 sector_size; /* physical sector size in bytes */
2782 	u8 log2_per_phys;
2783 	u16 lowest_aligned;
2784 
2785 	sector_size = ata_id_logical_sector_size(dev->id);
2786 	log2_per_phys = ata_id_log2_per_physical_sector(dev->id);
2787 	lowest_aligned = ata_id_logical_sector_offset(dev->id, log2_per_phys);
2788 
2789 	if (scsicmd[0] == READ_CAPACITY) {
2790 		if (last_lba >= 0xffffffffULL)
2791 			last_lba = 0xffffffff;
2792 
2793 		/* sector count, 32-bit */
2794 		rbuf[0] = last_lba >> (8 * 3);
2795 		rbuf[1] = last_lba >> (8 * 2);
2796 		rbuf[2] = last_lba >> (8 * 1);
2797 		rbuf[3] = last_lba;
2798 
2799 		/* sector size */
2800 		rbuf[4] = sector_size >> (8 * 3);
2801 		rbuf[5] = sector_size >> (8 * 2);
2802 		rbuf[6] = sector_size >> (8 * 1);
2803 		rbuf[7] = sector_size;
2804 
2805 		return 8;
2806 	}
2807 
2808 	/*
2809 	 * READ CAPACITY 16 command is defined as a service action
2810 	 * (SERVICE_ACTION_IN_16 command).
2811 	 */
2812 	if (scsicmd[0] != SERVICE_ACTION_IN_16 ||
2813 	    (scsicmd[1] & 0x1f) != SAI_READ_CAPACITY_16) {
2814 		ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
2815 		return 0;
2816 	}
2817 
2818 	/* sector count, 64-bit */
2819 	rbuf[0] = last_lba >> (8 * 7);
2820 	rbuf[1] = last_lba >> (8 * 6);
2821 	rbuf[2] = last_lba >> (8 * 5);
2822 	rbuf[3] = last_lba >> (8 * 4);
2823 	rbuf[4] = last_lba >> (8 * 3);
2824 	rbuf[5] = last_lba >> (8 * 2);
2825 	rbuf[6] = last_lba >> (8 * 1);
2826 	rbuf[7] = last_lba;
2827 
2828 	/* sector size */
2829 	rbuf[ 8] = sector_size >> (8 * 3);
2830 	rbuf[ 9] = sector_size >> (8 * 2);
2831 	rbuf[10] = sector_size >> (8 * 1);
2832 	rbuf[11] = sector_size;
2833 
2834 	if (ata_id_zoned_cap(dev->id) || dev->class == ATA_DEV_ZAC)
2835 		rbuf[12] = (1 << 4); /* RC_BASIS */
2836 	rbuf[13] = log2_per_phys;
2837 	rbuf[14] = (lowest_aligned >> 8) & 0x3f;
2838 	rbuf[15] = lowest_aligned;
2839 
2840 	if (ata_id_has_trim(dev->id) && !(dev->quirks & ATA_QUIRK_NOTRIM)) {
2841 		rbuf[14] |= 0x80; /* LBPME */
2842 
2843 		if (ata_id_has_zero_after_trim(dev->id) &&
2844 		    dev->quirks & ATA_QUIRK_ZERO_AFTER_TRIM) {
2845 			ata_dev_info(dev, "Enabling discard_zeroes_data\n");
2846 			rbuf[14] |= 0x40; /* LBPRZ */
2847 		}
2848 	}
2849 
2850 	return 16;
2851 }
2852 
2853 /**
2854  *	ata_scsiop_report_luns - Simulate REPORT LUNS command
2855  *	@dev: Target device.
2856  *	@cmd: SCSI command of interest.
2857  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
2858  *
2859  *	Simulate REPORT LUNS command.
2860  *
2861  *	LOCKING:
2862  *	spin_lock_irqsave(host lock)
2863  */
ata_scsiop_report_luns(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)2864 static unsigned int ata_scsiop_report_luns(struct ata_device *dev,
2865 					   struct scsi_cmnd *cmd, u8 *rbuf)
2866 {
2867 	rbuf[3] = 8;	/* just one lun, LUN 0, size 8 bytes */
2868 
2869 	return 16;
2870 }
2871 
2872 /*
2873  * ATAPI devices typically report zero for their SCSI version, and sometimes
2874  * deviate from the spec WRT response data format.  If SCSI version is
2875  * reported as zero like normal, then we make the following fixups:
2876  *   1) Fake MMC-5 version, to indicate to the Linux scsi midlayer this is a
2877  *	modern device.
2878  *   2) Ensure response data format / ATAPI information are always correct.
2879  */
atapi_fixup_inquiry(struct scsi_cmnd * cmd)2880 static void atapi_fixup_inquiry(struct scsi_cmnd *cmd)
2881 {
2882 	u8 buf[4];
2883 
2884 	sg_copy_to_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, 4);
2885 	if (buf[2] == 0) {
2886 		buf[2] = 0x5;
2887 		buf[3] = 0x32;
2888 	}
2889 	sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, 4);
2890 }
2891 
atapi_qc_complete(struct ata_queued_cmd * qc)2892 static void atapi_qc_complete(struct ata_queued_cmd *qc)
2893 {
2894 	struct scsi_cmnd *cmd = qc->scsicmd;
2895 	unsigned int err_mask = qc->err_mask;
2896 
2897 	/* handle completion from EH */
2898 	if (unlikely(err_mask || qc->flags & ATA_QCFLAG_SENSE_VALID)) {
2899 
2900 		if (!(qc->flags & ATA_QCFLAG_SENSE_VALID))
2901 			ata_gen_passthru_sense(qc);
2902 
2903 		/* SCSI EH automatically locks door if sdev->locked is
2904 		 * set.  Sometimes door lock request continues to
2905 		 * fail, for example, when no media is present.  This
2906 		 * creates a loop - SCSI EH issues door lock which
2907 		 * fails and gets invoked again to acquire sense data
2908 		 * for the failed command.
2909 		 *
2910 		 * If door lock fails, always clear sdev->locked to
2911 		 * avoid this infinite loop.
2912 		 *
2913 		 * This may happen before SCSI scan is complete.  Make
2914 		 * sure qc->dev->sdev isn't NULL before dereferencing.
2915 		 */
2916 		if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL && qc->dev->sdev)
2917 			qc->dev->sdev->locked = 0;
2918 
2919 		ata_scsi_qc_done(qc, true, SAM_STAT_CHECK_CONDITION);
2920 		return;
2921 	}
2922 
2923 	/* successful completion path */
2924 	if (cmd->cmnd[0] == INQUIRY && (cmd->cmnd[1] & 0x03) == 0)
2925 		atapi_fixup_inquiry(cmd);
2926 
2927 	ata_scsi_qc_done(qc, true, SAM_STAT_GOOD);
2928 }
2929 /**
2930  *	atapi_xlat - Initialize PACKET taskfile
2931  *	@qc: command structure to be initialized
2932  *
2933  *	LOCKING:
2934  *	spin_lock_irqsave(host lock)
2935  *
2936  *	RETURNS:
2937  *	Zero on success, non-zero on failure.
2938  */
atapi_xlat(struct ata_queued_cmd * qc)2939 static unsigned int atapi_xlat(struct ata_queued_cmd *qc)
2940 {
2941 	struct scsi_cmnd *scmd = qc->scsicmd;
2942 	struct ata_device *dev = qc->dev;
2943 	int nodata = (scmd->sc_data_direction == DMA_NONE);
2944 	int using_pio = !nodata && (dev->flags & ATA_DFLAG_PIO);
2945 	unsigned int nbytes;
2946 
2947 	memset(qc->cdb, 0, dev->cdb_len);
2948 	memcpy(qc->cdb, scmd->cmnd, scmd->cmd_len);
2949 
2950 	qc->complete_fn = atapi_qc_complete;
2951 
2952 	qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2953 	if (scmd->sc_data_direction == DMA_TO_DEVICE) {
2954 		qc->tf.flags |= ATA_TFLAG_WRITE;
2955 	}
2956 
2957 	qc->tf.command = ATA_CMD_PACKET;
2958 	ata_qc_set_pc_nbytes(qc);
2959 
2960 	/* check whether ATAPI DMA is safe */
2961 	if (!nodata && !using_pio && atapi_check_dma(qc))
2962 		using_pio = 1;
2963 
2964 	/* Some controller variants snoop this value for Packet
2965 	 * transfers to do state machine and FIFO management.  Thus we
2966 	 * want to set it properly, and for DMA where it is
2967 	 * effectively meaningless.
2968 	 */
2969 	nbytes = min(ata_qc_raw_nbytes(qc), (unsigned int)63 * 1024);
2970 
2971 	/* Most ATAPI devices which honor transfer chunk size don't
2972 	 * behave according to the spec when odd chunk size which
2973 	 * matches the transfer length is specified.  If the number of
2974 	 * bytes to transfer is 2n+1.  According to the spec, what
2975 	 * should happen is to indicate that 2n+1 is going to be
2976 	 * transferred and transfer 2n+2 bytes where the last byte is
2977 	 * padding.
2978 	 *
2979 	 * In practice, this doesn't happen.  ATAPI devices first
2980 	 * indicate and transfer 2n bytes and then indicate and
2981 	 * transfer 2 bytes where the last byte is padding.
2982 	 *
2983 	 * This inconsistency confuses several controllers which
2984 	 * perform PIO using DMA such as Intel AHCIs and sil3124/32.
2985 	 * These controllers use actual number of transferred bytes to
2986 	 * update DMA pointer and transfer of 4n+2 bytes make those
2987 	 * controller push DMA pointer by 4n+4 bytes because SATA data
2988 	 * FISes are aligned to 4 bytes.  This causes data corruption
2989 	 * and buffer overrun.
2990 	 *
2991 	 * Always setting nbytes to even number solves this problem
2992 	 * because then ATAPI devices don't have to split data at 2n
2993 	 * boundaries.
2994 	 */
2995 	if (nbytes & 0x1)
2996 		nbytes++;
2997 
2998 	qc->tf.lbam = (nbytes & 0xFF);
2999 	qc->tf.lbah = (nbytes >> 8);
3000 
3001 	if (nodata)
3002 		qc->tf.protocol = ATAPI_PROT_NODATA;
3003 	else if (using_pio)
3004 		qc->tf.protocol = ATAPI_PROT_PIO;
3005 	else {
3006 		/* DMA data xfer */
3007 		qc->tf.protocol = ATAPI_PROT_DMA;
3008 		qc->tf.feature |= ATAPI_PKT_DMA;
3009 
3010 		if ((dev->flags & ATA_DFLAG_DMADIR) &&
3011 		    (scmd->sc_data_direction != DMA_TO_DEVICE))
3012 			/* some SATA bridges need us to indicate data xfer direction */
3013 			qc->tf.feature |= ATAPI_DMADIR;
3014 	}
3015 
3016 
3017 	/* FIXME: We need to translate 0x05 READ_BLOCK_LIMITS to a MODE_SENSE
3018 	   as ATAPI tape drives don't get this right otherwise */
3019 	return 0;
3020 }
3021 
ata_find_dev(struct ata_port * ap,unsigned int devno)3022 static struct ata_device *ata_find_dev(struct ata_port *ap, unsigned int devno)
3023 {
3024 	/*
3025 	 * For the non-PMP case, ata_link_max_devices() returns 1 (SATA case),
3026 	 * or 2 (IDE master + slave case). However, the former case includes
3027 	 * libsas hosted devices which are numbered per scsi host, leading
3028 	 * to devno potentially being larger than 0 but with each struct
3029 	 * ata_device having its own struct ata_port and struct ata_link.
3030 	 * To accommodate these, ignore devno and always use device number 0.
3031 	 */
3032 	if (likely(!sata_pmp_attached(ap))) {
3033 		int link_max_devices = ata_link_max_devices(&ap->link);
3034 
3035 		if (link_max_devices == 1)
3036 			return &ap->link.device[0];
3037 
3038 		if (devno < link_max_devices)
3039 			return &ap->link.device[devno];
3040 
3041 		return NULL;
3042 	}
3043 
3044 	/*
3045 	 * For PMP-attached devices, the device number corresponds to C
3046 	 * (channel) of SCSI [H:C:I:L], indicating the port pmp link
3047 	 * for the device.
3048 	 */
3049 	if (devno < ap->nr_pmp_links)
3050 		return &ap->pmp_link[devno].device[0];
3051 
3052 	return NULL;
3053 }
3054 
__ata_scsi_find_dev(struct ata_port * ap,const struct scsi_device * scsidev)3055 static struct ata_device *__ata_scsi_find_dev(struct ata_port *ap,
3056 					      const struct scsi_device *scsidev)
3057 {
3058 	int devno;
3059 
3060 	/* skip commands not addressed to targets we simulate */
3061 	if (!sata_pmp_attached(ap)) {
3062 		if (unlikely(scsidev->channel || scsidev->lun))
3063 			return NULL;
3064 		devno = scsidev->id;
3065 	} else {
3066 		if (unlikely(scsidev->id || scsidev->lun))
3067 			return NULL;
3068 		devno = scsidev->channel;
3069 	}
3070 
3071 	return ata_find_dev(ap, devno);
3072 }
3073 
3074 /**
3075  *	ata_scsi_find_dev - lookup ata_device from scsi_cmnd
3076  *	@ap: ATA port to which the device is attached
3077  *	@scsidev: SCSI device from which we derive the ATA device
3078  *
3079  *	Given various information provided in struct scsi_cmnd,
3080  *	map that onto an ATA bus, and using that mapping
3081  *	determine which ata_device is associated with the
3082  *	SCSI command to be sent.
3083  *
3084  *	LOCKING:
3085  *	spin_lock_irqsave(host lock)
3086  *
3087  *	RETURNS:
3088  *	Associated ATA device, or %NULL if not found.
3089  */
3090 struct ata_device *
ata_scsi_find_dev(struct ata_port * ap,const struct scsi_device * scsidev)3091 ata_scsi_find_dev(struct ata_port *ap, const struct scsi_device *scsidev)
3092 {
3093 	struct ata_device *dev = __ata_scsi_find_dev(ap, scsidev);
3094 
3095 	if (!ata_adapter_is_online(ap))
3096 		return NULL;
3097 
3098 	if (unlikely(!dev || !ata_dev_enabled(dev)))
3099 		return NULL;
3100 
3101 	return dev;
3102 }
3103 
3104 /*
3105  *	ata_scsi_map_proto - Map pass-thru protocol value to taskfile value.
3106  *	@byte1: Byte 1 from pass-thru CDB.
3107  *
3108  *	RETURNS:
3109  *	ATA_PROT_UNKNOWN if mapping failed/unimplemented, protocol otherwise.
3110  */
3111 static u8
ata_scsi_map_proto(u8 byte1)3112 ata_scsi_map_proto(u8 byte1)
3113 {
3114 	switch((byte1 & 0x1e) >> 1) {
3115 	case 3:		/* Non-data */
3116 		return ATA_PROT_NODATA;
3117 
3118 	case 6:		/* DMA */
3119 	case 10:	/* UDMA Data-in */
3120 	case 11:	/* UDMA Data-Out */
3121 		return ATA_PROT_DMA;
3122 
3123 	case 4:		/* PIO Data-in */
3124 	case 5:		/* PIO Data-out */
3125 		return ATA_PROT_PIO;
3126 
3127 	case 12:	/* FPDMA */
3128 		return ATA_PROT_NCQ;
3129 
3130 	case 0:		/* Hard Reset */
3131 	case 1:		/* SRST */
3132 	case 8:		/* Device Diagnostic */
3133 	case 9:		/* Device Reset */
3134 	case 7:		/* DMA Queued */
3135 	case 15:	/* Return Response Info */
3136 	default:	/* Reserved */
3137 		break;
3138 	}
3139 
3140 	return ATA_PROT_UNKNOWN;
3141 }
3142 
3143 /**
3144  *	ata_scsi_pass_thru - convert ATA pass-thru CDB to taskfile
3145  *	@qc: command structure to be initialized
3146  *
3147  *	Handles either 12, 16, or 32-byte versions of the CDB.
3148  *
3149  *	RETURNS:
3150  *	Zero on success, non-zero on failure.
3151  */
ata_scsi_pass_thru(struct ata_queued_cmd * qc)3152 static unsigned int ata_scsi_pass_thru(struct ata_queued_cmd *qc)
3153 {
3154 	struct ata_taskfile *tf = &(qc->tf);
3155 	struct scsi_cmnd *scmd = qc->scsicmd;
3156 	struct ata_device *dev = qc->dev;
3157 	const u8 *cdb = scmd->cmnd;
3158 	u16 fp;
3159 	u16 cdb_offset = 0;
3160 
3161 	/* 7Fh variable length cmd means a ata pass-thru(32) */
3162 	if (cdb[0] == VARIABLE_LENGTH_CMD)
3163 		cdb_offset = 9;
3164 
3165 	tf->protocol = ata_scsi_map_proto(cdb[1 + cdb_offset]);
3166 	if (tf->protocol == ATA_PROT_UNKNOWN) {
3167 		fp = 1;
3168 		goto invalid_fld;
3169 	}
3170 
3171 	if ((cdb[2 + cdb_offset] & 0x3) == 0) {
3172 		/*
3173 		 * When T_LENGTH is zero (No data is transferred), dir should
3174 		 * be DMA_NONE.
3175 		 */
3176 		if (scmd->sc_data_direction != DMA_NONE) {
3177 			fp = 2 + cdb_offset;
3178 			goto invalid_fld;
3179 		}
3180 
3181 		if (ata_is_ncq(tf->protocol))
3182 			tf->protocol = ATA_PROT_NCQ_NODATA;
3183 	}
3184 
3185 	/* enable LBA */
3186 	tf->flags |= ATA_TFLAG_LBA;
3187 
3188 	/*
3189 	 * 12 and 16 byte CDBs use different offsets to
3190 	 * provide the various register values.
3191 	 */
3192 	switch (cdb[0]) {
3193 	case ATA_16:
3194 		/*
3195 		 * 16-byte CDB - may contain extended commands.
3196 		 *
3197 		 * If that is the case, copy the upper byte register values.
3198 		 */
3199 		if (cdb[1] & 0x01) {
3200 			tf->hob_feature = cdb[3];
3201 			tf->hob_nsect = cdb[5];
3202 			tf->hob_lbal = cdb[7];
3203 			tf->hob_lbam = cdb[9];
3204 			tf->hob_lbah = cdb[11];
3205 			tf->flags |= ATA_TFLAG_LBA48;
3206 		} else
3207 			tf->flags &= ~ATA_TFLAG_LBA48;
3208 
3209 		/*
3210 		 * Always copy low byte, device and command registers.
3211 		 */
3212 		tf->feature = cdb[4];
3213 		tf->nsect = cdb[6];
3214 		tf->lbal = cdb[8];
3215 		tf->lbam = cdb[10];
3216 		tf->lbah = cdb[12];
3217 		tf->device = cdb[13];
3218 		tf->command = cdb[14];
3219 		break;
3220 	case ATA_12:
3221 		/*
3222 		 * 12-byte CDB - incapable of extended commands.
3223 		 */
3224 		tf->flags &= ~ATA_TFLAG_LBA48;
3225 
3226 		tf->feature = cdb[3];
3227 		tf->nsect = cdb[4];
3228 		tf->lbal = cdb[5];
3229 		tf->lbam = cdb[6];
3230 		tf->lbah = cdb[7];
3231 		tf->device = cdb[8];
3232 		tf->command = cdb[9];
3233 		break;
3234 	default:
3235 		/*
3236 		 * 32-byte CDB - may contain extended command fields.
3237 		 *
3238 		 * If that is the case, copy the upper byte register values.
3239 		 */
3240 		if (cdb[10] & 0x01) {
3241 			tf->hob_feature = cdb[20];
3242 			tf->hob_nsect = cdb[22];
3243 			tf->hob_lbal = cdb[16];
3244 			tf->hob_lbam = cdb[15];
3245 			tf->hob_lbah = cdb[14];
3246 			tf->flags |= ATA_TFLAG_LBA48;
3247 		} else
3248 			tf->flags &= ~ATA_TFLAG_LBA48;
3249 
3250 		tf->feature = cdb[21];
3251 		tf->nsect = cdb[23];
3252 		tf->lbal = cdb[19];
3253 		tf->lbam = cdb[18];
3254 		tf->lbah = cdb[17];
3255 		tf->device = cdb[24];
3256 		tf->command = cdb[25];
3257 		tf->auxiliary = get_unaligned_be32(&cdb[28]);
3258 		break;
3259 	}
3260 
3261 	/* For NCQ commands copy the tag value */
3262 	if (ata_is_ncq(tf->protocol))
3263 		tf->nsect = qc->hw_tag << 3;
3264 
3265 	/* enforce correct master/slave bit */
3266 	tf->device = dev->devno ?
3267 		tf->device | ATA_DEV1 : tf->device & ~ATA_DEV1;
3268 
3269 	switch (tf->command) {
3270 	/* READ/WRITE LONG use a non-standard sect_size */
3271 	case ATA_CMD_READ_LONG:
3272 	case ATA_CMD_READ_LONG_ONCE:
3273 	case ATA_CMD_WRITE_LONG:
3274 	case ATA_CMD_WRITE_LONG_ONCE:
3275 		if (tf->protocol != ATA_PROT_PIO || tf->nsect != 1) {
3276 			fp = 1;
3277 			goto invalid_fld;
3278 		}
3279 		qc->sect_size = scsi_bufflen(scmd);
3280 		break;
3281 
3282 	/* commands using reported Logical Block size (e.g. 512 or 4K) */
3283 	case ATA_CMD_CFA_WRITE_NE:
3284 	case ATA_CMD_CFA_TRANS_SECT:
3285 	case ATA_CMD_CFA_WRITE_MULT_NE:
3286 	/* XXX: case ATA_CMD_CFA_WRITE_SECTORS_WITHOUT_ERASE: */
3287 	case ATA_CMD_READ:
3288 	case ATA_CMD_READ_EXT:
3289 	case ATA_CMD_READ_QUEUED:
3290 	/* XXX: case ATA_CMD_READ_QUEUED_EXT: */
3291 	case ATA_CMD_FPDMA_READ:
3292 	case ATA_CMD_READ_MULTI:
3293 	case ATA_CMD_READ_MULTI_EXT:
3294 	case ATA_CMD_PIO_READ:
3295 	case ATA_CMD_PIO_READ_EXT:
3296 	case ATA_CMD_READ_STREAM_DMA_EXT:
3297 	case ATA_CMD_READ_STREAM_EXT:
3298 	case ATA_CMD_VERIFY:
3299 	case ATA_CMD_VERIFY_EXT:
3300 	case ATA_CMD_WRITE:
3301 	case ATA_CMD_WRITE_EXT:
3302 	case ATA_CMD_WRITE_FUA_EXT:
3303 	case ATA_CMD_WRITE_QUEUED:
3304 	case ATA_CMD_WRITE_QUEUED_FUA_EXT:
3305 	case ATA_CMD_FPDMA_WRITE:
3306 	case ATA_CMD_WRITE_MULTI:
3307 	case ATA_CMD_WRITE_MULTI_EXT:
3308 	case ATA_CMD_WRITE_MULTI_FUA_EXT:
3309 	case ATA_CMD_PIO_WRITE:
3310 	case ATA_CMD_PIO_WRITE_EXT:
3311 	case ATA_CMD_WRITE_STREAM_DMA_EXT:
3312 	case ATA_CMD_WRITE_STREAM_EXT:
3313 		qc->sect_size = scmd->device->sector_size;
3314 		break;
3315 
3316 	/* Everything else uses 512 byte "sectors" */
3317 	default:
3318 		qc->sect_size = ATA_SECT_SIZE;
3319 	}
3320 
3321 	/*
3322 	 * Set flags so that all registers will be written, pass on
3323 	 * write indication (used for PIO/DMA setup), result TF is
3324 	 * copied back and we don't whine too much about its failure.
3325 	 */
3326 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3327 	if (scmd->sc_data_direction == DMA_TO_DEVICE)
3328 		tf->flags |= ATA_TFLAG_WRITE;
3329 
3330 	qc->flags |= ATA_QCFLAG_RESULT_TF | ATA_QCFLAG_QUIET;
3331 
3332 	/*
3333 	 * Set transfer length.
3334 	 *
3335 	 * TODO: find out if we need to do more here to
3336 	 *       cover scatter/gather case.
3337 	 */
3338 	ata_qc_set_pc_nbytes(qc);
3339 
3340 	/* We may not issue DMA commands if no DMA mode is set */
3341 	if (tf->protocol == ATA_PROT_DMA && !ata_dma_enabled(dev)) {
3342 		fp = 1;
3343 		goto invalid_fld;
3344 	}
3345 
3346 	/* We may not issue NCQ commands to devices not supporting NCQ */
3347 	if (ata_is_ncq(tf->protocol) && !ata_ncq_enabled(dev)) {
3348 		fp = 1;
3349 		goto invalid_fld;
3350 	}
3351 
3352 	/* sanity check for pio multi commands */
3353 	if ((cdb[1] & 0xe0) && !is_multi_taskfile(tf)) {
3354 		fp = 1;
3355 		goto invalid_fld;
3356 	}
3357 
3358 	if (is_multi_taskfile(tf)) {
3359 		unsigned int multi_count = 1 << (cdb[1] >> 5);
3360 
3361 		/* compare the passed through multi_count
3362 		 * with the cached multi_count of libata
3363 		 */
3364 		if (multi_count != dev->multi_count)
3365 			ata_dev_warn(dev, "invalid multi_count %u ignored\n",
3366 				     multi_count);
3367 	}
3368 
3369 	/*
3370 	 * Filter SET_FEATURES - XFER MODE command -- otherwise,
3371 	 * SET_FEATURES - XFER MODE must be preceded/succeeded
3372 	 * by an update to hardware-specific registers for each
3373 	 * controller (i.e. the reason for ->set_piomode(),
3374 	 * ->set_dmamode(), and ->post_set_mode() hooks).
3375 	 */
3376 	if (tf->command == ATA_CMD_SET_FEATURES &&
3377 	    tf->feature == SETFEATURES_XFER) {
3378 		fp = (cdb[0] == ATA_16) ? 4 : 3;
3379 		goto invalid_fld;
3380 	}
3381 
3382 	/*
3383 	 * Filter TPM commands by default. These provide an
3384 	 * essentially uncontrolled encrypted "back door" between
3385 	 * applications and the disk. Set libata.allow_tpm=1 if you
3386 	 * have a real reason for wanting to use them. This ensures
3387 	 * that installed software cannot easily mess stuff up without
3388 	 * user intent. DVR type users will probably ship with this enabled
3389 	 * for movie content management.
3390 	 *
3391 	 * Note that for ATA8 we can issue a DCS change and DCS freeze lock
3392 	 * for this and should do in future but that it is not sufficient as
3393 	 * DCS is an optional feature set. Thus we also do the software filter
3394 	 * so that we comply with the TC consortium stated goal that the user
3395 	 * can turn off TC features of their system.
3396 	 */
3397 	if (tf->command >= 0x5C && tf->command <= 0x5F && !libata_allow_tpm) {
3398 		fp = (cdb[0] == ATA_16) ? 14 : 9;
3399 		goto invalid_fld;
3400 	}
3401 
3402 	return 0;
3403 
3404  invalid_fld:
3405 	ata_scsi_set_invalid_field(dev, scmd, fp, 0xff);
3406 	return 1;
3407 }
3408 
3409 /**
3410  * ata_format_dsm_trim_descr() - SATL Write Same to DSM Trim
3411  * @cmd: SCSI command being translated
3412  * @trmax: Maximum number of entries that will fit in sector_size bytes.
3413  * @sector: Starting sector
3414  * @count: Total Range of request in logical sectors
3415  *
3416  * Rewrite the WRITE SAME descriptor to be a DSM TRIM little-endian formatted
3417  * descriptor.
3418  *
3419  * Upto 64 entries of the format:
3420  *   63:48 Range Length
3421  *   47:0  LBA
3422  *
3423  *  Range Length of 0 is ignored.
3424  *  LBA's should be sorted order and not overlap.
3425  *
3426  * NOTE: this is the same format as ADD LBA(S) TO NV CACHE PINNED SET
3427  *
3428  * Return: Number of bytes copied into sglist.
3429  */
ata_format_dsm_trim_descr(struct scsi_cmnd * cmd,u32 trmax,u64 sector,u32 count)3430 static size_t ata_format_dsm_trim_descr(struct scsi_cmnd *cmd, u32 trmax,
3431 					u64 sector, u32 count)
3432 {
3433 	struct scsi_device *sdp = cmd->device;
3434 	size_t len = sdp->sector_size;
3435 	size_t r;
3436 	__le64 *buf;
3437 	u32 i = 0;
3438 	unsigned long flags;
3439 
3440 	WARN_ON(len > ATA_SCSI_RBUF_SIZE);
3441 
3442 	if (len > ATA_SCSI_RBUF_SIZE)
3443 		len = ATA_SCSI_RBUF_SIZE;
3444 
3445 	spin_lock_irqsave(&ata_scsi_rbuf_lock, flags);
3446 	buf = ((void *)ata_scsi_rbuf);
3447 	memset(buf, 0, len);
3448 	while (i < trmax) {
3449 		u64 entry = sector |
3450 			((u64)(count > 0xffff ? 0xffff : count) << 48);
3451 		buf[i++] = __cpu_to_le64(entry);
3452 		if (count <= 0xffff)
3453 			break;
3454 		count -= 0xffff;
3455 		sector += 0xffff;
3456 	}
3457 	r = sg_copy_from_buffer(scsi_sglist(cmd), scsi_sg_count(cmd), buf, len);
3458 	spin_unlock_irqrestore(&ata_scsi_rbuf_lock, flags);
3459 
3460 	return r;
3461 }
3462 
3463 /**
3464  * ata_scsi_write_same_xlat() - SATL Write Same to ATA SCT Write Same
3465  * @qc: Command to be translated
3466  *
3467  * Translate a SCSI WRITE SAME command to be either a DSM TRIM command or
3468  * an SCT Write Same command.
3469  * Based on WRITE SAME has the UNMAP flag:
3470  *
3471  *   - When set translate to DSM TRIM
3472  *   - When clear translate to SCT Write Same
3473  */
ata_scsi_write_same_xlat(struct ata_queued_cmd * qc)3474 static unsigned int ata_scsi_write_same_xlat(struct ata_queued_cmd *qc)
3475 {
3476 	struct ata_taskfile *tf = &qc->tf;
3477 	struct scsi_cmnd *scmd = qc->scsicmd;
3478 	struct scsi_device *sdp = scmd->device;
3479 	size_t len = sdp->sector_size;
3480 	struct ata_device *dev = qc->dev;
3481 	const u8 *cdb = scmd->cmnd;
3482 	u64 block;
3483 	u32 n_block;
3484 	const u32 trmax = len >> 3;
3485 	u32 size;
3486 	u16 fp;
3487 	u8 bp = 0xff;
3488 	u8 unmap = cdb[1] & 0x8;
3489 
3490 	/* we may not issue DMA commands if no DMA mode is set */
3491 	if (unlikely(!ata_dma_enabled(dev)))
3492 		goto invalid_opcode;
3493 
3494 	/*
3495 	 * We only allow sending this command through the block layer,
3496 	 * as it modifies the DATA OUT buffer, which would corrupt user
3497 	 * memory for SG_IO commands.
3498 	 */
3499 	if (unlikely(blk_rq_is_passthrough(scsi_cmd_to_rq(scmd))))
3500 		goto invalid_opcode;
3501 
3502 	if (unlikely(scmd->cmd_len < 16)) {
3503 		fp = 15;
3504 		goto invalid_fld;
3505 	}
3506 	scsi_16_lba_len(cdb, &block, &n_block);
3507 
3508 	if (!unmap || (dev->quirks & ATA_QUIRK_NOTRIM) ||
3509 	    !ata_id_has_trim(dev->id)) {
3510 		fp = 1;
3511 		bp = 3;
3512 		goto invalid_fld;
3513 	}
3514 	/* If the request is too large the cmd is invalid */
3515 	if (n_block > 0xffff * trmax) {
3516 		fp = 2;
3517 		goto invalid_fld;
3518 	}
3519 
3520 	/*
3521 	 * WRITE SAME always has a sector sized buffer as payload, this
3522 	 * should never be a multiple entry S/G list.
3523 	 */
3524 	if (!scsi_sg_count(scmd))
3525 		goto invalid_param_len;
3526 
3527 	/*
3528 	 * size must match sector size in bytes
3529 	 * For DATA SET MANAGEMENT TRIM in ACS-2 nsect (aka count)
3530 	 * is defined as number of 512 byte blocks to be transferred.
3531 	 */
3532 
3533 	size = ata_format_dsm_trim_descr(scmd, trmax, block, n_block);
3534 	if (size != len)
3535 		goto invalid_param_len;
3536 
3537 	if (ata_ncq_enabled(dev) && ata_fpdma_dsm_supported(dev)) {
3538 		/* Newer devices support queued TRIM commands */
3539 		tf->protocol = ATA_PROT_NCQ;
3540 		tf->command = ATA_CMD_FPDMA_SEND;
3541 		tf->hob_nsect = ATA_SUBCMD_FPDMA_SEND_DSM & 0x1f;
3542 		tf->nsect = qc->hw_tag << 3;
3543 		tf->hob_feature = (size / 512) >> 8;
3544 		tf->feature = size / 512;
3545 
3546 		tf->auxiliary = 1;
3547 	} else {
3548 		tf->protocol = ATA_PROT_DMA;
3549 		tf->hob_feature = 0;
3550 		tf->feature = ATA_DSM_TRIM;
3551 		tf->hob_nsect = (size / 512) >> 8;
3552 		tf->nsect = size / 512;
3553 		tf->command = ATA_CMD_DSM;
3554 	}
3555 
3556 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48 |
3557 		     ATA_TFLAG_WRITE;
3558 
3559 	ata_qc_set_pc_nbytes(qc);
3560 
3561 	return 0;
3562 
3563 invalid_fld:
3564 	ata_scsi_set_invalid_field(dev, scmd, fp, bp);
3565 	return 1;
3566 invalid_param_len:
3567 	/* "Parameter list length error" */
3568 	ata_scsi_set_sense(dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3569 	return 1;
3570 invalid_opcode:
3571 	/* "Invalid command operation code" */
3572 	ata_scsi_set_sense(dev, scmd, ILLEGAL_REQUEST, 0x20, 0x0);
3573 	return 1;
3574 }
3575 
ata_scsi_report_supported_opcodes(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)3576 static unsigned int ata_scsi_report_supported_opcodes(struct ata_device *dev,
3577 						      struct scsi_cmnd *cmd,
3578 						      u8 *rbuf)
3579 {
3580 	u8 *cdb = cmd->cmnd;
3581 	u8 supported = 0, cdlp = 0, rwcdlp = 0;
3582 
3583 	if (cdb[2] != 1 && cdb[2] != 3) {
3584 		ata_dev_warn(dev, "invalid command format %d\n", cdb[2]);
3585 		ata_scsi_set_invalid_field(dev, cmd, 2, 0xff);
3586 		return 0;
3587 	}
3588 
3589 	switch (cdb[3]) {
3590 	case INQUIRY:
3591 	case MODE_SENSE:
3592 	case MODE_SENSE_10:
3593 	case READ_CAPACITY:
3594 	case SERVICE_ACTION_IN_16:
3595 	case REPORT_LUNS:
3596 	case REQUEST_SENSE:
3597 	case SYNCHRONIZE_CACHE:
3598 	case SYNCHRONIZE_CACHE_16:
3599 	case REZERO_UNIT:
3600 	case SEEK_6:
3601 	case SEEK_10:
3602 	case TEST_UNIT_READY:
3603 	case SEND_DIAGNOSTIC:
3604 	case MAINTENANCE_IN:
3605 	case READ_6:
3606 	case READ_10:
3607 	case WRITE_6:
3608 	case WRITE_10:
3609 	case ATA_12:
3610 	case ATA_16:
3611 	case VERIFY:
3612 	case VERIFY_16:
3613 	case MODE_SELECT:
3614 	case MODE_SELECT_10:
3615 	case START_STOP:
3616 		supported = 3;
3617 		break;
3618 	case READ_16:
3619 		supported = 3;
3620 		if (dev->flags & ATA_DFLAG_CDL) {
3621 			/*
3622 			 * CDL read descriptors map to the T2A page, that is,
3623 			 * rwcdlp = 0x01 and cdlp = 0x01
3624 			 */
3625 			rwcdlp = 0x01;
3626 			cdlp = 0x01 << 3;
3627 		}
3628 		break;
3629 	case WRITE_16:
3630 		supported = 3;
3631 		if (dev->flags & ATA_DFLAG_CDL) {
3632 			/*
3633 			 * CDL write descriptors map to the T2B page, that is,
3634 			 * rwcdlp = 0x01 and cdlp = 0x02
3635 			 */
3636 			rwcdlp = 0x01;
3637 			cdlp = 0x02 << 3;
3638 		}
3639 		break;
3640 	case ZBC_IN:
3641 	case ZBC_OUT:
3642 		if (ata_id_zoned_cap(dev->id) ||
3643 		    dev->class == ATA_DEV_ZAC)
3644 			supported = 3;
3645 		break;
3646 	case SECURITY_PROTOCOL_IN:
3647 	case SECURITY_PROTOCOL_OUT:
3648 		if (dev->flags & ATA_DFLAG_TRUSTED)
3649 			supported = 3;
3650 		break;
3651 	default:
3652 		break;
3653 	}
3654 
3655 	/* One command format */
3656 	rbuf[0] = rwcdlp;
3657 	rbuf[1] = cdlp | supported;
3658 
3659 	return 4;
3660 }
3661 
3662 /**
3663  *	ata_scsiop_maint_in - Simulate a subset of MAINTENANCE_IN
3664  *	@dev: Target device.
3665  *	@cmd: SCSI command of interest.
3666  *	@rbuf: Response buffer, to which simulated SCSI cmd output is sent.
3667  *
3668  *	Yields a subset to satisfy scsi_report_opcode()
3669  *
3670  *	LOCKING:
3671  *	spin_lock_irqsave(host lock)
3672  */
ata_scsiop_maint_in(struct ata_device * dev,struct scsi_cmnd * cmd,u8 * rbuf)3673 static unsigned int ata_scsiop_maint_in(struct ata_device *dev,
3674 					struct scsi_cmnd *cmd, u8 *rbuf)
3675 {
3676 	u8 *cdb = cmd->cmnd;
3677 	u8 service_action = cdb[1] & 0x1f;
3678 
3679 	switch (service_action) {
3680 	case MI_REPORT_SUPPORTED_OPERATION_CODES:
3681 		return ata_scsi_report_supported_opcodes(dev, cmd, rbuf);
3682 	default:
3683 		ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
3684 		return 0;
3685 	}
3686 }
3687 
3688 /**
3689  *	ata_scsi_report_zones_complete - convert ATA output
3690  *	@qc: command structure returning the data
3691  *
3692  *	Convert T-13 little-endian field representation into
3693  *	T-10 big-endian field representation.
3694  *	What a mess.
3695  */
ata_scsi_report_zones_complete(struct ata_queued_cmd * qc)3696 static void ata_scsi_report_zones_complete(struct ata_queued_cmd *qc)
3697 {
3698 	struct scsi_cmnd *scmd = qc->scsicmd;
3699 	struct sg_mapping_iter miter;
3700 	unsigned int bytes = 0;
3701 
3702 	lockdep_assert_held(qc->ap->lock);
3703 
3704 	sg_miter_start(&miter, scsi_sglist(scmd), scsi_sg_count(scmd),
3705 		       SG_MITER_TO_SG | SG_MITER_ATOMIC);
3706 
3707 	while (sg_miter_next(&miter)) {
3708 		unsigned int offset = 0;
3709 
3710 		if (bytes == 0) {
3711 			char *hdr;
3712 			u32 list_length;
3713 			u64 max_lba, opt_lba;
3714 			u16 same;
3715 
3716 			/* Swizzle header */
3717 			hdr = miter.addr;
3718 			list_length = get_unaligned_le32(&hdr[0]);
3719 			same = get_unaligned_le16(&hdr[4]);
3720 			max_lba = get_unaligned_le64(&hdr[8]);
3721 			opt_lba = get_unaligned_le64(&hdr[16]);
3722 			put_unaligned_be32(list_length, &hdr[0]);
3723 			hdr[4] = same & 0xf;
3724 			put_unaligned_be64(max_lba, &hdr[8]);
3725 			put_unaligned_be64(opt_lba, &hdr[16]);
3726 			offset += 64;
3727 			bytes += 64;
3728 		}
3729 		while (offset < miter.length) {
3730 			char *rec;
3731 			u8 cond, type, non_seq, reset;
3732 			u64 size, start, wp;
3733 
3734 			/* Swizzle zone descriptor */
3735 			rec = miter.addr + offset;
3736 			type = rec[0] & 0xf;
3737 			cond = (rec[1] >> 4) & 0xf;
3738 			non_seq = (rec[1] & 2);
3739 			reset = (rec[1] & 1);
3740 			size = get_unaligned_le64(&rec[8]);
3741 			start = get_unaligned_le64(&rec[16]);
3742 			wp = get_unaligned_le64(&rec[24]);
3743 			rec[0] = type;
3744 			rec[1] = (cond << 4) | non_seq | reset;
3745 			put_unaligned_be64(size, &rec[8]);
3746 			put_unaligned_be64(start, &rec[16]);
3747 			put_unaligned_be64(wp, &rec[24]);
3748 			WARN_ON(offset + 64 > miter.length);
3749 			offset += 64;
3750 			bytes += 64;
3751 		}
3752 	}
3753 	sg_miter_stop(&miter);
3754 
3755 	ata_scsi_qc_complete(qc);
3756 }
3757 
ata_scsi_zbc_in_xlat(struct ata_queued_cmd * qc)3758 static unsigned int ata_scsi_zbc_in_xlat(struct ata_queued_cmd *qc)
3759 {
3760 	struct ata_taskfile *tf = &qc->tf;
3761 	struct scsi_cmnd *scmd = qc->scsicmd;
3762 	const u8 *cdb = scmd->cmnd;
3763 	u16 sect, fp = (u16)-1;
3764 	u8 sa, options, bp = 0xff;
3765 	u64 block;
3766 	u32 n_block;
3767 
3768 	if (unlikely(scmd->cmd_len < 16)) {
3769 		ata_dev_warn(qc->dev, "invalid cdb length %d\n",
3770 			     scmd->cmd_len);
3771 		fp = 15;
3772 		goto invalid_fld;
3773 	}
3774 	scsi_16_lba_len(cdb, &block, &n_block);
3775 	if (n_block != scsi_bufflen(scmd)) {
3776 		ata_dev_warn(qc->dev, "non-matching transfer count (%d/%d)\n",
3777 			     n_block, scsi_bufflen(scmd));
3778 		goto invalid_param_len;
3779 	}
3780 	sa = cdb[1] & 0x1f;
3781 	if (sa != ZI_REPORT_ZONES) {
3782 		ata_dev_warn(qc->dev, "invalid service action %d\n", sa);
3783 		fp = 1;
3784 		goto invalid_fld;
3785 	}
3786 	/*
3787 	 * ZAC allows only for transfers in 512 byte blocks,
3788 	 * and uses a 16 bit value for the transfer count.
3789 	 */
3790 	if ((n_block / 512) > 0xffff || n_block < 512 || (n_block % 512)) {
3791 		ata_dev_warn(qc->dev, "invalid transfer count %d\n", n_block);
3792 		goto invalid_param_len;
3793 	}
3794 	sect = n_block / 512;
3795 	options = cdb[14] & 0xbf;
3796 
3797 	if (ata_ncq_enabled(qc->dev) &&
3798 	    ata_fpdma_zac_mgmt_in_supported(qc->dev)) {
3799 		tf->protocol = ATA_PROT_NCQ;
3800 		tf->command = ATA_CMD_FPDMA_RECV;
3801 		tf->hob_nsect = ATA_SUBCMD_FPDMA_RECV_ZAC_MGMT_IN & 0x1f;
3802 		tf->nsect = qc->hw_tag << 3;
3803 		tf->feature = sect & 0xff;
3804 		tf->hob_feature = (sect >> 8) & 0xff;
3805 		tf->auxiliary = ATA_SUBCMD_ZAC_MGMT_IN_REPORT_ZONES | (options << 8);
3806 	} else {
3807 		tf->command = ATA_CMD_ZAC_MGMT_IN;
3808 		tf->feature = ATA_SUBCMD_ZAC_MGMT_IN_REPORT_ZONES;
3809 		tf->protocol = ATA_PROT_DMA;
3810 		tf->hob_feature = options;
3811 		tf->hob_nsect = (sect >> 8) & 0xff;
3812 		tf->nsect = sect & 0xff;
3813 	}
3814 	tf->device = ATA_LBA;
3815 	tf->lbah = (block >> 16) & 0xff;
3816 	tf->lbam = (block >> 8) & 0xff;
3817 	tf->lbal = block & 0xff;
3818 	tf->hob_lbah = (block >> 40) & 0xff;
3819 	tf->hob_lbam = (block >> 32) & 0xff;
3820 	tf->hob_lbal = (block >> 24) & 0xff;
3821 
3822 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48;
3823 	qc->flags |= ATA_QCFLAG_RESULT_TF;
3824 
3825 	ata_qc_set_pc_nbytes(qc);
3826 
3827 	qc->complete_fn = ata_scsi_report_zones_complete;
3828 
3829 	return 0;
3830 
3831 invalid_fld:
3832 	ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
3833 	return 1;
3834 
3835 invalid_param_len:
3836 	/* "Parameter list length error" */
3837 	ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3838 	return 1;
3839 }
3840 
ata_scsi_zbc_out_xlat(struct ata_queued_cmd * qc)3841 static unsigned int ata_scsi_zbc_out_xlat(struct ata_queued_cmd *qc)
3842 {
3843 	struct ata_taskfile *tf = &qc->tf;
3844 	struct scsi_cmnd *scmd = qc->scsicmd;
3845 	struct ata_device *dev = qc->dev;
3846 	const u8 *cdb = scmd->cmnd;
3847 	u8 all, sa;
3848 	u64 block;
3849 	u32 n_block;
3850 	u16 fp = (u16)-1;
3851 
3852 	if (unlikely(scmd->cmd_len < 16)) {
3853 		fp = 15;
3854 		goto invalid_fld;
3855 	}
3856 
3857 	sa = cdb[1] & 0x1f;
3858 	if ((sa != ZO_CLOSE_ZONE) && (sa != ZO_FINISH_ZONE) &&
3859 	    (sa != ZO_OPEN_ZONE) && (sa != ZO_RESET_WRITE_POINTER)) {
3860 		fp = 1;
3861 		goto invalid_fld;
3862 	}
3863 
3864 	scsi_16_lba_len(cdb, &block, &n_block);
3865 	if (n_block) {
3866 		/*
3867 		 * ZAC MANAGEMENT OUT doesn't define any length
3868 		 */
3869 		goto invalid_param_len;
3870 	}
3871 
3872 	all = cdb[14] & 0x1;
3873 	if (all) {
3874 		/*
3875 		 * Ignore the block address (zone ID) as defined by ZBC.
3876 		 */
3877 		block = 0;
3878 	} else if (block >= dev->n_sectors) {
3879 		/*
3880 		 * Block must be a valid zone ID (a zone start LBA).
3881 		 */
3882 		fp = 2;
3883 		goto invalid_fld;
3884 	}
3885 
3886 	if (ata_ncq_enabled(qc->dev) &&
3887 	    ata_fpdma_zac_mgmt_out_supported(qc->dev)) {
3888 		tf->protocol = ATA_PROT_NCQ_NODATA;
3889 		tf->command = ATA_CMD_NCQ_NON_DATA;
3890 		tf->feature = ATA_SUBCMD_NCQ_NON_DATA_ZAC_MGMT_OUT;
3891 		tf->nsect = qc->hw_tag << 3;
3892 		tf->auxiliary = sa | ((u16)all << 8);
3893 	} else {
3894 		tf->protocol = ATA_PROT_NODATA;
3895 		tf->command = ATA_CMD_ZAC_MGMT_OUT;
3896 		tf->feature = sa;
3897 		tf->hob_feature = all;
3898 	}
3899 	tf->lbah = (block >> 16) & 0xff;
3900 	tf->lbam = (block >> 8) & 0xff;
3901 	tf->lbal = block & 0xff;
3902 	tf->hob_lbah = (block >> 40) & 0xff;
3903 	tf->hob_lbam = (block >> 32) & 0xff;
3904 	tf->hob_lbal = (block >> 24) & 0xff;
3905 	tf->device = ATA_LBA;
3906 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_LBA48;
3907 
3908 	return 0;
3909 
3910  invalid_fld:
3911 	ata_scsi_set_invalid_field(qc->dev, scmd, fp, 0xff);
3912 	return 1;
3913 invalid_param_len:
3914 	/* "Parameter list length error" */
3915 	ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
3916 	return 1;
3917 }
3918 
3919 /**
3920  *	ata_mselect_caching - Simulate MODE SELECT for caching info page
3921  *	@qc: Storage for translated ATA taskfile
3922  *	@buf: input buffer
3923  *	@len: number of valid bytes in the input buffer
3924  *	@fp: out parameter for the failed field on error
3925  *
3926  *	Prepare a taskfile to modify caching information for the device.
3927  *
3928  *	LOCKING:
3929  *	None.
3930  */
ata_mselect_caching(struct ata_queued_cmd * qc,const u8 * buf,int len,u16 * fp)3931 static int ata_mselect_caching(struct ata_queued_cmd *qc,
3932 			       const u8 *buf, int len, u16 *fp)
3933 {
3934 	struct ata_taskfile *tf = &qc->tf;
3935 	struct ata_device *dev = qc->dev;
3936 	u8 mpage[CACHE_MPAGE_LEN];
3937 	u8 wce;
3938 	int i;
3939 
3940 	/*
3941 	 * The first two bytes of def_cache_mpage are a header, so offsets
3942 	 * in mpage are off by 2 compared to buf.  Same for len.
3943 	 */
3944 
3945 	if (len != CACHE_MPAGE_LEN - 2) {
3946 		*fp = min(len, CACHE_MPAGE_LEN - 2);
3947 		return -EINVAL;
3948 	}
3949 
3950 	wce = buf[0] & (1 << 2);
3951 
3952 	/*
3953 	 * Check that read-only bits are not modified.
3954 	 */
3955 	ata_msense_caching(dev->id, mpage, false);
3956 	for (i = 0; i < CACHE_MPAGE_LEN - 2; i++) {
3957 		if (i == 0)
3958 			continue;
3959 		if (mpage[i + 2] != buf[i]) {
3960 			*fp = i;
3961 			return -EINVAL;
3962 		}
3963 	}
3964 
3965 	tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
3966 	tf->protocol = ATA_PROT_NODATA;
3967 	tf->nsect = 0;
3968 	tf->command = ATA_CMD_SET_FEATURES;
3969 	tf->feature = wce ? SETFEATURES_WC_ON : SETFEATURES_WC_OFF;
3970 	return 0;
3971 }
3972 
3973 /*
3974  * Simulate MODE SELECT control mode page, sub-page 0.
3975  */
ata_mselect_control_spg0(struct ata_queued_cmd * qc,const u8 * buf,int len,u16 * fp)3976 static int ata_mselect_control_spg0(struct ata_queued_cmd *qc,
3977 				    const u8 *buf, int len, u16 *fp)
3978 {
3979 	struct ata_device *dev = qc->dev;
3980 	u8 mpage[CONTROL_MPAGE_LEN];
3981 	u8 d_sense;
3982 	int i;
3983 
3984 	/*
3985 	 * The first two bytes of def_control_mpage are a header, so offsets
3986 	 * in mpage are off by 2 compared to buf.  Same for len.
3987 	 */
3988 
3989 	if (len != CONTROL_MPAGE_LEN - 2) {
3990 		*fp = min(len, CONTROL_MPAGE_LEN - 2);
3991 		return -EINVAL;
3992 	}
3993 
3994 	d_sense = buf[0] & (1 << 2);
3995 
3996 	/*
3997 	 * Check that read-only bits are not modified.
3998 	 */
3999 	ata_msense_control_spg0(dev, mpage, false);
4000 	for (i = 0; i < CONTROL_MPAGE_LEN - 2; i++) {
4001 		if (i == 0)
4002 			continue;
4003 		if (mpage[2 + i] != buf[i]) {
4004 			*fp = i;
4005 			return -EINVAL;
4006 		}
4007 	}
4008 	if (d_sense & (1 << 2))
4009 		dev->flags |= ATA_DFLAG_D_SENSE;
4010 	else
4011 		dev->flags &= ~ATA_DFLAG_D_SENSE;
4012 	return 0;
4013 }
4014 
4015 /*
4016  * Translate MODE SELECT control mode page, sub-page f2h (ATA feature mode
4017  * page) into a SET FEATURES command.
4018  */
ata_mselect_control_ata_feature(struct ata_queued_cmd * qc,const u8 * buf,int len,u16 * fp)4019 static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc,
4020 					   const u8 *buf, int len, u16 *fp)
4021 {
4022 	struct ata_device *dev = qc->dev;
4023 	struct ata_taskfile *tf = &qc->tf;
4024 	u8 cdl_action;
4025 
4026 	/*
4027 	 * The first four bytes of ATA Feature Control mode page are a header,
4028 	 * so offsets in mpage are off by 4 compared to buf.  Same for len.
4029 	 */
4030 	if (len != ATA_FEATURE_SUB_MPAGE_LEN - 4) {
4031 		*fp = min(len, ATA_FEATURE_SUB_MPAGE_LEN - 4);
4032 		return -EINVAL;
4033 	}
4034 
4035 	/* Check cdl_ctrl */
4036 	switch (buf[0] & 0x03) {
4037 	case 0:
4038 		/* Disable CDL */
4039 		ata_dev_dbg(dev, "Disabling CDL\n");
4040 		cdl_action = 0;
4041 		dev->flags &= ~ATA_DFLAG_CDL_ENABLED;
4042 		break;
4043 	case 0x02:
4044 		/*
4045 		 * Enable CDL. Since CDL is mutually exclusive with NCQ
4046 		 * priority, allow this only if NCQ priority is disabled.
4047 		 */
4048 		if (dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLED) {
4049 			ata_dev_err(dev,
4050 				"NCQ priority must be disabled to enable CDL\n");
4051 			return -EINVAL;
4052 		}
4053 		ata_dev_dbg(dev, "Enabling CDL\n");
4054 		cdl_action = 1;
4055 		dev->flags |= ATA_DFLAG_CDL_ENABLED;
4056 		break;
4057 	default:
4058 		*fp = 0;
4059 		return -EINVAL;
4060 	}
4061 
4062 	tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
4063 	tf->protocol = ATA_PROT_NODATA;
4064 	tf->command = ATA_CMD_SET_FEATURES;
4065 	tf->feature = SETFEATURES_CDL;
4066 	tf->nsect = cdl_action;
4067 
4068 	return 1;
4069 }
4070 
4071 /**
4072  *	ata_mselect_control - Simulate MODE SELECT for control page
4073  *	@qc: Storage for translated ATA taskfile
4074  *	@spg: target sub-page of the control page
4075  *	@buf: input buffer
4076  *	@len: number of valid bytes in the input buffer
4077  *	@fp: out parameter for the failed field on error
4078  *
4079  *	Prepare a taskfile to modify caching information for the device.
4080  *
4081  *	LOCKING:
4082  *	None.
4083  */
ata_mselect_control(struct ata_queued_cmd * qc,u8 spg,const u8 * buf,int len,u16 * fp)4084 static int ata_mselect_control(struct ata_queued_cmd *qc, u8 spg,
4085 			       const u8 *buf, int len, u16 *fp)
4086 {
4087 	switch (spg) {
4088 	case 0:
4089 		return ata_mselect_control_spg0(qc, buf, len, fp);
4090 	case ATA_FEATURE_SUB_MPAGE:
4091 		return ata_mselect_control_ata_feature(qc, buf, len, fp);
4092 	default:
4093 		return -EINVAL;
4094 	}
4095 }
4096 
4097 /**
4098  *	ata_scsi_mode_select_xlat - Simulate MODE SELECT 6, 10 commands
4099  *	@qc: Storage for translated ATA taskfile
4100  *
4101  *	Converts a MODE SELECT command to an ATA SET FEATURES taskfile.
4102  *	Assume this is invoked for direct access devices (e.g. disks) only.
4103  *	There should be no block descriptor for other device types.
4104  *
4105  *	LOCKING:
4106  *	spin_lock_irqsave(host lock)
4107  */
ata_scsi_mode_select_xlat(struct ata_queued_cmd * qc)4108 static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc)
4109 {
4110 	struct scsi_cmnd *scmd = qc->scsicmd;
4111 	const u8 *cdb = scmd->cmnd;
4112 	u8 pg, spg;
4113 	unsigned six_byte, pg_len, hdr_len, bd_len;
4114 	int len, ret;
4115 	u16 fp = (u16)-1;
4116 	u8 bp = 0xff;
4117 	u8 buffer[64];
4118 	const u8 *p = buffer;
4119 
4120 	six_byte = (cdb[0] == MODE_SELECT);
4121 	if (six_byte) {
4122 		if (scmd->cmd_len < 5) {
4123 			fp = 4;
4124 			goto invalid_fld;
4125 		}
4126 
4127 		len = cdb[4];
4128 		hdr_len = 4;
4129 	} else {
4130 		if (scmd->cmd_len < 9) {
4131 			fp = 8;
4132 			goto invalid_fld;
4133 		}
4134 
4135 		len = get_unaligned_be16(&cdb[7]);
4136 		hdr_len = 8;
4137 	}
4138 
4139 	/* We only support PF=1, SP=0.  */
4140 	if ((cdb[1] & 0x11) != 0x10) {
4141 		fp = 1;
4142 		bp = (cdb[1] & 0x01) ? 1 : 5;
4143 		goto invalid_fld;
4144 	}
4145 
4146 	/* Test early for possible overrun.  */
4147 	if (!scsi_sg_count(scmd) || scsi_sglist(scmd)->length < len)
4148 		goto invalid_param_len;
4149 
4150 	/* Move past header and block descriptors.  */
4151 	if (len < hdr_len)
4152 		goto invalid_param_len;
4153 
4154 	if (!sg_copy_to_buffer(scsi_sglist(scmd), scsi_sg_count(scmd),
4155 			       buffer, sizeof(buffer)))
4156 		goto invalid_param_len;
4157 
4158 	if (six_byte)
4159 		bd_len = p[3];
4160 	else
4161 		bd_len = get_unaligned_be16(&p[6]);
4162 
4163 	len -= hdr_len;
4164 	p += hdr_len;
4165 	if (len < bd_len)
4166 		goto invalid_param_len;
4167 	if (bd_len != 0 && bd_len != 8) {
4168 		fp = (six_byte) ? 3 : 6;
4169 		fp += bd_len + hdr_len;
4170 		goto invalid_param;
4171 	}
4172 
4173 	len -= bd_len;
4174 	p += bd_len;
4175 	if (len == 0)
4176 		goto skip;
4177 
4178 	/* Parse both possible formats for the mode page headers.  */
4179 	pg = p[0] & 0x3f;
4180 	if (p[0] & 0x40) {
4181 		if (len < 4)
4182 			goto invalid_param_len;
4183 
4184 		spg = p[1];
4185 		pg_len = get_unaligned_be16(&p[2]);
4186 		p += 4;
4187 		len -= 4;
4188 	} else {
4189 		if (len < 2)
4190 			goto invalid_param_len;
4191 
4192 		spg = 0;
4193 		pg_len = p[1];
4194 		p += 2;
4195 		len -= 2;
4196 	}
4197 
4198 	/*
4199 	 * Supported subpages: all subpages and ATA feature sub-page f2h of
4200 	 * the control page.
4201 	 */
4202 	if (spg) {
4203 		switch (spg) {
4204 		case ALL_SUB_MPAGES:
4205 			/* All subpages is not supported for the control page */
4206 			if (pg == CONTROL_MPAGE) {
4207 				fp = (p[0] & 0x40) ? 1 : 0;
4208 				fp += hdr_len + bd_len;
4209 				goto invalid_param;
4210 			}
4211 			break;
4212 		case ATA_FEATURE_SUB_MPAGE:
4213 			if (qc->dev->flags & ATA_DFLAG_CDL &&
4214 			    pg == CONTROL_MPAGE)
4215 				break;
4216 			fallthrough;
4217 		default:
4218 			fp = (p[0] & 0x40) ? 1 : 0;
4219 			fp += hdr_len + bd_len;
4220 			goto invalid_param;
4221 		}
4222 	}
4223 	if (pg_len > len)
4224 		goto invalid_param_len;
4225 
4226 	switch (pg) {
4227 	case CACHE_MPAGE:
4228 		if (ata_mselect_caching(qc, p, pg_len, &fp) < 0) {
4229 			fp += hdr_len + bd_len;
4230 			goto invalid_param;
4231 		}
4232 		break;
4233 	case CONTROL_MPAGE:
4234 		ret = ata_mselect_control(qc, spg, p, pg_len, &fp);
4235 		if (ret < 0) {
4236 			fp += hdr_len + bd_len;
4237 			goto invalid_param;
4238 		}
4239 		if (!ret)
4240 			goto skip; /* No ATA command to send */
4241 		break;
4242 	default:
4243 		/* Invalid page code */
4244 		fp = bd_len + hdr_len;
4245 		goto invalid_param;
4246 	}
4247 
4248 	/*
4249 	 * Only one page has changeable data, so we only support setting one
4250 	 * page at a time.
4251 	 */
4252 	if (len > pg_len)
4253 		goto invalid_param;
4254 
4255 	return 0;
4256 
4257  invalid_fld:
4258 	ata_scsi_set_invalid_field(qc->dev, scmd, fp, bp);
4259 	return 1;
4260 
4261  invalid_param:
4262 	ata_scsi_set_invalid_parameter(qc->dev, scmd, fp);
4263 	return 1;
4264 
4265  invalid_param_len:
4266 	/* "Parameter list length error" */
4267 	ata_scsi_set_sense(qc->dev, scmd, ILLEGAL_REQUEST, 0x1a, 0x0);
4268 	return 1;
4269 
4270  skip:
4271 	scmd->result = SAM_STAT_GOOD;
4272 	return 1;
4273 }
4274 
ata_scsi_trusted_op(u32 len,bool send,bool dma)4275 static u8 ata_scsi_trusted_op(u32 len, bool send, bool dma)
4276 {
4277 	if (len == 0)
4278 		return ATA_CMD_TRUSTED_NONDATA;
4279 	else if (send)
4280 		return dma ? ATA_CMD_TRUSTED_SND_DMA : ATA_CMD_TRUSTED_SND;
4281 	else
4282 		return dma ? ATA_CMD_TRUSTED_RCV_DMA : ATA_CMD_TRUSTED_RCV;
4283 }
4284 
ata_scsi_security_inout_xlat(struct ata_queued_cmd * qc)4285 static unsigned int ata_scsi_security_inout_xlat(struct ata_queued_cmd *qc)
4286 {
4287 	struct scsi_cmnd *scmd = qc->scsicmd;
4288 	const u8 *cdb = scmd->cmnd;
4289 	struct ata_taskfile *tf = &qc->tf;
4290 	u8 secp = cdb[1];
4291 	bool send = (cdb[0] == SECURITY_PROTOCOL_OUT);
4292 	u16 spsp = get_unaligned_be16(&cdb[2]);
4293 	u32 len = get_unaligned_be32(&cdb[6]);
4294 	bool dma = !(qc->dev->flags & ATA_DFLAG_PIO);
4295 
4296 	/*
4297 	 * We don't support the ATA "security" protocol.
4298 	 */
4299 	if (secp == 0xef) {
4300 		ata_scsi_set_invalid_field(qc->dev, scmd, 1, 0);
4301 		return 1;
4302 	}
4303 
4304 	if (cdb[4] & 7) { /* INC_512 */
4305 		if (len > 0xffff) {
4306 			ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0);
4307 			return 1;
4308 		}
4309 	} else {
4310 		if (len > 0x01fffe00) {
4311 			ata_scsi_set_invalid_field(qc->dev, scmd, 6, 0);
4312 			return 1;
4313 		}
4314 
4315 		/* convert to the sector-based ATA addressing */
4316 		len = (len + 511) / 512;
4317 	}
4318 
4319 	tf->protocol = dma ? ATA_PROT_DMA : ATA_PROT_PIO;
4320 	tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR | ATA_TFLAG_LBA;
4321 	if (send)
4322 		tf->flags |= ATA_TFLAG_WRITE;
4323 	tf->command = ata_scsi_trusted_op(len, send, dma);
4324 	tf->feature = secp;
4325 	tf->lbam = spsp & 0xff;
4326 	tf->lbah = spsp >> 8;
4327 
4328 	if (len) {
4329 		tf->nsect = len & 0xff;
4330 		tf->lbal = len >> 8;
4331 	} else {
4332 		if (!send)
4333 			tf->lbah = (1 << 7);
4334 	}
4335 
4336 	ata_qc_set_pc_nbytes(qc);
4337 	return 0;
4338 }
4339 
4340 /**
4341  *	ata_scsi_var_len_cdb_xlat - SATL variable length CDB to Handler
4342  *	@qc: Command to be translated
4343  *
4344  *	Translate a SCSI variable length CDB to specified commands.
4345  *	It checks a service action value in CDB to call corresponding handler.
4346  *
4347  *	RETURNS:
4348  *	Zero on success, non-zero on failure
4349  *
4350  */
ata_scsi_var_len_cdb_xlat(struct ata_queued_cmd * qc)4351 static unsigned int ata_scsi_var_len_cdb_xlat(struct ata_queued_cmd *qc)
4352 {
4353 	struct scsi_cmnd *scmd = qc->scsicmd;
4354 	const u8 *cdb = scmd->cmnd;
4355 	const u16 sa = get_unaligned_be16(&cdb[8]);
4356 
4357 	/*
4358 	 * if service action represents a ata pass-thru(32) command,
4359 	 * then pass it to ata_scsi_pass_thru handler.
4360 	 */
4361 	if (sa == ATA_32)
4362 		return ata_scsi_pass_thru(qc);
4363 
4364 	/* unsupported service action */
4365 	return 1;
4366 }
4367 
4368 /**
4369  *	ata_get_xlat_func - check if SCSI to ATA translation is possible
4370  *	@dev: ATA device
4371  *	@cmd: SCSI command opcode to consider
4372  *
4373  *	Look up the SCSI command given, and determine whether the
4374  *	SCSI command is to be translated or simulated.
4375  *
4376  *	RETURNS:
4377  *	Pointer to translation function if possible, %NULL if not.
4378  */
4379 
ata_get_xlat_func(struct ata_device * dev,u8 cmd)4380 static inline ata_xlat_func_t ata_get_xlat_func(struct ata_device *dev, u8 cmd)
4381 {
4382 	switch (cmd) {
4383 	case READ_6:
4384 	case READ_10:
4385 	case READ_16:
4386 
4387 	case WRITE_6:
4388 	case WRITE_10:
4389 	case WRITE_16:
4390 		return ata_scsi_rw_xlat;
4391 
4392 	case WRITE_SAME_16:
4393 		return ata_scsi_write_same_xlat;
4394 
4395 	case SYNCHRONIZE_CACHE:
4396 	case SYNCHRONIZE_CACHE_16:
4397 		if (ata_try_flush_cache(dev))
4398 			return ata_scsi_flush_xlat;
4399 		break;
4400 
4401 	case VERIFY:
4402 	case VERIFY_16:
4403 		return ata_scsi_verify_xlat;
4404 
4405 	case ATA_12:
4406 	case ATA_16:
4407 		return ata_scsi_pass_thru;
4408 
4409 	case VARIABLE_LENGTH_CMD:
4410 		return ata_scsi_var_len_cdb_xlat;
4411 
4412 	case MODE_SELECT:
4413 	case MODE_SELECT_10:
4414 		return ata_scsi_mode_select_xlat;
4415 
4416 	case ZBC_IN:
4417 		return ata_scsi_zbc_in_xlat;
4418 
4419 	case ZBC_OUT:
4420 		return ata_scsi_zbc_out_xlat;
4421 
4422 	case SECURITY_PROTOCOL_IN:
4423 	case SECURITY_PROTOCOL_OUT:
4424 		if (!(dev->flags & ATA_DFLAG_TRUSTED))
4425 			break;
4426 		return ata_scsi_security_inout_xlat;
4427 
4428 	case START_STOP:
4429 		return ata_scsi_start_stop_xlat;
4430 	}
4431 
4432 	return NULL;
4433 }
4434 
4435 /**
4436  *	ata_scsi_simulate - simulate SCSI command on ATA device
4437  *	@dev: the target device
4438  *	@cmd: SCSI command being sent to device.
4439  *
4440  *	Interprets and directly executes a select list of SCSI commands
4441  *	that can be handled internally.
4442  *
4443  *	LOCKING:
4444  *	spin_lock_irqsave(host lock)
4445  */
ata_scsi_simulate(struct ata_device * dev,struct scsi_cmnd * cmd)4446 static void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd)
4447 {
4448 	const u8 *scsicmd = cmd->cmnd;
4449 	u8 tmp8;
4450 
4451 	switch (scsicmd[0]) {
4452 	case INQUIRY:
4453 		ata_scsi_rbuf_fill(dev, cmd, ata_scsiop_inquiry);
4454 		break;
4455 
4456 	case MODE_SENSE:
4457 	case MODE_SENSE_10:
4458 		ata_scsi_rbuf_fill(dev, cmd, ata_scsiop_mode_sense);
4459 		break;
4460 
4461 	case READ_CAPACITY:
4462 	case SERVICE_ACTION_IN_16:
4463 		ata_scsi_rbuf_fill(dev, cmd, ata_scsiop_read_cap);
4464 		break;
4465 
4466 	case REPORT_LUNS:
4467 		ata_scsi_rbuf_fill(dev, cmd, ata_scsiop_report_luns);
4468 		break;
4469 
4470 	case REQUEST_SENSE:
4471 		ata_scsi_set_sense(dev, cmd, 0, 0, 0);
4472 		break;
4473 
4474 	/* if we reach this, then writeback caching is disabled,
4475 	 * turning this into a no-op.
4476 	 */
4477 	case SYNCHRONIZE_CACHE:
4478 	case SYNCHRONIZE_CACHE_16:
4479 		fallthrough;
4480 
4481 	/* no-op's, complete with success */
4482 	case REZERO_UNIT:
4483 	case SEEK_6:
4484 	case SEEK_10:
4485 	case TEST_UNIT_READY:
4486 		break;
4487 
4488 	case SEND_DIAGNOSTIC:
4489 		tmp8 = scsicmd[1] & ~(1 << 3);
4490 		if (tmp8 != 0x4 || scsicmd[3] || scsicmd[4])
4491 			ata_scsi_set_invalid_field(dev, cmd, 1, 0xff);
4492 		break;
4493 
4494 	case MAINTENANCE_IN:
4495 		ata_scsi_rbuf_fill(dev, cmd, ata_scsiop_maint_in);
4496 		break;
4497 
4498 	/* all other commands */
4499 	default:
4500 		ata_scsi_set_sense(dev, cmd, ILLEGAL_REQUEST, 0x20, 0x0);
4501 		/* "Invalid command operation code" */
4502 		break;
4503 	}
4504 
4505 	scsi_done(cmd);
4506 }
4507 
__ata_scsi_queuecmd(struct scsi_cmnd * scmd,struct ata_device * dev)4508 enum scsi_qc_status __ata_scsi_queuecmd(struct scsi_cmnd *scmd,
4509 					struct ata_device *dev)
4510 {
4511 	struct ata_port *ap = dev->link->ap;
4512 	u8 scsi_op = scmd->cmnd[0];
4513 	ata_xlat_func_t xlat_func;
4514 
4515 	/*
4516 	 * scsi_queue_rq() will defer commands if scsi_host_in_recovery().
4517 	 * However, this check is done without holding the ap->lock (a libata
4518 	 * specific lock), so we can have received an error irq since then,
4519 	 * therefore we must check if EH is pending or running, while holding
4520 	 * ap->lock.
4521 	 */
4522 	if (ata_port_eh_scheduled(ap))
4523 		return SCSI_MLQUEUE_DEVICE_BUSY;
4524 
4525 	if (unlikely(!scmd->cmd_len))
4526 		goto bad_cdb_len;
4527 
4528 	if (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ZAC) {
4529 		if (unlikely(scmd->cmd_len > dev->cdb_len))
4530 			goto bad_cdb_len;
4531 
4532 		xlat_func = ata_get_xlat_func(dev, scsi_op);
4533 	} else if (likely((scsi_op != ATA_16) || !atapi_passthru16)) {
4534 		/* relay SCSI command to ATAPI device */
4535 		int len = COMMAND_SIZE(scsi_op);
4536 
4537 		if (unlikely(len > scmd->cmd_len ||
4538 			     len > dev->cdb_len ||
4539 			     scmd->cmd_len > ATAPI_CDB_LEN))
4540 			goto bad_cdb_len;
4541 
4542 		xlat_func = atapi_xlat;
4543 	} else {
4544 		/* ATA_16 passthru, treat as an ATA command */
4545 		if (unlikely(scmd->cmd_len > 16))
4546 			goto bad_cdb_len;
4547 
4548 		xlat_func = ata_get_xlat_func(dev, scsi_op);
4549 	}
4550 
4551 	if (xlat_func)
4552 		return ata_scsi_translate(dev, scmd, xlat_func);
4553 
4554 	ata_scsi_simulate(dev, scmd);
4555 
4556 	return 0;
4557 
4558  bad_cdb_len:
4559 	scmd->result = DID_ERROR << 16;
4560 	scsi_done(scmd);
4561 	return 0;
4562 }
4563 
4564 /**
4565  *	ata_scsi_queuecmd - Issue SCSI cdb to libata-managed device
4566  *	@shost: SCSI host of command to be sent
4567  *	@cmd: SCSI command to be sent
4568  *
4569  *	In some cases, this function translates SCSI commands into
4570  *	ATA taskfiles, and queues the taskfiles to be sent to
4571  *	hardware.  In other cases, this function simulates a
4572  *	SCSI device by evaluating and responding to certain
4573  *	SCSI commands.  This creates the overall effect of
4574  *	ATA and ATAPI devices appearing as SCSI devices.
4575  *
4576  *	LOCKING:
4577  *	ATA host lock
4578  *
4579  *	RETURNS:
4580  *	Return value from __ata_scsi_queuecmd() if @cmd can be queued,
4581  *	0 otherwise.
4582  */
ata_scsi_queuecmd(struct Scsi_Host * shost,struct scsi_cmnd * cmd)4583 enum scsi_qc_status ata_scsi_queuecmd(struct Scsi_Host *shost,
4584 				      struct scsi_cmnd *cmd)
4585 {
4586 	struct ata_port *ap;
4587 	struct ata_device *dev;
4588 	struct scsi_device *scsidev = cmd->device;
4589 	enum scsi_qc_status rc = 0;
4590 	unsigned long irq_flags;
4591 
4592 	ap = ata_shost_to_port(shost);
4593 
4594 	spin_lock_irqsave(ap->lock, irq_flags);
4595 
4596 	dev = ata_scsi_find_dev(ap, scsidev);
4597 	if (likely(dev))
4598 		rc = __ata_scsi_queuecmd(cmd, dev);
4599 	else {
4600 		cmd->result = (DID_BAD_TARGET << 16);
4601 		scsi_done(cmd);
4602 	}
4603 
4604 	spin_unlock_irqrestore(ap->lock, irq_flags);
4605 
4606 	return rc;
4607 }
4608 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
4609 
ata_scsi_add_hosts(struct ata_host * host,const struct scsi_host_template * sht)4610 int ata_scsi_add_hosts(struct ata_host *host, const struct scsi_host_template *sht)
4611 {
4612 	int i, rc;
4613 
4614 	for (i = 0; i < host->n_ports; i++) {
4615 		struct ata_port *ap = host->ports[i];
4616 		struct Scsi_Host *shost;
4617 
4618 		rc = -ENOMEM;
4619 		shost = scsi_host_alloc(sht, sizeof(struct ata_port *));
4620 		if (!shost)
4621 			goto err_alloc;
4622 
4623 		shost->eh_noresume = 1;
4624 		*(struct ata_port **)&shost->hostdata[0] = ap;
4625 		ap->scsi_host = shost;
4626 
4627 		shost->transportt = &ata_scsi_transportt;
4628 		shost->unique_id = ap->print_id;
4629 		shost->max_id = 16;
4630 		shost->max_lun = 1;
4631 		shost->max_channel = 1;
4632 		shost->max_cmd_len = 32;
4633 
4634 		/* Schedule policy is determined by ->qc_defer()
4635 		 * callback and it needs to see every deferred qc.
4636 		 * Set host_blocked to 1 to prevent SCSI midlayer from
4637 		 * automatically deferring requests.
4638 		 */
4639 		shost->max_host_blocked = 1;
4640 
4641 		rc = scsi_add_host_with_dma(shost, &ap->tdev, ap->host->dev);
4642 		if (rc)
4643 			goto err_alloc;
4644 	}
4645 
4646 	return 0;
4647 
4648  err_alloc:
4649 	while (--i >= 0) {
4650 		struct Scsi_Host *shost = host->ports[i]->scsi_host;
4651 
4652 		/* scsi_host_put() is in ata_devres_release() */
4653 		scsi_remove_host(shost);
4654 	}
4655 	return rc;
4656 }
4657 
4658 #ifdef CONFIG_OF
ata_scsi_assign_ofnode(struct ata_device * dev,struct ata_port * ap)4659 static void ata_scsi_assign_ofnode(struct ata_device *dev, struct ata_port *ap)
4660 {
4661 	struct scsi_device *sdev = dev->sdev;
4662 	struct device *d = ap->host->dev;
4663 	struct device_node *np = d->of_node;
4664 	struct device_node *child;
4665 
4666 	for_each_available_child_of_node(np, child) {
4667 		int ret;
4668 		u32 val;
4669 
4670 		ret = of_property_read_u32(child, "reg", &val);
4671 		if (ret)
4672 			continue;
4673 		if (val == dev->devno) {
4674 			dev_dbg(d, "found matching device node\n");
4675 			sdev->sdev_gendev.of_node = child;
4676 			return;
4677 		}
4678 	}
4679 }
4680 #else
ata_scsi_assign_ofnode(struct ata_device * dev,struct ata_port * ap)4681 static void ata_scsi_assign_ofnode(struct ata_device *dev, struct ata_port *ap)
4682 {
4683 }
4684 #endif
4685 
ata_scsi_scan_host(struct ata_port * ap,int sync)4686 void ata_scsi_scan_host(struct ata_port *ap, int sync)
4687 {
4688 	int tries = 5;
4689 	struct ata_device *last_failed_dev = NULL;
4690 	struct ata_link *link;
4691 	struct ata_device *dev;
4692 
4693  repeat:
4694 	ata_for_each_link(link, ap, EDGE) {
4695 		ata_for_each_dev(dev, link, ENABLED) {
4696 			struct scsi_device *sdev;
4697 			int channel = 0, id = 0;
4698 
4699 			if (dev->sdev)
4700 				continue;
4701 
4702 			if (ata_is_host_link(link))
4703 				id = dev->devno;
4704 			else
4705 				channel = link->pmp;
4706 
4707 			sdev = __scsi_add_device(ap->scsi_host, channel, id, 0,
4708 						 NULL);
4709 			if (!IS_ERR(sdev)) {
4710 				dev->sdev = sdev;
4711 				ata_scsi_assign_ofnode(dev, ap);
4712 				scsi_device_put(sdev);
4713 			} else {
4714 				dev->sdev = NULL;
4715 			}
4716 		}
4717 	}
4718 
4719 	/* If we scanned while EH was in progress or allocation
4720 	 * failure occurred, scan would have failed silently.  Check
4721 	 * whether all devices are attached.
4722 	 */
4723 	ata_for_each_link(link, ap, EDGE) {
4724 		ata_for_each_dev(dev, link, ENABLED) {
4725 			if (!dev->sdev)
4726 				goto exit_loop;
4727 		}
4728 	}
4729  exit_loop:
4730 	if (!link)
4731 		return;
4732 
4733 	/* we're missing some SCSI devices */
4734 	if (sync) {
4735 		/* If caller requested synchrnous scan && we've made
4736 		 * any progress, sleep briefly and repeat.
4737 		 */
4738 		if (dev != last_failed_dev) {
4739 			msleep(100);
4740 			last_failed_dev = dev;
4741 			goto repeat;
4742 		}
4743 
4744 		/* We might be failing to detect boot device, give it
4745 		 * a few more chances.
4746 		 */
4747 		if (--tries) {
4748 			msleep(100);
4749 			goto repeat;
4750 		}
4751 
4752 		ata_port_err(ap,
4753 			     "WARNING: synchronous SCSI scan failed without making any progress, switching to async\n");
4754 	}
4755 
4756 	queue_delayed_work(system_long_wq, &ap->hotplug_task,
4757 			   round_jiffies_relative(HZ));
4758 }
4759 
4760 /**
4761  *	ata_scsi_offline_dev - offline attached SCSI device
4762  *	@dev: ATA device to offline attached SCSI device for
4763  *
4764  *	This function is called from ata_eh_detach_dev() and is responsible for
4765  *	taking the SCSI device attached to @dev offline.  This function is
4766  *	called with host lock which protects dev->sdev against clearing.
4767  *
4768  *	LOCKING:
4769  *	spin_lock_irqsave(host lock)
4770  *
4771  *	RETURNS:
4772  *	true if attached SCSI device exists, false otherwise.
4773  */
ata_scsi_offline_dev(struct ata_device * dev)4774 bool ata_scsi_offline_dev(struct ata_device *dev)
4775 {
4776 	if (dev->sdev) {
4777 		scsi_device_set_state(dev->sdev, SDEV_OFFLINE);
4778 		return true;
4779 	}
4780 	return false;
4781 }
4782 
4783 /**
4784  *	ata_scsi_remove_dev - remove attached SCSI device
4785  *	@dev: ATA device to remove attached SCSI device for
4786  *
4787  *	This function is called from ata_eh_scsi_hotplug() and
4788  *	responsible for removing the SCSI device attached to @dev.
4789  *
4790  *	LOCKING:
4791  *	Kernel thread context (may sleep).
4792  */
ata_scsi_remove_dev(struct ata_device * dev)4793 static void ata_scsi_remove_dev(struct ata_device *dev)
4794 {
4795 	struct ata_port *ap = dev->link->ap;
4796 	struct scsi_device *sdev;
4797 	unsigned long flags;
4798 
4799 	/* Alas, we need to grab scan_mutex to ensure SCSI device
4800 	 * state doesn't change underneath us and thus
4801 	 * scsi_device_get() always succeeds.  The mutex locking can
4802 	 * be removed if there is __scsi_device_get() interface which
4803 	 * increments reference counts regardless of device state.
4804 	 */
4805 	mutex_lock(&ap->scsi_host->scan_mutex);
4806 	spin_lock_irqsave(ap->lock, flags);
4807 
4808 	/* clearing dev->sdev is protected by host lock */
4809 	sdev = dev->sdev;
4810 	dev->sdev = NULL;
4811 
4812 	if (sdev) {
4813 		/* If user initiated unplug races with us, sdev can go
4814 		 * away underneath us after the host lock and
4815 		 * scan_mutex are released.  Hold onto it.
4816 		 */
4817 		if (scsi_device_get(sdev) == 0) {
4818 			/* The following ensures the attached sdev is
4819 			 * offline on return from ata_scsi_offline_dev()
4820 			 * regardless it wins or loses the race
4821 			 * against this function.
4822 			 */
4823 			scsi_device_set_state(sdev, SDEV_OFFLINE);
4824 		} else {
4825 			WARN_ON(1);
4826 			sdev = NULL;
4827 		}
4828 	}
4829 
4830 	spin_unlock_irqrestore(ap->lock, flags);
4831 	mutex_unlock(&ap->scsi_host->scan_mutex);
4832 
4833 	if (sdev) {
4834 		ata_dev_info(dev, "detaching (SCSI %s)\n",
4835 			     dev_name(&sdev->sdev_gendev));
4836 
4837 		scsi_remove_device(sdev);
4838 		scsi_device_put(sdev);
4839 	}
4840 }
4841 
ata_scsi_handle_link_detach(struct ata_link * link)4842 static void ata_scsi_handle_link_detach(struct ata_link *link)
4843 {
4844 	struct ata_port *ap = link->ap;
4845 	struct ata_device *dev;
4846 
4847 	ata_for_each_dev(dev, link, ALL) {
4848 		unsigned long flags;
4849 
4850 		spin_lock_irqsave(ap->lock, flags);
4851 		if (!(dev->flags & ATA_DFLAG_DETACHED)) {
4852 			spin_unlock_irqrestore(ap->lock, flags);
4853 			continue;
4854 		}
4855 
4856 		dev->flags &= ~ATA_DFLAG_DETACHED;
4857 		spin_unlock_irqrestore(ap->lock, flags);
4858 
4859 		ata_scsi_remove_dev(dev);
4860 	}
4861 }
4862 
4863 /**
4864  *	ata_scsi_media_change_notify - send media change event
4865  *	@dev: Pointer to the disk device with media change event
4866  *
4867  *	Tell the block layer to send a media change notification
4868  *	event.
4869  *
4870  * 	LOCKING:
4871  * 	spin_lock_irqsave(host lock)
4872  */
ata_scsi_media_change_notify(struct ata_device * dev)4873 void ata_scsi_media_change_notify(struct ata_device *dev)
4874 {
4875 	if (dev->sdev)
4876 		sdev_evt_send_simple(dev->sdev, SDEV_EVT_MEDIA_CHANGE,
4877 				     GFP_ATOMIC);
4878 }
4879 
4880 /**
4881  *	ata_scsi_hotplug - SCSI part of hotplug
4882  *	@work: Pointer to ATA port to perform SCSI hotplug on
4883  *
4884  *	Perform SCSI part of hotplug.  It's executed from a separate
4885  *	workqueue after EH completes.  This is necessary because SCSI
4886  *	hot plugging requires working EH and hot unplugging is
4887  *	synchronized with hot plugging with a mutex.
4888  *
4889  *	LOCKING:
4890  *	Kernel thread context (may sleep).
4891  */
ata_scsi_hotplug(struct work_struct * work)4892 void ata_scsi_hotplug(struct work_struct *work)
4893 {
4894 	struct ata_port *ap =
4895 		container_of(work, struct ata_port, hotplug_task.work);
4896 	int i;
4897 
4898 	if (ap->pflags & ATA_PFLAG_UNLOADING)
4899 		return;
4900 
4901 	mutex_lock(&ap->scsi_scan_mutex);
4902 
4903 	/* Unplug detached devices.  We cannot use link iterator here
4904 	 * because PMP links have to be scanned even if PMP is
4905 	 * currently not attached.  Iterate manually.
4906 	 */
4907 	ata_scsi_handle_link_detach(&ap->link);
4908 	if (ap->pmp_link)
4909 		for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
4910 			ata_scsi_handle_link_detach(&ap->pmp_link[i]);
4911 
4912 	/* scan for new ones */
4913 	ata_scsi_scan_host(ap, 0);
4914 
4915 	mutex_unlock(&ap->scsi_scan_mutex);
4916 }
4917 
4918 /**
4919  *	ata_scsi_user_scan - indication for user-initiated bus scan
4920  *	@shost: SCSI host to scan
4921  *	@channel: Channel to scan
4922  *	@id: ID to scan
4923  *	@lun: LUN to scan
4924  *
4925  *	This function is called when user explicitly requests bus
4926  *	scan.  Set probe pending flag and invoke EH.
4927  *
4928  *	LOCKING:
4929  *	SCSI layer (we don't care)
4930  *
4931  *	RETURNS:
4932  *	Zero.
4933  */
ata_scsi_user_scan(struct Scsi_Host * shost,unsigned int channel,unsigned int id,u64 lun)4934 int ata_scsi_user_scan(struct Scsi_Host *shost, unsigned int channel,
4935 		       unsigned int id, u64 lun)
4936 {
4937 	struct ata_port *ap = ata_shost_to_port(shost);
4938 	unsigned long flags;
4939 	int devno, rc = 0;
4940 
4941 	if (lun != SCAN_WILD_CARD && lun)
4942 		return -EINVAL;
4943 
4944 	if (!sata_pmp_attached(ap)) {
4945 		if (channel != SCAN_WILD_CARD && channel)
4946 			return -EINVAL;
4947 		devno = id;
4948 	} else {
4949 		if (id != SCAN_WILD_CARD && id)
4950 			return -EINVAL;
4951 		devno = channel;
4952 	}
4953 
4954 	spin_lock_irqsave(ap->lock, flags);
4955 
4956 	if (devno == SCAN_WILD_CARD) {
4957 		struct ata_link *link;
4958 
4959 		ata_for_each_link(link, ap, EDGE) {
4960 			struct ata_eh_info *ehi = &link->eh_info;
4961 			ehi->probe_mask |= ATA_ALL_DEVICES;
4962 			ehi->action |= ATA_EH_RESET;
4963 		}
4964 	} else {
4965 		struct ata_device *dev = ata_find_dev(ap, devno);
4966 
4967 		if (dev) {
4968 			struct ata_eh_info *ehi = &dev->link->eh_info;
4969 			ehi->probe_mask |= 1 << dev->devno;
4970 			ehi->action |= ATA_EH_RESET;
4971 		} else
4972 			rc = -EINVAL;
4973 	}
4974 
4975 	if (rc == 0) {
4976 		ata_port_schedule_eh(ap);
4977 		spin_unlock_irqrestore(ap->lock, flags);
4978 		ata_port_wait_eh(ap);
4979 	} else
4980 		spin_unlock_irqrestore(ap->lock, flags);
4981 
4982 	return rc;
4983 }
4984 
4985 /**
4986  *	ata_scsi_dev_rescan - initiate scsi_rescan_device()
4987  *	@work: Pointer to ATA port to perform scsi_rescan_device()
4988  *
4989  *	After ATA pass thru (SAT) commands are executed successfully,
4990  *	libata need to propagate the changes to SCSI layer.
4991  *
4992  *	LOCKING:
4993  *	Kernel thread context (may sleep).
4994  */
ata_scsi_dev_rescan(struct work_struct * work)4995 void ata_scsi_dev_rescan(struct work_struct *work)
4996 {
4997 	struct ata_port *ap =
4998 		container_of(work, struct ata_port, scsi_rescan_task.work);
4999 	struct ata_link *link;
5000 	struct ata_device *dev;
5001 	unsigned long flags;
5002 	bool do_resume;
5003 	int ret = 0;
5004 
5005 	mutex_lock(&ap->scsi_scan_mutex);
5006 	spin_lock_irqsave(ap->lock, flags);
5007 
5008 	ata_for_each_link(link, ap, EDGE) {
5009 		ata_for_each_dev(dev, link, ENABLED) {
5010 			struct scsi_device *sdev = dev->sdev;
5011 
5012 			/*
5013 			 * If the port was suspended before this was scheduled,
5014 			 * bail out.
5015 			 */
5016 			if (ap->pflags & ATA_PFLAG_SUSPENDED)
5017 				goto unlock_ap;
5018 
5019 			if (!sdev)
5020 				continue;
5021 			if (scsi_device_get(sdev))
5022 				continue;
5023 
5024 			do_resume = dev->flags & ATA_DFLAG_RESUMING;
5025 
5026 			spin_unlock_irqrestore(ap->lock, flags);
5027 			if (do_resume) {
5028 				ret = scsi_resume_device(sdev);
5029 				if (ret == -EWOULDBLOCK) {
5030 					scsi_device_put(sdev);
5031 					goto unlock_scan;
5032 				}
5033 				dev->flags &= ~ATA_DFLAG_RESUMING;
5034 			}
5035 			ret = scsi_rescan_device(sdev);
5036 			scsi_device_put(sdev);
5037 			spin_lock_irqsave(ap->lock, flags);
5038 
5039 			if (ret)
5040 				goto unlock_ap;
5041 		}
5042 	}
5043 
5044 unlock_ap:
5045 	spin_unlock_irqrestore(ap->lock, flags);
5046 unlock_scan:
5047 	mutex_unlock(&ap->scsi_scan_mutex);
5048 
5049 	/* Reschedule with a delay if scsi_rescan_device() returned an error */
5050 	if (ret)
5051 		schedule_delayed_work(&ap->scsi_rescan_task,
5052 				      msecs_to_jiffies(5));
5053 }
5054