xref: /linux/drivers/ata/libahci.c (revision fb2c3f44a7e14627b9dca8e6b568e6cdc234b40b)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  libahci.c - Common AHCI SATA low-level routines
4  *
5  *  Maintained by:  Tejun Heo <tj@kernel.org>
6  *    		    Please ALWAYS copy linux-ide@vger.kernel.org
7  *		    on emails.
8  *
9  *  Copyright 2004-2005 Red Hat, Inc.
10  *
11  * libata documentation is available via 'make {ps|pdf}docs',
12  * as Documentation/driver-api/libata.rst
13  *
14  * AHCI hardware documentation:
15  * http://www.intel.com/technology/serialata/pdf/rev1_0.pdf
16  * http://www.intel.com/technology/serialata/pdf/rev1_1.pdf
17  */
18 
19 #include <linux/bitops.h>
20 #include <linux/kernel.h>
21 #include <linux/gfp.h>
22 #include <linux/module.h>
23 #include <linux/nospec.h>
24 #include <linux/blkdev.h>
25 #include <linux/delay.h>
26 #include <linux/interrupt.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/device.h>
29 #include <scsi/scsi_host.h>
30 #include <scsi/scsi_cmnd.h>
31 #include <linux/libata.h>
32 #include <linux/pci.h>
33 #include <linux/pm_runtime.h>
34 #include "ahci.h"
35 #include "libata.h"
36 
37 static int ahci_skip_host_reset;
38 int ahci_ignore_sss;
39 EXPORT_SYMBOL_GPL(ahci_ignore_sss);
40 
41 module_param_named(skip_host_reset, ahci_skip_host_reset, int, 0444);
42 MODULE_PARM_DESC(skip_host_reset, "skip global host reset (0=don't skip, 1=skip)");
43 
44 module_param_named(ignore_sss, ahci_ignore_sss, int, 0444);
45 MODULE_PARM_DESC(ignore_sss, "Ignore staggered spinup flag (0=don't ignore, 1=ignore)");
46 
47 static int ahci_set_lpm(struct ata_link *link, enum ata_lpm_policy policy,
48 			unsigned hints);
49 static ssize_t ahci_led_show(struct ata_port *ap, char *buf);
50 static ssize_t ahci_led_store(struct ata_port *ap, const char *buf,
51 			      size_t size);
52 static ssize_t ahci_transmit_led_message(struct ata_port *ap, u32 state,
53 					ssize_t size);
54 
55 
56 
57 static int ahci_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val);
58 static int ahci_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val);
59 static void ahci_qc_fill_rtf(struct ata_queued_cmd *qc);
60 static void ahci_qc_ncq_fill_rtf(struct ata_port *ap, u64 done_mask);
61 static int ahci_port_start(struct ata_port *ap);
62 static void ahci_port_stop(struct ata_port *ap);
63 static enum ata_completion_errors ahci_qc_prep(struct ata_queued_cmd *qc);
64 static int ahci_pmp_qc_defer(struct ata_queued_cmd *qc);
65 static void ahci_freeze(struct ata_port *ap);
66 static void ahci_thaw(struct ata_port *ap);
67 static void ahci_set_aggressive_devslp(struct ata_port *ap, bool sleep);
68 static void ahci_enable_fbs(struct ata_port *ap);
69 static void ahci_disable_fbs(struct ata_port *ap);
70 static void ahci_pmp_attach(struct ata_port *ap);
71 static void ahci_pmp_detach(struct ata_port *ap);
72 static int ahci_softreset(struct ata_link *link, unsigned int *class,
73 			  unsigned long deadline);
74 static int ahci_pmp_retry_softreset(struct ata_link *link, unsigned int *class,
75 			  unsigned long deadline);
76 static int ahci_hardreset(struct ata_link *link, unsigned int *class,
77 			  unsigned long deadline);
78 static void ahci_postreset(struct ata_link *link, unsigned int *class);
79 static void ahci_post_internal_cmd(struct ata_queued_cmd *qc);
80 static void ahci_dev_config(struct ata_device *dev);
81 #ifdef CONFIG_PM
82 static int ahci_port_suspend(struct ata_port *ap, pm_message_t mesg);
83 #endif
84 static ssize_t ahci_activity_show(struct ata_device *dev, char *buf);
85 static ssize_t ahci_activity_store(struct ata_device *dev,
86 				   enum sw_activity val);
87 static void ahci_init_sw_activity(struct ata_link *link);
88 
89 static ssize_t ahci_show_host_caps(struct device *dev,
90 				   struct device_attribute *attr, char *buf);
91 static ssize_t ahci_show_host_cap2(struct device *dev,
92 				   struct device_attribute *attr, char *buf);
93 static ssize_t ahci_show_host_version(struct device *dev,
94 				      struct device_attribute *attr, char *buf);
95 static ssize_t ahci_show_port_cmd(struct device *dev,
96 				  struct device_attribute *attr, char *buf);
97 static ssize_t ahci_read_em_buffer(struct device *dev,
98 				   struct device_attribute *attr, char *buf);
99 static ssize_t ahci_store_em_buffer(struct device *dev,
100 				    struct device_attribute *attr,
101 				    const char *buf, size_t size);
102 static ssize_t ahci_show_em_supported(struct device *dev,
103 				      struct device_attribute *attr, char *buf);
104 static irqreturn_t ahci_single_level_irq_intr(int irq, void *dev_instance);
105 
106 static DEVICE_ATTR(ahci_host_caps, S_IRUGO, ahci_show_host_caps, NULL);
107 static DEVICE_ATTR(ahci_host_cap2, S_IRUGO, ahci_show_host_cap2, NULL);
108 static DEVICE_ATTR(ahci_host_version, S_IRUGO, ahci_show_host_version, NULL);
109 static DEVICE_ATTR(ahci_port_cmd, S_IRUGO, ahci_show_port_cmd, NULL);
110 static DEVICE_ATTR(em_buffer, S_IWUSR | S_IRUGO,
111 		   ahci_read_em_buffer, ahci_store_em_buffer);
112 static DEVICE_ATTR(em_message_supported, S_IRUGO, ahci_show_em_supported, NULL);
113 
114 static struct attribute *ahci_shost_attrs[] = {
115 	&dev_attr_link_power_management_supported.attr,
116 	&dev_attr_link_power_management_policy.attr,
117 	&dev_attr_em_message_type.attr,
118 	&dev_attr_em_message.attr,
119 	&dev_attr_ahci_host_caps.attr,
120 	&dev_attr_ahci_host_cap2.attr,
121 	&dev_attr_ahci_host_version.attr,
122 	&dev_attr_ahci_port_cmd.attr,
123 	&dev_attr_em_buffer.attr,
124 	&dev_attr_em_message_supported.attr,
125 	NULL
126 };
127 
128 static const struct attribute_group ahci_shost_attr_group = {
129 	.attrs = ahci_shost_attrs
130 };
131 
132 const struct attribute_group *ahci_shost_groups[] = {
133 	&ahci_shost_attr_group,
134 	NULL
135 };
136 EXPORT_SYMBOL_GPL(ahci_shost_groups);
137 
138 static struct attribute *ahci_sdev_attrs[] = {
139 	&dev_attr_sw_activity.attr,
140 	&dev_attr_unload_heads.attr,
141 	&dev_attr_ncq_prio_supported.attr,
142 	&dev_attr_ncq_prio_enable.attr,
143 	NULL
144 };
145 
146 static const struct attribute_group ahci_sdev_attr_group = {
147 	.attrs = ahci_sdev_attrs
148 };
149 
150 const struct attribute_group *ahci_sdev_groups[] = {
151 	&ahci_sdev_attr_group,
152 	NULL
153 };
154 EXPORT_SYMBOL_GPL(ahci_sdev_groups);
155 
156 struct ata_port_operations ahci_ops = {
157 	.inherits		= &sata_pmp_port_ops,
158 
159 	.qc_defer		= ahci_pmp_qc_defer,
160 	.qc_prep		= ahci_qc_prep,
161 	.qc_issue		= ahci_qc_issue,
162 	.qc_fill_rtf		= ahci_qc_fill_rtf,
163 	.qc_ncq_fill_rtf	= ahci_qc_ncq_fill_rtf,
164 
165 	.freeze			= ahci_freeze,
166 	.thaw			= ahci_thaw,
167 	.reset.softreset	= ahci_softreset,
168 	.reset.hardreset	= ahci_hardreset,
169 	.reset.postreset	= ahci_postreset,
170 	.pmp_reset.softreset	= ahci_softreset,
171 	.error_handler		= ahci_error_handler,
172 	.post_internal_cmd	= ahci_post_internal_cmd,
173 	.dev_config		= ahci_dev_config,
174 
175 	.scr_read		= ahci_scr_read,
176 	.scr_write		= ahci_scr_write,
177 	.pmp_attach		= ahci_pmp_attach,
178 	.pmp_detach		= ahci_pmp_detach,
179 
180 	.set_lpm		= ahci_set_lpm,
181 	.em_show		= ahci_led_show,
182 	.em_store		= ahci_led_store,
183 	.sw_activity_show	= ahci_activity_show,
184 	.sw_activity_store	= ahci_activity_store,
185 	.transmit_led_message	= ahci_transmit_led_message,
186 #ifdef CONFIG_PM
187 	.port_suspend		= ahci_port_suspend,
188 	.port_resume		= ahci_port_resume,
189 #endif
190 	.port_start		= ahci_port_start,
191 	.port_stop		= ahci_port_stop,
192 };
193 EXPORT_SYMBOL_GPL(ahci_ops);
194 
195 struct ata_port_operations ahci_pmp_retry_srst_ops = {
196 	.inherits		= &ahci_ops,
197 	.reset.softreset	= ahci_pmp_retry_softreset,
198 };
199 EXPORT_SYMBOL_GPL(ahci_pmp_retry_srst_ops);
200 
201 static bool ahci_em_messages __read_mostly = true;
202 module_param(ahci_em_messages, bool, 0444);
203 /* add other LED protocol types when they become supported */
204 MODULE_PARM_DESC(ahci_em_messages,
205 	"AHCI Enclosure Management Message control (0 = off, 1 = on)");
206 
207 /* device sleep idle timeout in ms */
208 static int devslp_idle_timeout __read_mostly = 1000;
209 module_param(devslp_idle_timeout, int, 0644);
210 MODULE_PARM_DESC(devslp_idle_timeout, "device sleep idle timeout");
211 
212 static void ahci_enable_ahci(void __iomem *mmio)
213 {
214 	int i;
215 	u32 tmp;
216 
217 	/* turn on AHCI_EN */
218 	tmp = readl(mmio + HOST_CTL);
219 	if (tmp & HOST_AHCI_EN)
220 		return;
221 
222 	/* Some controllers need AHCI_EN to be written multiple times.
223 	 * Try a few times before giving up.
224 	 */
225 	for (i = 0; i < 5; i++) {
226 		tmp |= HOST_AHCI_EN;
227 		writel(tmp, mmio + HOST_CTL);
228 		tmp = readl(mmio + HOST_CTL);	/* flush && sanity check */
229 		if (tmp & HOST_AHCI_EN)
230 			return;
231 		msleep(10);
232 	}
233 
234 	WARN_ON(1);
235 }
236 
237 /**
238  *	ahci_rpm_get_port - Make sure the port is powered on
239  *	@ap: Port to power on
240  *
241  *	Whenever there is need to access the AHCI host registers outside of
242  *	normal execution paths, call this function to make sure the host is
243  *	actually powered on.
244  */
245 static int ahci_rpm_get_port(struct ata_port *ap)
246 {
247 	return pm_runtime_get_sync(ap->dev);
248 }
249 
250 /**
251  *	ahci_rpm_put_port - Undoes ahci_rpm_get_port()
252  *	@ap: Port to power down
253  *
254  *	Undoes ahci_rpm_get_port() and possibly powers down the AHCI host
255  *	if it has no more active users.
256  */
257 static void ahci_rpm_put_port(struct ata_port *ap)
258 {
259 	pm_runtime_put(ap->dev);
260 }
261 
262 static ssize_t ahci_show_host_caps(struct device *dev,
263 				   struct device_attribute *attr, char *buf)
264 {
265 	struct Scsi_Host *shost = class_to_shost(dev);
266 	struct ata_port *ap = ata_shost_to_port(shost);
267 	struct ahci_host_priv *hpriv = ap->host->private_data;
268 
269 	return sprintf(buf, "%x\n", hpriv->cap);
270 }
271 
272 static ssize_t ahci_show_host_cap2(struct device *dev,
273 				   struct device_attribute *attr, char *buf)
274 {
275 	struct Scsi_Host *shost = class_to_shost(dev);
276 	struct ata_port *ap = ata_shost_to_port(shost);
277 	struct ahci_host_priv *hpriv = ap->host->private_data;
278 
279 	return sprintf(buf, "%x\n", hpriv->cap2);
280 }
281 
282 static ssize_t ahci_show_host_version(struct device *dev,
283 				   struct device_attribute *attr, char *buf)
284 {
285 	struct Scsi_Host *shost = class_to_shost(dev);
286 	struct ata_port *ap = ata_shost_to_port(shost);
287 	struct ahci_host_priv *hpriv = ap->host->private_data;
288 
289 	return sprintf(buf, "%x\n", hpriv->version);
290 }
291 
292 static ssize_t ahci_show_port_cmd(struct device *dev,
293 				  struct device_attribute *attr, char *buf)
294 {
295 	struct Scsi_Host *shost = class_to_shost(dev);
296 	struct ata_port *ap = ata_shost_to_port(shost);
297 	void __iomem *port_mmio = ahci_port_base(ap);
298 	ssize_t ret;
299 
300 	ahci_rpm_get_port(ap);
301 	ret = sprintf(buf, "%x\n", readl(port_mmio + PORT_CMD));
302 	ahci_rpm_put_port(ap);
303 
304 	return ret;
305 }
306 
307 static ssize_t ahci_read_em_buffer(struct device *dev,
308 				   struct device_attribute *attr, char *buf)
309 {
310 	struct Scsi_Host *shost = class_to_shost(dev);
311 	struct ata_port *ap = ata_shost_to_port(shost);
312 	struct ahci_host_priv *hpriv = ap->host->private_data;
313 	void __iomem *mmio = hpriv->mmio;
314 	void __iomem *em_mmio = mmio + hpriv->em_loc;
315 	u32 em_ctl, msg;
316 	unsigned long flags;
317 	size_t count;
318 	int i;
319 
320 	ahci_rpm_get_port(ap);
321 	spin_lock_irqsave(ap->lock, flags);
322 
323 	em_ctl = readl(mmio + HOST_EM_CTL);
324 	if (!(ap->flags & ATA_FLAG_EM) || em_ctl & EM_CTL_XMT ||
325 	    !(hpriv->em_msg_type & EM_MSG_TYPE_SGPIO)) {
326 		spin_unlock_irqrestore(ap->lock, flags);
327 		ahci_rpm_put_port(ap);
328 		return -EINVAL;
329 	}
330 
331 	if (!(em_ctl & EM_CTL_MR)) {
332 		spin_unlock_irqrestore(ap->lock, flags);
333 		ahci_rpm_put_port(ap);
334 		return -EAGAIN;
335 	}
336 
337 	if (!(em_ctl & EM_CTL_SMB))
338 		em_mmio += hpriv->em_buf_sz;
339 
340 	count = hpriv->em_buf_sz;
341 
342 	/* the count should not be larger than PAGE_SIZE */
343 	if (count > PAGE_SIZE) {
344 		if (printk_ratelimit())
345 			ata_port_warn(ap,
346 				      "EM read buffer size too large: "
347 				      "buffer size %u, page size %lu\n",
348 				      hpriv->em_buf_sz, PAGE_SIZE);
349 		count = PAGE_SIZE;
350 	}
351 
352 	for (i = 0; i < count; i += 4) {
353 		msg = readl(em_mmio + i);
354 		buf[i] = msg & 0xff;
355 		buf[i + 1] = (msg >> 8) & 0xff;
356 		buf[i + 2] = (msg >> 16) & 0xff;
357 		buf[i + 3] = (msg >> 24) & 0xff;
358 	}
359 
360 	spin_unlock_irqrestore(ap->lock, flags);
361 	ahci_rpm_put_port(ap);
362 
363 	return i;
364 }
365 
366 static ssize_t ahci_store_em_buffer(struct device *dev,
367 				    struct device_attribute *attr,
368 				    const char *buf, size_t size)
369 {
370 	struct Scsi_Host *shost = class_to_shost(dev);
371 	struct ata_port *ap = ata_shost_to_port(shost);
372 	struct ahci_host_priv *hpriv = ap->host->private_data;
373 	void __iomem *mmio = hpriv->mmio;
374 	void __iomem *em_mmio = mmio + hpriv->em_loc;
375 	const unsigned char *msg_buf = buf;
376 	u32 em_ctl, msg;
377 	unsigned long flags;
378 	int i;
379 
380 	/* check size validity */
381 	if (!(ap->flags & ATA_FLAG_EM) ||
382 	    !(hpriv->em_msg_type & EM_MSG_TYPE_SGPIO) ||
383 	    size % 4 || size > hpriv->em_buf_sz)
384 		return -EINVAL;
385 
386 	ahci_rpm_get_port(ap);
387 	spin_lock_irqsave(ap->lock, flags);
388 
389 	em_ctl = readl(mmio + HOST_EM_CTL);
390 	if (em_ctl & EM_CTL_TM) {
391 		spin_unlock_irqrestore(ap->lock, flags);
392 		ahci_rpm_put_port(ap);
393 		return -EBUSY;
394 	}
395 
396 	for (i = 0; i < size; i += 4) {
397 		msg = msg_buf[i] | msg_buf[i + 1] << 8 |
398 		      msg_buf[i + 2] << 16 | msg_buf[i + 3] << 24;
399 		writel(msg, em_mmio + i);
400 	}
401 
402 	writel(em_ctl | EM_CTL_TM, mmio + HOST_EM_CTL);
403 
404 	spin_unlock_irqrestore(ap->lock, flags);
405 	ahci_rpm_put_port(ap);
406 
407 	return size;
408 }
409 
410 static ssize_t ahci_show_em_supported(struct device *dev,
411 				      struct device_attribute *attr, char *buf)
412 {
413 	struct Scsi_Host *shost = class_to_shost(dev);
414 	struct ata_port *ap = ata_shost_to_port(shost);
415 	struct ahci_host_priv *hpriv = ap->host->private_data;
416 	void __iomem *mmio = hpriv->mmio;
417 	u32 em_ctl;
418 
419 	ahci_rpm_get_port(ap);
420 	em_ctl = readl(mmio + HOST_EM_CTL);
421 	ahci_rpm_put_port(ap);
422 
423 	return sprintf(buf, "%s%s%s%s\n",
424 		       em_ctl & EM_CTL_LED ? "led " : "",
425 		       em_ctl & EM_CTL_SAFTE ? "saf-te " : "",
426 		       em_ctl & EM_CTL_SES ? "ses-2 " : "",
427 		       em_ctl & EM_CTL_SGPIO ? "sgpio " : "");
428 }
429 
430 /**
431  *	ahci_save_initial_config - Save and fixup initial config values
432  *	@dev: target AHCI device
433  *	@hpriv: host private area to store config values
434  *
435  *	Some registers containing configuration info might be setup by
436  *	BIOS and might be cleared on reset.  This function saves the
437  *	initial values of those registers into @hpriv such that they
438  *	can be restored after controller reset.
439  *
440  *	If inconsistent, config values are fixed up by this function.
441  *
442  *	If it is not set already this function sets hpriv->start_engine to
443  *	ahci_start_engine.
444  *
445  *	LOCKING:
446  *	None.
447  */
448 void ahci_save_initial_config(struct device *dev, struct ahci_host_priv *hpriv)
449 {
450 	void __iomem *mmio = hpriv->mmio;
451 	void __iomem *port_mmio;
452 	unsigned long port_map;
453 	u32 cap, cap2, vers;
454 	int i;
455 
456 	/* make sure AHCI mode is enabled before accessing CAP */
457 	ahci_enable_ahci(mmio);
458 
459 	/*
460 	 * Values prefixed with saved_ are written back to the HBA and ports
461 	 * registers after reset. Values without are used for driver operation.
462 	 */
463 
464 	/*
465 	 * Override HW-init HBA capability fields with the platform-specific
466 	 * values. The rest of the HBA capabilities are defined as Read-only
467 	 * and can't be modified in CSR anyway.
468 	 */
469 	cap = readl(mmio + HOST_CAP);
470 	if (hpriv->saved_cap)
471 		cap = (cap & ~(HOST_CAP_SSS | HOST_CAP_MPS)) | hpriv->saved_cap;
472 	hpriv->saved_cap = cap;
473 
474 	/* CAP2 register is only defined for AHCI 1.2 and later */
475 	vers = readl(mmio + HOST_VERSION);
476 	if ((vers >> 16) > 1 ||
477 	   ((vers >> 16) == 1 && (vers & 0xFFFF) >= 0x200))
478 		hpriv->saved_cap2 = cap2 = readl(mmio + HOST_CAP2);
479 	else
480 		hpriv->saved_cap2 = cap2 = 0;
481 
482 	/* some chips have errata preventing 64bit use */
483 	if ((cap & HOST_CAP_64) && (hpriv->flags & AHCI_HFLAG_32BIT_ONLY)) {
484 		dev_info(dev, "controller can't do 64bit DMA, forcing 32bit\n");
485 		cap &= ~HOST_CAP_64;
486 	}
487 
488 	if ((cap & HOST_CAP_NCQ) && (hpriv->flags & AHCI_HFLAG_NO_NCQ)) {
489 		dev_info(dev, "controller can't do NCQ, turning off CAP_NCQ\n");
490 		cap &= ~HOST_CAP_NCQ;
491 	}
492 
493 	if (!(cap & HOST_CAP_NCQ) && (hpriv->flags & AHCI_HFLAG_YES_NCQ)) {
494 		dev_info(dev, "controller can do NCQ, turning on CAP_NCQ\n");
495 		cap |= HOST_CAP_NCQ;
496 	}
497 
498 	if ((cap & HOST_CAP_PMP) && (hpriv->flags & AHCI_HFLAG_NO_PMP)) {
499 		dev_info(dev, "controller can't do PMP, turning off CAP_PMP\n");
500 		cap &= ~HOST_CAP_PMP;
501 	}
502 
503 	if ((cap & HOST_CAP_SNTF) && (hpriv->flags & AHCI_HFLAG_NO_SNTF)) {
504 		dev_info(dev,
505 			 "controller can't do SNTF, turning off CAP_SNTF\n");
506 		cap &= ~HOST_CAP_SNTF;
507 	}
508 
509 	if ((cap2 & HOST_CAP2_SDS) && (hpriv->flags & AHCI_HFLAG_NO_DEVSLP)) {
510 		dev_info(dev,
511 			 "controller can't do DEVSLP, turning off\n");
512 		cap2 &= ~HOST_CAP2_SDS;
513 		cap2 &= ~HOST_CAP2_SADM;
514 	}
515 
516 	if (!(cap & HOST_CAP_FBS) && (hpriv->flags & AHCI_HFLAG_YES_FBS)) {
517 		dev_info(dev, "controller can do FBS, turning on CAP_FBS\n");
518 		cap |= HOST_CAP_FBS;
519 	}
520 
521 	if ((cap & HOST_CAP_FBS) && (hpriv->flags & AHCI_HFLAG_NO_FBS)) {
522 		dev_info(dev, "controller can't do FBS, turning off CAP_FBS\n");
523 		cap &= ~HOST_CAP_FBS;
524 	}
525 
526 	if (!(cap & HOST_CAP_ALPM) && (hpriv->flags & AHCI_HFLAG_YES_ALPM)) {
527 		dev_info(dev, "controller can do ALPM, turning on CAP_ALPM\n");
528 		cap |= HOST_CAP_ALPM;
529 	}
530 
531 	if ((cap & HOST_CAP_SXS) && (hpriv->flags & AHCI_HFLAG_NO_SXS)) {
532 		dev_info(dev, "controller does not support SXS, disabling CAP_SXS\n");
533 		cap &= ~HOST_CAP_SXS;
534 	}
535 
536 	/* Override the HBA ports mapping if the platform needs it */
537 	port_map = readl(mmio + HOST_PORTS_IMPL);
538 	if (hpriv->saved_port_map && port_map != hpriv->saved_port_map) {
539 		dev_info(dev, "forcing port_map 0x%lx -> 0x%x\n",
540 			 port_map, hpriv->saved_port_map);
541 		port_map = hpriv->saved_port_map;
542 	} else {
543 		hpriv->saved_port_map = port_map;
544 	}
545 
546 	/* mask_port_map not set means that all ports are available */
547 	if (hpriv->mask_port_map) {
548 		dev_warn(dev, "masking port_map 0x%lx -> 0x%lx\n",
549 			port_map,
550 			port_map & hpriv->mask_port_map);
551 		port_map &= hpriv->mask_port_map;
552 	}
553 
554 	/* cross check port_map and cap.n_ports */
555 	if (port_map) {
556 		int map_ports = hweight_long(port_map);
557 
558 		/* If PI has more ports than n_ports, whine, clear
559 		 * port_map and let it be generated from n_ports.
560 		 */
561 		if (map_ports > ahci_nr_ports(cap)) {
562 			dev_warn(dev,
563 				 "implemented port map (0x%lx) contains more ports than nr_ports (%u), using nr_ports\n",
564 				 port_map, ahci_nr_ports(cap));
565 			port_map = 0;
566 		}
567 	}
568 
569 	/* fabricate port_map from cap.nr_ports for < AHCI 1.3 */
570 	if (!port_map && vers < 0x10300) {
571 		port_map = (1 << ahci_nr_ports(cap)) - 1;
572 		dev_warn(dev, "forcing PORTS_IMPL to 0x%lx\n", port_map);
573 
574 		/* write the fixed up value to the PI register */
575 		hpriv->saved_port_map = port_map;
576 	}
577 
578 	/*
579 	 * Preserve the ports capabilities defined by the platform. Note there
580 	 * is no need in storing the rest of the P#.CMD fields since they are
581 	 * volatile.
582 	 */
583 	for_each_set_bit(i, &port_map, AHCI_MAX_PORTS) {
584 		if (hpriv->saved_port_cap[i])
585 			continue;
586 
587 		port_mmio = __ahci_port_base(hpriv, i);
588 		hpriv->saved_port_cap[i] =
589 			readl(port_mmio + PORT_CMD) & PORT_CMD_CAP;
590 	}
591 
592 	/* record values to use during operation */
593 	hpriv->cap = cap;
594 	hpriv->cap2 = cap2;
595 	hpriv->version = vers;
596 	hpriv->port_map = port_map;
597 
598 	if (!hpriv->start_engine)
599 		hpriv->start_engine = ahci_start_engine;
600 
601 	if (!hpriv->stop_engine)
602 		hpriv->stop_engine = ahci_stop_engine;
603 
604 	if (!hpriv->irq_handler)
605 		hpriv->irq_handler = ahci_single_level_irq_intr;
606 }
607 EXPORT_SYMBOL_GPL(ahci_save_initial_config);
608 
609 /**
610  *	ahci_restore_initial_config - Restore initial config
611  *	@host: target ATA host
612  *
613  *	Restore initial config stored by ahci_save_initial_config().
614  *
615  *	LOCKING:
616  *	None.
617  */
618 static void ahci_restore_initial_config(struct ata_host *host)
619 {
620 	struct ahci_host_priv *hpriv = host->private_data;
621 	unsigned long port_map = hpriv->port_map;
622 	void __iomem *mmio = hpriv->mmio;
623 	void __iomem *port_mmio;
624 	int i;
625 
626 	writel(hpriv->saved_cap, mmio + HOST_CAP);
627 	if (hpriv->saved_cap2)
628 		writel(hpriv->saved_cap2, mmio + HOST_CAP2);
629 	writel(hpriv->saved_port_map, mmio + HOST_PORTS_IMPL);
630 	(void) readl(mmio + HOST_PORTS_IMPL);	/* flush */
631 
632 	for_each_set_bit(i, &port_map, AHCI_MAX_PORTS) {
633 		port_mmio = __ahci_port_base(hpriv, i);
634 		writel(hpriv->saved_port_cap[i], port_mmio + PORT_CMD);
635 	}
636 }
637 
638 static unsigned ahci_scr_offset(struct ata_port *ap, unsigned int sc_reg)
639 {
640 	static const int offset[] = {
641 		[SCR_STATUS]		= PORT_SCR_STAT,
642 		[SCR_CONTROL]		= PORT_SCR_CTL,
643 		[SCR_ERROR]		= PORT_SCR_ERR,
644 		[SCR_ACTIVE]		= PORT_SCR_ACT,
645 		[SCR_NOTIFICATION]	= PORT_SCR_NTF,
646 	};
647 	struct ahci_host_priv *hpriv = ap->host->private_data;
648 
649 	if (sc_reg < ARRAY_SIZE(offset) &&
650 	    (sc_reg != SCR_NOTIFICATION || (hpriv->cap & HOST_CAP_SNTF)))
651 		return offset[sc_reg];
652 	return 0;
653 }
654 
655 static int ahci_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val)
656 {
657 	void __iomem *port_mmio = ahci_port_base(link->ap);
658 	int offset = ahci_scr_offset(link->ap, sc_reg);
659 
660 	if (offset) {
661 		*val = readl(port_mmio + offset);
662 		return 0;
663 	}
664 	return -EINVAL;
665 }
666 
667 static int ahci_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val)
668 {
669 	void __iomem *port_mmio = ahci_port_base(link->ap);
670 	int offset = ahci_scr_offset(link->ap, sc_reg);
671 
672 	if (offset) {
673 		writel(val, port_mmio + offset);
674 		return 0;
675 	}
676 	return -EINVAL;
677 }
678 
679 void ahci_start_engine(struct ata_port *ap)
680 {
681 	void __iomem *port_mmio = ahci_port_base(ap);
682 	u32 tmp;
683 
684 	/* start DMA */
685 	tmp = readl(port_mmio + PORT_CMD);
686 	tmp |= PORT_CMD_START;
687 	writel(tmp, port_mmio + PORT_CMD);
688 	readl(port_mmio + PORT_CMD); /* flush */
689 }
690 EXPORT_SYMBOL_GPL(ahci_start_engine);
691 
692 int ahci_stop_engine(struct ata_port *ap)
693 {
694 	void __iomem *port_mmio = ahci_port_base(ap);
695 	struct ahci_host_priv *hpriv = ap->host->private_data;
696 	u32 tmp;
697 
698 	/*
699 	 * On some controllers, stopping a port's DMA engine while the port
700 	 * is in ALPM state (partial or slumber) results in failures on
701 	 * subsequent DMA engine starts.  For those controllers, put the
702 	 * port back in active state before stopping its DMA engine.
703 	 */
704 	if ((hpriv->flags & AHCI_HFLAG_WAKE_BEFORE_STOP) &&
705 	    (ap->link.lpm_policy > ATA_LPM_MAX_POWER) &&
706 	    ahci_set_lpm(&ap->link, ATA_LPM_MAX_POWER, ATA_LPM_WAKE_ONLY)) {
707 		dev_err(ap->host->dev, "Failed to wake up port before engine stop\n");
708 		return -EIO;
709 	}
710 
711 	tmp = readl(port_mmio + PORT_CMD);
712 
713 	/* check if the HBA is idle */
714 	if ((tmp & (PORT_CMD_START | PORT_CMD_LIST_ON)) == 0)
715 		return 0;
716 
717 	/*
718 	 * Don't try to issue commands but return with ENODEV if the
719 	 * AHCI controller not available anymore (e.g. due to PCIe hot
720 	 * unplugging). Otherwise a 500ms delay for each port is added.
721 	 */
722 	if (tmp == 0xffffffff) {
723 		dev_err(ap->host->dev, "AHCI controller unavailable!\n");
724 		return -ENODEV;
725 	}
726 
727 	/* setting HBA to idle */
728 	tmp &= ~PORT_CMD_START;
729 	writel(tmp, port_mmio + PORT_CMD);
730 
731 	/* wait for engine to stop. This could be as long as 500 msec */
732 	tmp = ata_wait_register(ap, port_mmio + PORT_CMD,
733 				PORT_CMD_LIST_ON, PORT_CMD_LIST_ON, 1, 500);
734 	if (tmp & PORT_CMD_LIST_ON)
735 		return -EIO;
736 
737 	return 0;
738 }
739 EXPORT_SYMBOL_GPL(ahci_stop_engine);
740 
741 void ahci_start_fis_rx(struct ata_port *ap)
742 {
743 	void __iomem *port_mmio = ahci_port_base(ap);
744 	struct ahci_host_priv *hpriv = ap->host->private_data;
745 	struct ahci_port_priv *pp = ap->private_data;
746 	u32 tmp;
747 
748 	/*
749 	 * On HBAs that only support 32-bit addressing PxCLBU is read only '0'.
750 	 * When applying the AHCI_HFLAG_32BIT_ONLY quirk, PxCLBU is RW, and the
751 	 * reset value is Implementation Specific, so we need to clear it to 0.
752 	 */
753 	if (hpriv->cap & HOST_CAP_64)
754 		writel((pp->cmd_slot_dma >> 16) >> 16,
755 		       port_mmio + PORT_LST_ADDR_HI);
756 	else if (hpriv->flags & AHCI_HFLAG_32BIT_ONLY)
757 		writel(0, port_mmio + PORT_LST_ADDR_HI);
758 	writel(pp->cmd_slot_dma & 0xffffffff, port_mmio + PORT_LST_ADDR);
759 
760 	/*
761 	 * On HBAs that only support 32-bit addressing PxFBU is read only '0'.
762 	 * When applying the AHCI_HFLAG_32BIT_ONLY quirk, PxFBU is RW, and the
763 	 * reset value is Implementation Specific, so we need to clear it to 0.
764 	 */
765 	if (hpriv->cap & HOST_CAP_64)
766 		writel((pp->rx_fis_dma >> 16) >> 16,
767 		       port_mmio + PORT_FIS_ADDR_HI);
768 	else if (hpriv->flags & AHCI_HFLAG_32BIT_ONLY)
769 		writel(0, port_mmio + PORT_FIS_ADDR_HI);
770 	writel(pp->rx_fis_dma & 0xffffffff, port_mmio + PORT_FIS_ADDR);
771 
772 	/* enable FIS reception */
773 	tmp = readl(port_mmio + PORT_CMD);
774 	tmp |= PORT_CMD_FIS_RX;
775 	writel(tmp, port_mmio + PORT_CMD);
776 
777 	/* flush */
778 	readl(port_mmio + PORT_CMD);
779 }
780 EXPORT_SYMBOL_GPL(ahci_start_fis_rx);
781 
782 static int ahci_stop_fis_rx(struct ata_port *ap)
783 {
784 	void __iomem *port_mmio = ahci_port_base(ap);
785 	u32 tmp;
786 
787 	/* disable FIS reception */
788 	tmp = readl(port_mmio + PORT_CMD);
789 	tmp &= ~PORT_CMD_FIS_RX;
790 	writel(tmp, port_mmio + PORT_CMD);
791 
792 	/* wait for completion, spec says 500ms, give it 1000 */
793 	tmp = ata_wait_register(ap, port_mmio + PORT_CMD, PORT_CMD_FIS_ON,
794 				PORT_CMD_FIS_ON, 10, 1000);
795 	if (tmp & PORT_CMD_FIS_ON)
796 		return -EBUSY;
797 
798 	return 0;
799 }
800 
801 static void ahci_power_up(struct ata_port *ap)
802 {
803 	struct ahci_host_priv *hpriv = ap->host->private_data;
804 	void __iomem *port_mmio = ahci_port_base(ap);
805 	u32 cmd;
806 
807 	cmd = readl(port_mmio + PORT_CMD) & ~PORT_CMD_ICC_MASK;
808 
809 	/* spin up device */
810 	if (hpriv->cap & HOST_CAP_SSS) {
811 		cmd |= PORT_CMD_SPIN_UP;
812 		writel(cmd, port_mmio + PORT_CMD);
813 	}
814 
815 	/* wake up link */
816 	writel(cmd | PORT_CMD_ICC_ACTIVE, port_mmio + PORT_CMD);
817 }
818 
819 static int ahci_set_lpm(struct ata_link *link, enum ata_lpm_policy policy,
820 			unsigned int hints)
821 {
822 	struct ata_port *ap = link->ap;
823 	struct ahci_host_priv *hpriv = ap->host->private_data;
824 	struct ahci_port_priv *pp = ap->private_data;
825 	void __iomem *port_mmio = ahci_port_base(ap);
826 
827 	if (policy != ATA_LPM_MAX_POWER) {
828 		/* wakeup flag only applies to the max power policy */
829 		hints &= ~ATA_LPM_WAKE_ONLY;
830 
831 		/*
832 		 * Disable interrupts on Phy Ready. This keeps us from
833 		 * getting woken up due to spurious phy ready
834 		 * interrupts.
835 		 */
836 		pp->intr_mask &= ~PORT_IRQ_PHYRDY;
837 		writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
838 
839 		sata_link_scr_lpm(link, policy, false);
840 	}
841 
842 	if (hpriv->cap & HOST_CAP_ALPM) {
843 		u32 cmd = readl(port_mmio + PORT_CMD);
844 
845 		if (policy == ATA_LPM_MAX_POWER || !(hints & ATA_LPM_HIPM)) {
846 			if (!(hints & ATA_LPM_WAKE_ONLY))
847 				cmd &= ~(PORT_CMD_ASP | PORT_CMD_ALPE);
848 			cmd |= PORT_CMD_ICC_ACTIVE;
849 
850 			writel(cmd, port_mmio + PORT_CMD);
851 			readl(port_mmio + PORT_CMD);
852 
853 			/* wait 10ms to be sure we've come out of LPM state */
854 			ata_msleep(ap, 10);
855 
856 			if (hints & ATA_LPM_WAKE_ONLY)
857 				return 0;
858 		} else {
859 			cmd |= PORT_CMD_ALPE;
860 			if (policy == ATA_LPM_MIN_POWER)
861 				cmd |= PORT_CMD_ASP;
862 			else if (policy == ATA_LPM_MIN_POWER_WITH_PARTIAL)
863 				cmd &= ~PORT_CMD_ASP;
864 
865 			/* write out new cmd value */
866 			writel(cmd, port_mmio + PORT_CMD);
867 		}
868 	}
869 
870 	/* set aggressive device sleep */
871 	if ((hpriv->cap2 & HOST_CAP2_SDS) &&
872 	    (hpriv->cap2 & HOST_CAP2_SADM) &&
873 	    (link->device->flags & ATA_DFLAG_DEVSLP)) {
874 		if (policy == ATA_LPM_MIN_POWER ||
875 		    policy == ATA_LPM_MIN_POWER_WITH_PARTIAL)
876 			ahci_set_aggressive_devslp(ap, true);
877 		else
878 			ahci_set_aggressive_devslp(ap, false);
879 	}
880 
881 	if (policy == ATA_LPM_MAX_POWER) {
882 		sata_link_scr_lpm(link, policy, false);
883 
884 		/* turn PHYRDY IRQ back on */
885 		pp->intr_mask |= PORT_IRQ_PHYRDY;
886 		writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
887 	}
888 
889 	return 0;
890 }
891 
892 #ifdef CONFIG_PM
893 static void ahci_power_down(struct ata_port *ap)
894 {
895 	struct ahci_host_priv *hpriv = ap->host->private_data;
896 	void __iomem *port_mmio = ahci_port_base(ap);
897 	u32 cmd, scontrol;
898 
899 	if (!(hpriv->cap & HOST_CAP_SSS))
900 		return;
901 
902 	/* put device into listen mode, first set PxSCTL.DET to 0 */
903 	scontrol = readl(port_mmio + PORT_SCR_CTL);
904 	scontrol &= ~0xf;
905 	writel(scontrol, port_mmio + PORT_SCR_CTL);
906 
907 	/* then set PxCMD.SUD to 0 */
908 	cmd = readl(port_mmio + PORT_CMD) & ~PORT_CMD_ICC_MASK;
909 	cmd &= ~PORT_CMD_SPIN_UP;
910 	writel(cmd, port_mmio + PORT_CMD);
911 }
912 #endif
913 
914 static void ahci_start_port(struct ata_port *ap)
915 {
916 	struct ahci_host_priv *hpriv = ap->host->private_data;
917 	struct ahci_port_priv *pp = ap->private_data;
918 	struct ata_link *link;
919 	struct ahci_em_priv *emp;
920 	ssize_t rc;
921 	int i;
922 
923 	/* enable FIS reception */
924 	ahci_start_fis_rx(ap);
925 
926 	/* enable DMA */
927 	if (!(hpriv->flags & AHCI_HFLAG_DELAY_ENGINE))
928 		hpriv->start_engine(ap);
929 
930 	/* turn on LEDs */
931 	if (ap->flags & ATA_FLAG_EM) {
932 		ata_for_each_link(link, ap, EDGE) {
933 			emp = &pp->em_priv[link->pmp];
934 
935 			/* EM Transmit bit maybe busy during init */
936 			for (i = 0; i < EM_MAX_RETRY; i++) {
937 				rc = ap->ops->transmit_led_message(ap,
938 							       emp->led_state,
939 							       4);
940 				/*
941 				 * If busy, give a breather but do not
942 				 * release EH ownership by using msleep()
943 				 * instead of ata_msleep().  EM Transmit
944 				 * bit is busy for the whole host and
945 				 * releasing ownership will cause other
946 				 * ports to fail the same way.
947 				 */
948 				if (rc == -EBUSY)
949 					msleep(1);
950 				else
951 					break;
952 			}
953 		}
954 	}
955 
956 	if (ap->flags & ATA_FLAG_SW_ACTIVITY)
957 		ata_for_each_link(link, ap, EDGE)
958 			ahci_init_sw_activity(link);
959 
960 }
961 
962 static int ahci_deinit_port(struct ata_port *ap, const char **emsg)
963 {
964 	int rc;
965 	struct ahci_host_priv *hpriv = ap->host->private_data;
966 
967 	/* disable DMA */
968 	rc = hpriv->stop_engine(ap);
969 	if (rc) {
970 		*emsg = "failed to stop engine";
971 		return rc;
972 	}
973 
974 	/* disable FIS reception */
975 	rc = ahci_stop_fis_rx(ap);
976 	if (rc) {
977 		*emsg = "failed stop FIS RX";
978 		return rc;
979 	}
980 
981 	return 0;
982 }
983 
984 int ahci_reset_controller(struct ata_host *host)
985 {
986 	struct ahci_host_priv *hpriv = host->private_data;
987 	void __iomem *mmio = hpriv->mmio;
988 	u32 tmp;
989 
990 	/*
991 	 * We must be in AHCI mode, before using anything AHCI-specific, such
992 	 * as HOST_RESET.
993 	 */
994 	ahci_enable_ahci(mmio);
995 
996 	/* Global controller reset */
997 	if (ahci_skip_host_reset) {
998 		dev_info(host->dev, "Skipping global host reset\n");
999 		return 0;
1000 	}
1001 
1002 	tmp = readl(mmio + HOST_CTL);
1003 	if (!(tmp & HOST_RESET)) {
1004 		writel(tmp | HOST_RESET, mmio + HOST_CTL);
1005 		readl(mmio + HOST_CTL); /* flush */
1006 	}
1007 
1008 	/*
1009 	 * To perform host reset, OS should set HOST_RESET and poll until this
1010 	 * bit is read to be "0". Reset must complete within 1 second, or the
1011 	 * hardware should be considered fried.
1012 	 */
1013 	tmp = ata_wait_register(NULL, mmio + HOST_CTL, HOST_RESET,
1014 				HOST_RESET, 10, 1000);
1015 	if (tmp & HOST_RESET) {
1016 		dev_err(host->dev, "Controller reset failed (0x%x)\n",
1017 			tmp);
1018 		return -EIO;
1019 	}
1020 
1021 	/* Turn on AHCI mode */
1022 	ahci_enable_ahci(mmio);
1023 
1024 	/* Some registers might be cleared on reset. Restore initial values. */
1025 	if (!(hpriv->flags & AHCI_HFLAG_NO_WRITE_TO_RO))
1026 		ahci_restore_initial_config(host);
1027 
1028 	return 0;
1029 }
1030 EXPORT_SYMBOL_GPL(ahci_reset_controller);
1031 
1032 static void ahci_sw_activity(struct ata_link *link)
1033 {
1034 	struct ata_port *ap = link->ap;
1035 	struct ahci_port_priv *pp = ap->private_data;
1036 	struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
1037 
1038 	if (!(link->flags & ATA_LFLAG_SW_ACTIVITY))
1039 		return;
1040 
1041 	emp->activity++;
1042 	if (!timer_pending(&emp->timer))
1043 		mod_timer(&emp->timer, jiffies + msecs_to_jiffies(10));
1044 }
1045 
1046 static void ahci_sw_activity_blink(struct timer_list *t)
1047 {
1048 	struct ahci_em_priv *emp = timer_container_of(emp, t, timer);
1049 	struct ata_link *link = emp->link;
1050 	struct ata_port *ap = link->ap;
1051 
1052 	unsigned long led_message = emp->led_state;
1053 	u32 activity_led_state;
1054 	unsigned long flags;
1055 
1056 	led_message &= EM_MSG_LED_VALUE;
1057 	led_message |= ap->port_no | (link->pmp << 8);
1058 
1059 	/* check to see if we've had activity.  If so,
1060 	 * toggle state of LED and reset timer.  If not,
1061 	 * turn LED to desired idle state.
1062 	 */
1063 	spin_lock_irqsave(ap->lock, flags);
1064 	if (emp->saved_activity != emp->activity) {
1065 		emp->saved_activity = emp->activity;
1066 		/* get the current LED state */
1067 		activity_led_state = led_message & EM_MSG_LED_VALUE_ON;
1068 
1069 		if (activity_led_state)
1070 			activity_led_state = 0;
1071 		else
1072 			activity_led_state = 1;
1073 
1074 		/* clear old state */
1075 		led_message &= ~EM_MSG_LED_VALUE_ACTIVITY;
1076 
1077 		/* toggle state */
1078 		led_message |= (activity_led_state << 16);
1079 		mod_timer(&emp->timer, jiffies + msecs_to_jiffies(100));
1080 	} else {
1081 		/* switch to idle */
1082 		led_message &= ~EM_MSG_LED_VALUE_ACTIVITY;
1083 		if (emp->blink_policy == BLINK_OFF)
1084 			led_message |= (1 << 16);
1085 	}
1086 	spin_unlock_irqrestore(ap->lock, flags);
1087 	ap->ops->transmit_led_message(ap, led_message, 4);
1088 }
1089 
1090 static void ahci_init_sw_activity(struct ata_link *link)
1091 {
1092 	struct ata_port *ap = link->ap;
1093 	struct ahci_port_priv *pp = ap->private_data;
1094 	struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
1095 
1096 	/* init activity stats, setup timer */
1097 	emp->saved_activity = emp->activity = 0;
1098 	emp->link = link;
1099 	timer_setup(&emp->timer, ahci_sw_activity_blink, 0);
1100 
1101 	/* check our blink policy and set flag for link if it's enabled */
1102 	if (emp->blink_policy)
1103 		link->flags |= ATA_LFLAG_SW_ACTIVITY;
1104 }
1105 
1106 int ahci_reset_em(struct ata_host *host)
1107 {
1108 	struct ahci_host_priv *hpriv = host->private_data;
1109 	void __iomem *mmio = hpriv->mmio;
1110 	u32 em_ctl;
1111 
1112 	em_ctl = readl(mmio + HOST_EM_CTL);
1113 	if ((em_ctl & EM_CTL_TM) || (em_ctl & EM_CTL_RST))
1114 		return -EINVAL;
1115 
1116 	writel(em_ctl | EM_CTL_RST, mmio + HOST_EM_CTL);
1117 	return 0;
1118 }
1119 EXPORT_SYMBOL_GPL(ahci_reset_em);
1120 
1121 static ssize_t ahci_transmit_led_message(struct ata_port *ap, u32 state,
1122 					ssize_t size)
1123 {
1124 	struct ahci_host_priv *hpriv = ap->host->private_data;
1125 	struct ahci_port_priv *pp = ap->private_data;
1126 	void __iomem *mmio = hpriv->mmio;
1127 	u32 em_ctl;
1128 	u32 message[] = {0, 0};
1129 	unsigned long flags;
1130 	int pmp;
1131 	struct ahci_em_priv *emp;
1132 
1133 	/* get the slot number from the message */
1134 	pmp = (state & EM_MSG_LED_PMP_SLOT) >> 8;
1135 	if (pmp < EM_MAX_SLOTS)
1136 		emp = &pp->em_priv[pmp];
1137 	else
1138 		return -EINVAL;
1139 
1140 	ahci_rpm_get_port(ap);
1141 	spin_lock_irqsave(ap->lock, flags);
1142 
1143 	/*
1144 	 * if we are still busy transmitting a previous message,
1145 	 * do not allow
1146 	 */
1147 	em_ctl = readl(mmio + HOST_EM_CTL);
1148 	if (em_ctl & EM_CTL_TM) {
1149 		spin_unlock_irqrestore(ap->lock, flags);
1150 		ahci_rpm_put_port(ap);
1151 		return -EBUSY;
1152 	}
1153 
1154 	if (hpriv->em_msg_type & EM_MSG_TYPE_LED) {
1155 		/*
1156 		 * create message header - this is all zero except for
1157 		 * the message size, which is 4 bytes.
1158 		 */
1159 		message[0] |= (4 << 8);
1160 
1161 		/* ignore 0:4 of byte zero, fill in port info yourself */
1162 		message[1] = ((state & ~EM_MSG_LED_HBA_PORT) | ap->port_no);
1163 
1164 		/* write message to EM_LOC */
1165 		writel(message[0], mmio + hpriv->em_loc);
1166 		writel(message[1], mmio + hpriv->em_loc+4);
1167 
1168 		/*
1169 		 * tell hardware to transmit the message
1170 		 */
1171 		writel(em_ctl | EM_CTL_TM, mmio + HOST_EM_CTL);
1172 	}
1173 
1174 	/* save off new led state for port/slot */
1175 	emp->led_state = state;
1176 
1177 	spin_unlock_irqrestore(ap->lock, flags);
1178 	ahci_rpm_put_port(ap);
1179 
1180 	return size;
1181 }
1182 
1183 static ssize_t ahci_led_show(struct ata_port *ap, char *buf)
1184 {
1185 	struct ahci_port_priv *pp = ap->private_data;
1186 	struct ata_link *link;
1187 	struct ahci_em_priv *emp;
1188 	int rc = 0;
1189 
1190 	ata_for_each_link(link, ap, EDGE) {
1191 		emp = &pp->em_priv[link->pmp];
1192 		rc += sprintf(buf, "%lx\n", emp->led_state);
1193 	}
1194 	return rc;
1195 }
1196 
1197 static ssize_t ahci_led_store(struct ata_port *ap, const char *buf,
1198 				size_t size)
1199 {
1200 	unsigned int state;
1201 	int pmp;
1202 	struct ahci_port_priv *pp = ap->private_data;
1203 	struct ahci_em_priv *emp;
1204 
1205 	if (kstrtouint(buf, 0, &state) < 0)
1206 		return -EINVAL;
1207 
1208 	/* get the slot number from the message */
1209 	pmp = (state & EM_MSG_LED_PMP_SLOT) >> 8;
1210 	if (pmp < EM_MAX_SLOTS) {
1211 		pmp = array_index_nospec(pmp, EM_MAX_SLOTS);
1212 		emp = &pp->em_priv[pmp];
1213 	} else {
1214 		return -EINVAL;
1215 	}
1216 
1217 	/* mask off the activity bits if we are in sw_activity
1218 	 * mode, user should turn off sw_activity before setting
1219 	 * activity led through em_message
1220 	 */
1221 	if (emp->blink_policy)
1222 		state &= ~EM_MSG_LED_VALUE_ACTIVITY;
1223 
1224 	return ap->ops->transmit_led_message(ap, state, size);
1225 }
1226 
1227 static ssize_t ahci_activity_store(struct ata_device *dev, enum sw_activity val)
1228 {
1229 	struct ata_link *link = dev->link;
1230 	struct ata_port *ap = link->ap;
1231 	struct ahci_port_priv *pp = ap->private_data;
1232 	struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
1233 	u32 port_led_state = emp->led_state;
1234 
1235 	/* save the desired Activity LED behavior */
1236 	if (val == OFF) {
1237 		/* clear LFLAG */
1238 		link->flags &= ~(ATA_LFLAG_SW_ACTIVITY);
1239 
1240 		/* set the LED to OFF */
1241 		port_led_state &= EM_MSG_LED_VALUE_OFF;
1242 		port_led_state |= (ap->port_no | (link->pmp << 8));
1243 		ap->ops->transmit_led_message(ap, port_led_state, 4);
1244 	} else {
1245 		link->flags |= ATA_LFLAG_SW_ACTIVITY;
1246 		if (val == BLINK_OFF) {
1247 			/* set LED to ON for idle */
1248 			port_led_state &= EM_MSG_LED_VALUE_OFF;
1249 			port_led_state |= (ap->port_no | (link->pmp << 8));
1250 			port_led_state |= EM_MSG_LED_VALUE_ON; /* check this */
1251 			ap->ops->transmit_led_message(ap, port_led_state, 4);
1252 		}
1253 	}
1254 	emp->blink_policy = val;
1255 	return 0;
1256 }
1257 
1258 static ssize_t ahci_activity_show(struct ata_device *dev, char *buf)
1259 {
1260 	struct ata_link *link = dev->link;
1261 	struct ata_port *ap = link->ap;
1262 	struct ahci_port_priv *pp = ap->private_data;
1263 	struct ahci_em_priv *emp = &pp->em_priv[link->pmp];
1264 
1265 	/* display the saved value of activity behavior for this
1266 	 * disk.
1267 	 */
1268 	return sprintf(buf, "%d\n", emp->blink_policy);
1269 }
1270 
1271 static void ahci_port_clear_pending_irq(struct ata_port *ap)
1272 {
1273 	struct ahci_host_priv *hpriv = ap->host->private_data;
1274 	void __iomem *port_mmio = ahci_port_base(ap);
1275 	u32 tmp;
1276 
1277 	/* clear SError */
1278 	tmp = readl(port_mmio + PORT_SCR_ERR);
1279 	dev_dbg(ap->host->dev, "PORT_SCR_ERR 0x%x\n", tmp);
1280 	writel(tmp, port_mmio + PORT_SCR_ERR);
1281 
1282 	/* clear port IRQ */
1283 	tmp = readl(port_mmio + PORT_IRQ_STAT);
1284 	dev_dbg(ap->host->dev, "PORT_IRQ_STAT 0x%x\n", tmp);
1285 	if (tmp)
1286 		writel(tmp, port_mmio + PORT_IRQ_STAT);
1287 
1288 	writel(1 << ap->port_no, hpriv->mmio + HOST_IRQ_STAT);
1289 }
1290 
1291 static void ahci_port_init(struct device *dev, struct ata_port *ap,
1292 			   int port_no, void __iomem *mmio,
1293 			   void __iomem *port_mmio)
1294 {
1295 	const char *emsg = NULL;
1296 	int rc;
1297 
1298 	/* make sure port is not active */
1299 	rc = ahci_deinit_port(ap, &emsg);
1300 	if (rc)
1301 		dev_warn(dev, "%s (%d)\n", emsg, rc);
1302 
1303 	ahci_port_clear_pending_irq(ap);
1304 }
1305 
1306 void ahci_init_controller(struct ata_host *host)
1307 {
1308 	struct ahci_host_priv *hpriv = host->private_data;
1309 	void __iomem *mmio = hpriv->mmio;
1310 	int i;
1311 	void __iomem *port_mmio;
1312 	u32 tmp;
1313 
1314 	for (i = 0; i < host->n_ports; i++) {
1315 		struct ata_port *ap = host->ports[i];
1316 
1317 		port_mmio = ahci_port_base(ap);
1318 		if (ata_port_is_dummy(ap))
1319 			continue;
1320 
1321 		ahci_port_init(host->dev, ap, i, mmio, port_mmio);
1322 	}
1323 
1324 	tmp = readl(mmio + HOST_CTL);
1325 	dev_dbg(host->dev, "HOST_CTL 0x%x\n", tmp);
1326 	writel(tmp | HOST_IRQ_EN, mmio + HOST_CTL);
1327 	tmp = readl(mmio + HOST_CTL);
1328 	dev_dbg(host->dev, "HOST_CTL 0x%x\n", tmp);
1329 }
1330 EXPORT_SYMBOL_GPL(ahci_init_controller);
1331 
1332 static void ahci_dev_config(struct ata_device *dev)
1333 {
1334 	struct ahci_host_priv *hpriv = dev->link->ap->host->private_data;
1335 
1336 	if ((dev->class == ATA_DEV_ATAPI) &&
1337 	    (hpriv->flags & AHCI_HFLAG_ATAPI_DMA_QUIRK))
1338 		dev->quirks |= ATA_QUIRK_ATAPI_MOD16_DMA;
1339 
1340 	if (hpriv->flags & AHCI_HFLAG_SECT255) {
1341 		dev->max_sectors = 255;
1342 		ata_dev_info(dev,
1343 			     "SB600 AHCI: limiting to 255 sectors per cmd\n");
1344 	}
1345 }
1346 
1347 unsigned int ahci_dev_classify(struct ata_port *ap)
1348 {
1349 	void __iomem *port_mmio = ahci_port_base(ap);
1350 	struct ata_taskfile tf;
1351 	u32 tmp;
1352 
1353 	tmp = readl(port_mmio + PORT_SIG);
1354 	tf.lbah		= (tmp >> 24)	& 0xff;
1355 	tf.lbam		= (tmp >> 16)	& 0xff;
1356 	tf.lbal		= (tmp >> 8)	& 0xff;
1357 	tf.nsect	= (tmp)		& 0xff;
1358 
1359 	return ata_port_classify(ap, &tf);
1360 }
1361 EXPORT_SYMBOL_GPL(ahci_dev_classify);
1362 
1363 void ahci_fill_cmd_slot(struct ahci_port_priv *pp, unsigned int tag,
1364 			u32 opts)
1365 {
1366 	dma_addr_t cmd_tbl_dma;
1367 
1368 	cmd_tbl_dma = pp->cmd_tbl_dma + tag * AHCI_CMD_TBL_SZ;
1369 
1370 	pp->cmd_slot[tag].opts = cpu_to_le32(opts);
1371 	pp->cmd_slot[tag].status = 0;
1372 	pp->cmd_slot[tag].tbl_addr = cpu_to_le32(cmd_tbl_dma & 0xffffffff);
1373 	pp->cmd_slot[tag].tbl_addr_hi = cpu_to_le32((cmd_tbl_dma >> 16) >> 16);
1374 }
1375 EXPORT_SYMBOL_GPL(ahci_fill_cmd_slot);
1376 
1377 int ahci_kick_engine(struct ata_port *ap)
1378 {
1379 	void __iomem *port_mmio = ahci_port_base(ap);
1380 	struct ahci_host_priv *hpriv = ap->host->private_data;
1381 	u8 status = readl(port_mmio + PORT_TFDATA) & 0xFF;
1382 	u32 tmp;
1383 	int busy, rc;
1384 
1385 	/* stop engine */
1386 	rc = hpriv->stop_engine(ap);
1387 	if (rc)
1388 		goto out_restart;
1389 
1390 	/* need to do CLO?
1391 	 * always do CLO if PMP is attached (AHCI-1.3 9.2)
1392 	 */
1393 	busy = status & (ATA_BUSY | ATA_DRQ);
1394 	if (!busy && !sata_pmp_attached(ap)) {
1395 		rc = 0;
1396 		goto out_restart;
1397 	}
1398 
1399 	if (!(hpriv->cap & HOST_CAP_CLO)) {
1400 		rc = -EOPNOTSUPP;
1401 		goto out_restart;
1402 	}
1403 
1404 	/* perform CLO */
1405 	tmp = readl(port_mmio + PORT_CMD);
1406 	tmp |= PORT_CMD_CLO;
1407 	writel(tmp, port_mmio + PORT_CMD);
1408 
1409 	rc = 0;
1410 	tmp = ata_wait_register(ap, port_mmio + PORT_CMD,
1411 				PORT_CMD_CLO, PORT_CMD_CLO, 1, 500);
1412 	if (tmp & PORT_CMD_CLO)
1413 		rc = -EIO;
1414 
1415 	/* restart engine */
1416  out_restart:
1417 	hpriv->start_engine(ap);
1418 	return rc;
1419 }
1420 EXPORT_SYMBOL_GPL(ahci_kick_engine);
1421 
1422 static int ahci_exec_polled_cmd(struct ata_port *ap, int pmp,
1423 				struct ata_taskfile *tf, int is_cmd, u16 flags,
1424 				unsigned int timeout_msec)
1425 {
1426 	const u32 cmd_fis_len = 5; /* five dwords */
1427 	struct ahci_port_priv *pp = ap->private_data;
1428 	void __iomem *port_mmio = ahci_port_base(ap);
1429 	u8 *fis = pp->cmd_tbl;
1430 	u32 tmp;
1431 
1432 	/* prep the command */
1433 	ata_tf_to_fis(tf, pmp, is_cmd, fis);
1434 	ahci_fill_cmd_slot(pp, 0, cmd_fis_len | flags | (pmp << 12));
1435 
1436 	/* set port value for softreset of Port Multiplier */
1437 	if (pp->fbs_enabled && pp->fbs_last_dev != pmp) {
1438 		tmp = readl(port_mmio + PORT_FBS);
1439 		tmp &= ~(PORT_FBS_DEV_MASK | PORT_FBS_DEC);
1440 		tmp |= pmp << PORT_FBS_DEV_OFFSET;
1441 		writel(tmp, port_mmio + PORT_FBS);
1442 		pp->fbs_last_dev = pmp;
1443 	}
1444 
1445 	/* issue & wait */
1446 	writel(1, port_mmio + PORT_CMD_ISSUE);
1447 
1448 	if (timeout_msec) {
1449 		tmp = ata_wait_register(ap, port_mmio + PORT_CMD_ISSUE,
1450 					0x1, 0x1, 1, timeout_msec);
1451 		if (tmp & 0x1) {
1452 			ahci_kick_engine(ap);
1453 			return -EBUSY;
1454 		}
1455 	} else
1456 		readl(port_mmio + PORT_CMD_ISSUE);	/* flush */
1457 
1458 	return 0;
1459 }
1460 
1461 int ahci_do_softreset(struct ata_link *link, unsigned int *class,
1462 		      int pmp, unsigned long deadline,
1463 		      int (*check_ready)(struct ata_link *link))
1464 {
1465 	struct ata_port *ap = link->ap;
1466 	struct ahci_host_priv *hpriv = ap->host->private_data;
1467 	struct ahci_port_priv *pp = ap->private_data;
1468 	const char *reason = NULL;
1469 	unsigned long now;
1470 	unsigned int msecs;
1471 	struct ata_taskfile tf;
1472 	bool fbs_disabled = false;
1473 	int rc;
1474 
1475 	/* prepare for SRST (AHCI-1.1 10.4.1) */
1476 	rc = ahci_kick_engine(ap);
1477 	if (rc && rc != -EOPNOTSUPP)
1478 		ata_link_warn(link, "failed to reset engine (errno=%d)\n", rc);
1479 
1480 	/*
1481 	 * According to AHCI-1.2 9.3.9: if FBS is enable, software shall
1482 	 * clear PxFBS.EN to '0' prior to issuing software reset to devices
1483 	 * that is attached to port multiplier.
1484 	 */
1485 	if (!ata_is_host_link(link) && pp->fbs_enabled) {
1486 		ahci_disable_fbs(ap);
1487 		fbs_disabled = true;
1488 	}
1489 
1490 	ata_tf_init(link->device, &tf);
1491 
1492 	/* issue the first H2D Register FIS */
1493 	msecs = 0;
1494 	now = jiffies;
1495 	if (time_after(deadline, now))
1496 		msecs = jiffies_to_msecs(deadline - now);
1497 
1498 	tf.ctl |= ATA_SRST;
1499 	if (ahci_exec_polled_cmd(ap, pmp, &tf, 0,
1500 				 AHCI_CMD_RESET | AHCI_CMD_CLR_BUSY, msecs)) {
1501 		rc = -EIO;
1502 		reason = "1st FIS failed";
1503 		goto fail;
1504 	}
1505 
1506 	/* spec says at least 5us, but be generous and sleep for 1ms */
1507 	ata_msleep(ap, 1);
1508 
1509 	/* issue the second H2D Register FIS */
1510 	tf.ctl &= ~ATA_SRST;
1511 	ahci_exec_polled_cmd(ap, pmp, &tf, 0, 0, 0);
1512 
1513 	/* wait for link to become ready */
1514 	rc = ata_wait_after_reset(link, deadline, check_ready);
1515 	if (rc == -EBUSY && hpriv->flags & AHCI_HFLAG_SRST_TOUT_IS_OFFLINE) {
1516 		/*
1517 		 * Workaround for cases where link online status can't
1518 		 * be trusted.  Treat device readiness timeout as link
1519 		 * offline.
1520 		 */
1521 		ata_link_info(link, "device not ready, treating as offline\n");
1522 		*class = ATA_DEV_NONE;
1523 	} else if (rc) {
1524 		/* link occupied, -ENODEV too is an error */
1525 		reason = "device not ready";
1526 		goto fail;
1527 	} else
1528 		*class = ahci_dev_classify(ap);
1529 
1530 	/* re-enable FBS if disabled before */
1531 	if (fbs_disabled)
1532 		ahci_enable_fbs(ap);
1533 
1534 	return 0;
1535 
1536  fail:
1537 	ata_link_err(link, "softreset failed (%s)\n", reason);
1538 	return rc;
1539 }
1540 EXPORT_SYMBOL_GPL(ahci_do_softreset);
1541 
1542 int ahci_check_ready(struct ata_link *link)
1543 {
1544 	void __iomem *port_mmio = ahci_port_base(link->ap);
1545 	u8 status = readl(port_mmio + PORT_TFDATA) & 0xFF;
1546 
1547 	return ata_check_ready(status);
1548 }
1549 EXPORT_SYMBOL_GPL(ahci_check_ready);
1550 
1551 static int ahci_softreset(struct ata_link *link, unsigned int *class,
1552 			  unsigned long deadline)
1553 {
1554 	int pmp = sata_srst_pmp(link);
1555 
1556 	return ahci_do_softreset(link, class, pmp, deadline, ahci_check_ready);
1557 }
1558 
1559 static int ahci_bad_pmp_check_ready(struct ata_link *link)
1560 {
1561 	void __iomem *port_mmio = ahci_port_base(link->ap);
1562 	u8 status = readl(port_mmio + PORT_TFDATA) & 0xFF;
1563 	u32 irq_status = readl(port_mmio + PORT_IRQ_STAT);
1564 
1565 	/*
1566 	 * There is no need to check TFDATA if BAD PMP is found due to HW bug,
1567 	 * which can save timeout delay.
1568 	 */
1569 	if (irq_status & PORT_IRQ_BAD_PMP)
1570 		return -EIO;
1571 
1572 	return ata_check_ready(status);
1573 }
1574 
1575 static int ahci_pmp_retry_softreset(struct ata_link *link, unsigned int *class,
1576 				    unsigned long deadline)
1577 {
1578 	struct ata_port *ap = link->ap;
1579 	void __iomem *port_mmio = ahci_port_base(ap);
1580 	int pmp = sata_srst_pmp(link);
1581 	int rc;
1582 	u32 irq_sts;
1583 
1584 	rc = ahci_do_softreset(link, class, pmp, deadline,
1585 			       ahci_bad_pmp_check_ready);
1586 
1587 	/*
1588 	 * Soft reset fails with IPMS set when PMP is enabled but
1589 	 * SATA HDD/ODD is connected to SATA port, do soft reset
1590 	 * again to port 0.
1591 	 */
1592 	if (rc == -EIO) {
1593 		irq_sts = readl(port_mmio + PORT_IRQ_STAT);
1594 		if (irq_sts & PORT_IRQ_BAD_PMP) {
1595 			ata_link_warn(link,
1596 					"applying PMP SRST workaround "
1597 					"and retrying\n");
1598 			rc = ahci_do_softreset(link, class, 0, deadline,
1599 					       ahci_check_ready);
1600 		}
1601 	}
1602 
1603 	return rc;
1604 }
1605 
1606 int ahci_do_hardreset(struct ata_link *link, unsigned int *class,
1607 		      unsigned long deadline, bool *online)
1608 {
1609 	const unsigned int *timing = sata_ehc_deb_timing(&link->eh_context);
1610 	struct ata_port *ap = link->ap;
1611 	struct ahci_port_priv *pp = ap->private_data;
1612 	struct ahci_host_priv *hpriv = ap->host->private_data;
1613 	u8 *d2h_fis = pp->rx_fis + RX_FIS_D2H_REG;
1614 	struct ata_taskfile tf;
1615 	int rc;
1616 
1617 	hpriv->stop_engine(ap);
1618 
1619 	/* clear D2H reception area to properly wait for D2H FIS */
1620 	ata_tf_init(link->device, &tf);
1621 	tf.status = ATA_BUSY;
1622 	ata_tf_to_fis(&tf, 0, 0, d2h_fis);
1623 
1624 	ahci_port_clear_pending_irq(ap);
1625 
1626 	rc = sata_link_hardreset(link, timing, deadline, online,
1627 				 ahci_check_ready);
1628 
1629 	hpriv->start_engine(ap);
1630 
1631 	if (*online)
1632 		*class = ahci_dev_classify(ap);
1633 
1634 	return rc;
1635 }
1636 EXPORT_SYMBOL_GPL(ahci_do_hardreset);
1637 
1638 static int ahci_hardreset(struct ata_link *link, unsigned int *class,
1639 			  unsigned long deadline)
1640 {
1641 	bool online;
1642 
1643 	return ahci_do_hardreset(link, class, deadline, &online);
1644 }
1645 
1646 static void ahci_postreset(struct ata_link *link, unsigned int *class)
1647 {
1648 	struct ata_port *ap = link->ap;
1649 	void __iomem *port_mmio = ahci_port_base(ap);
1650 	u32 new_tmp, tmp;
1651 
1652 	ata_std_postreset(link, class);
1653 
1654 	/* Make sure port's ATAPI bit is set appropriately */
1655 	new_tmp = tmp = readl(port_mmio + PORT_CMD);
1656 	if (*class == ATA_DEV_ATAPI)
1657 		new_tmp |= PORT_CMD_ATAPI;
1658 	else
1659 		new_tmp &= ~PORT_CMD_ATAPI;
1660 	if (new_tmp != tmp) {
1661 		writel(new_tmp, port_mmio + PORT_CMD);
1662 		readl(port_mmio + PORT_CMD); /* flush */
1663 	}
1664 }
1665 
1666 static unsigned int ahci_fill_sg(struct ata_queued_cmd *qc, void *cmd_tbl)
1667 {
1668 	struct scatterlist *sg;
1669 	struct ahci_sg *ahci_sg = cmd_tbl + AHCI_CMD_TBL_HDR_SZ;
1670 	unsigned int si;
1671 
1672 	/*
1673 	 * Next, the S/G list.
1674 	 */
1675 	for_each_sg(qc->sg, sg, qc->n_elem, si) {
1676 		dma_addr_t addr = sg_dma_address(sg);
1677 		u32 sg_len = sg_dma_len(sg);
1678 
1679 		ahci_sg[si].addr = cpu_to_le32(addr & 0xffffffff);
1680 		ahci_sg[si].addr_hi = cpu_to_le32((addr >> 16) >> 16);
1681 		ahci_sg[si].flags_size = cpu_to_le32(sg_len - 1);
1682 	}
1683 
1684 	return si;
1685 }
1686 
1687 static int ahci_pmp_qc_defer(struct ata_queued_cmd *qc)
1688 {
1689 	struct ata_port *ap = qc->ap;
1690 	struct ahci_port_priv *pp = ap->private_data;
1691 
1692 	if (!sata_pmp_attached(ap) || pp->fbs_enabled)
1693 		return ata_std_qc_defer(qc);
1694 	else
1695 		return sata_pmp_qc_defer_cmd_switch(qc);
1696 }
1697 
1698 static enum ata_completion_errors ahci_qc_prep(struct ata_queued_cmd *qc)
1699 {
1700 	struct ata_port *ap = qc->ap;
1701 	struct ahci_port_priv *pp = ap->private_data;
1702 	int is_atapi = ata_is_atapi(qc->tf.protocol);
1703 	void *cmd_tbl;
1704 	u32 opts;
1705 	const u32 cmd_fis_len = 5; /* five dwords */
1706 	unsigned int n_elem;
1707 
1708 	/*
1709 	 * Fill in command table information.  First, the header,
1710 	 * a SATA Register - Host to Device command FIS.
1711 	 */
1712 	cmd_tbl = pp->cmd_tbl + qc->hw_tag * AHCI_CMD_TBL_SZ;
1713 
1714 	ata_tf_to_fis(&qc->tf, qc->dev->link->pmp, 1, cmd_tbl);
1715 	if (is_atapi) {
1716 		memset(cmd_tbl + AHCI_CMD_TBL_CDB, 0, 32);
1717 		memcpy(cmd_tbl + AHCI_CMD_TBL_CDB, qc->cdb, qc->dev->cdb_len);
1718 	}
1719 
1720 	n_elem = 0;
1721 	if (qc->flags & ATA_QCFLAG_DMAMAP)
1722 		n_elem = ahci_fill_sg(qc, cmd_tbl);
1723 
1724 	/*
1725 	 * Fill in command slot information.
1726 	 */
1727 	opts = cmd_fis_len | n_elem << 16 | (qc->dev->link->pmp << 12);
1728 	if (qc->tf.flags & ATA_TFLAG_WRITE)
1729 		opts |= AHCI_CMD_WRITE;
1730 	if (is_atapi)
1731 		opts |= AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH;
1732 
1733 	ahci_fill_cmd_slot(pp, qc->hw_tag, opts);
1734 
1735 	return AC_ERR_OK;
1736 }
1737 
1738 static void ahci_fbs_dec_intr(struct ata_port *ap)
1739 {
1740 	struct ahci_port_priv *pp = ap->private_data;
1741 	void __iomem *port_mmio = ahci_port_base(ap);
1742 	u32 fbs = readl(port_mmio + PORT_FBS);
1743 	int retries = 3;
1744 
1745 	BUG_ON(!pp->fbs_enabled);
1746 
1747 	/* time to wait for DEC is not specified by AHCI spec,
1748 	 * add a retry loop for safety.
1749 	 */
1750 	writel(fbs | PORT_FBS_DEC, port_mmio + PORT_FBS);
1751 	fbs = readl(port_mmio + PORT_FBS);
1752 	while ((fbs & PORT_FBS_DEC) && retries--) {
1753 		udelay(1);
1754 		fbs = readl(port_mmio + PORT_FBS);
1755 	}
1756 
1757 	if (fbs & PORT_FBS_DEC)
1758 		dev_err(ap->host->dev, "failed to clear device error\n");
1759 }
1760 
1761 static void ahci_error_intr(struct ata_port *ap, u32 irq_stat)
1762 {
1763 	struct ahci_host_priv *hpriv = ap->host->private_data;
1764 	struct ahci_port_priv *pp = ap->private_data;
1765 	struct ata_eh_info *host_ehi = &ap->link.eh_info;
1766 	struct ata_link *link = NULL;
1767 	struct ata_queued_cmd *active_qc;
1768 	struct ata_eh_info *active_ehi;
1769 	bool fbs_need_dec = false;
1770 	u32 serror;
1771 
1772 	/* determine active link with error */
1773 	if (pp->fbs_enabled) {
1774 		void __iomem *port_mmio = ahci_port_base(ap);
1775 		u32 fbs = readl(port_mmio + PORT_FBS);
1776 		int pmp = fbs >> PORT_FBS_DWE_OFFSET;
1777 
1778 		if ((fbs & PORT_FBS_SDE) && (pmp < ap->nr_pmp_links)) {
1779 			link = &ap->pmp_link[pmp];
1780 			fbs_need_dec = true;
1781 		}
1782 
1783 	} else
1784 		ata_for_each_link(link, ap, EDGE)
1785 			if (ata_link_active(link))
1786 				break;
1787 
1788 	if (!link)
1789 		link = &ap->link;
1790 
1791 	active_qc = ata_qc_from_tag(ap, link->active_tag);
1792 	active_ehi = &link->eh_info;
1793 
1794 	/* record irq stat */
1795 	ata_ehi_clear_desc(host_ehi);
1796 	ata_ehi_push_desc(host_ehi, "irq_stat 0x%08x", irq_stat);
1797 
1798 	/* AHCI needs SError cleared; otherwise, it might lock up */
1799 	ahci_scr_read(&ap->link, SCR_ERROR, &serror);
1800 	ahci_scr_write(&ap->link, SCR_ERROR, serror);
1801 	host_ehi->serror |= serror;
1802 
1803 	/* some controllers set IRQ_IF_ERR on device errors, ignore it */
1804 	if (hpriv->flags & AHCI_HFLAG_IGN_IRQ_IF_ERR)
1805 		irq_stat &= ~PORT_IRQ_IF_ERR;
1806 
1807 	if (irq_stat & PORT_IRQ_TF_ERR) {
1808 		/* If qc is active, charge it; otherwise, the active
1809 		 * link.  There's no active qc on NCQ errors.  It will
1810 		 * be determined by EH by reading log page 10h.
1811 		 */
1812 		if (active_qc)
1813 			active_qc->err_mask |= AC_ERR_DEV;
1814 		else
1815 			active_ehi->err_mask |= AC_ERR_DEV;
1816 
1817 		if (hpriv->flags & AHCI_HFLAG_IGN_SERR_INTERNAL)
1818 			host_ehi->serror &= ~SERR_INTERNAL;
1819 	}
1820 
1821 	if (irq_stat & PORT_IRQ_UNK_FIS) {
1822 		u32 *unk = pp->rx_fis + RX_FIS_UNK;
1823 
1824 		active_ehi->err_mask |= AC_ERR_HSM;
1825 		active_ehi->action |= ATA_EH_RESET;
1826 		ata_ehi_push_desc(active_ehi,
1827 				  "unknown FIS %08x %08x %08x %08x" ,
1828 				  unk[0], unk[1], unk[2], unk[3]);
1829 	}
1830 
1831 	if (sata_pmp_attached(ap) && (irq_stat & PORT_IRQ_BAD_PMP)) {
1832 		active_ehi->err_mask |= AC_ERR_HSM;
1833 		active_ehi->action |= ATA_EH_RESET;
1834 		ata_ehi_push_desc(active_ehi, "incorrect PMP");
1835 	}
1836 
1837 	if (irq_stat & (PORT_IRQ_HBUS_ERR | PORT_IRQ_HBUS_DATA_ERR)) {
1838 		host_ehi->err_mask |= AC_ERR_HOST_BUS;
1839 		host_ehi->action |= ATA_EH_RESET;
1840 		ata_ehi_push_desc(host_ehi, "host bus error");
1841 	}
1842 
1843 	if (irq_stat & PORT_IRQ_IF_ERR) {
1844 		if (fbs_need_dec)
1845 			active_ehi->err_mask |= AC_ERR_DEV;
1846 		else {
1847 			host_ehi->err_mask |= AC_ERR_ATA_BUS;
1848 			host_ehi->action |= ATA_EH_RESET;
1849 		}
1850 
1851 		ata_ehi_push_desc(host_ehi, "interface fatal error");
1852 	}
1853 
1854 	if (irq_stat & (PORT_IRQ_CONNECT | PORT_IRQ_PHYRDY)) {
1855 		ata_ehi_hotplugged(host_ehi);
1856 		ata_ehi_push_desc(host_ehi, "%s",
1857 			irq_stat & PORT_IRQ_CONNECT ?
1858 			"connection status changed" : "PHY RDY changed");
1859 	}
1860 
1861 	/* okay, let's hand over to EH */
1862 
1863 	if (irq_stat & PORT_IRQ_FREEZE)
1864 		ata_port_freeze(ap);
1865 	else if (fbs_need_dec) {
1866 		ata_link_abort(link);
1867 		ahci_fbs_dec_intr(ap);
1868 	} else
1869 		ata_port_abort(ap);
1870 }
1871 
1872 static void ahci_qc_complete(struct ata_port *ap, void __iomem *port_mmio)
1873 {
1874 	struct ata_eh_info *ehi = &ap->link.eh_info;
1875 	struct ahci_port_priv *pp = ap->private_data;
1876 	u32 qc_active = 0;
1877 	int rc;
1878 
1879 	/*
1880 	 * pp->active_link is not reliable once FBS is enabled, both
1881 	 * PORT_SCR_ACT and PORT_CMD_ISSUE should be checked because
1882 	 * NCQ and non-NCQ commands may be in flight at the same time.
1883 	 */
1884 	if (pp->fbs_enabled) {
1885 		if (ap->qc_active) {
1886 			qc_active = readl(port_mmio + PORT_SCR_ACT);
1887 			qc_active |= readl(port_mmio + PORT_CMD_ISSUE);
1888 		}
1889 	} else {
1890 		/* pp->active_link is valid iff any command is in flight */
1891 		if (ap->qc_active && pp->active_link->sactive)
1892 			qc_active = readl(port_mmio + PORT_SCR_ACT);
1893 		else
1894 			qc_active = readl(port_mmio + PORT_CMD_ISSUE);
1895 	}
1896 
1897 	rc = ata_qc_complete_multiple(ap, qc_active);
1898 	if (unlikely(rc < 0 && !(ap->pflags & ATA_PFLAG_RESETTING))) {
1899 		ehi->err_mask |= AC_ERR_HSM;
1900 		ehi->action |= ATA_EH_RESET;
1901 		ata_port_freeze(ap);
1902 	}
1903 }
1904 
1905 static void ahci_handle_port_interrupt(struct ata_port *ap,
1906 				       void __iomem *port_mmio, u32 status)
1907 {
1908 	struct ahci_port_priv *pp = ap->private_data;
1909 	struct ahci_host_priv *hpriv = ap->host->private_data;
1910 
1911 	/* ignore BAD_PMP while resetting */
1912 	if (unlikely(ap->pflags & ATA_PFLAG_RESETTING))
1913 		status &= ~PORT_IRQ_BAD_PMP;
1914 
1915 	if (sata_lpm_ignore_phy_events(&ap->link)) {
1916 		status &= ~PORT_IRQ_PHYRDY;
1917 		ahci_scr_write(&ap->link, SCR_ERROR, SERR_PHYRDY_CHG);
1918 	}
1919 
1920 	if (unlikely(status & PORT_IRQ_ERROR)) {
1921 		/*
1922 		 * Before getting the error notification, we may have
1923 		 * received SDB FISes notifying successful completions.
1924 		 * Handle these first and then handle the error.
1925 		 */
1926 		ahci_qc_complete(ap, port_mmio);
1927 		ahci_error_intr(ap, status);
1928 		return;
1929 	}
1930 
1931 	if (status & PORT_IRQ_SDB_FIS) {
1932 		/* If SNotification is available, leave notification
1933 		 * handling to sata_async_notification().  If not,
1934 		 * emulate it by snooping SDB FIS RX area.
1935 		 *
1936 		 * Snooping FIS RX area is probably cheaper than
1937 		 * poking SNotification but some constrollers which
1938 		 * implement SNotification, ICH9 for example, don't
1939 		 * store AN SDB FIS into receive area.
1940 		 */
1941 		if (hpriv->cap & HOST_CAP_SNTF)
1942 			sata_async_notification(ap);
1943 		else {
1944 			/* If the 'N' bit in word 0 of the FIS is set,
1945 			 * we just received asynchronous notification.
1946 			 * Tell libata about it.
1947 			 *
1948 			 * Lack of SNotification should not appear in
1949 			 * ahci 1.2, so the workaround is unnecessary
1950 			 * when FBS is enabled.
1951 			 */
1952 			if (pp->fbs_enabled)
1953 				WARN_ON_ONCE(1);
1954 			else {
1955 				const __le32 *f = pp->rx_fis + RX_FIS_SDB;
1956 				u32 f0 = le32_to_cpu(f[0]);
1957 				if (f0 & (1 << 15))
1958 					sata_async_notification(ap);
1959 			}
1960 		}
1961 	}
1962 
1963 	/* Handle completed commands */
1964 	ahci_qc_complete(ap, port_mmio);
1965 }
1966 
1967 static void ahci_port_intr(struct ata_port *ap)
1968 {
1969 	void __iomem *port_mmio = ahci_port_base(ap);
1970 	u32 status;
1971 
1972 	status = readl(port_mmio + PORT_IRQ_STAT);
1973 	writel(status, port_mmio + PORT_IRQ_STAT);
1974 
1975 	ahci_handle_port_interrupt(ap, port_mmio, status);
1976 }
1977 
1978 static irqreturn_t ahci_multi_irqs_intr_hard(int irq, void *dev_instance)
1979 {
1980 	struct ata_port *ap = dev_instance;
1981 	void __iomem *port_mmio = ahci_port_base(ap);
1982 	u32 status;
1983 
1984 	status = readl(port_mmio + PORT_IRQ_STAT);
1985 	writel(status, port_mmio + PORT_IRQ_STAT);
1986 
1987 	spin_lock(ap->lock);
1988 	ahci_handle_port_interrupt(ap, port_mmio, status);
1989 	spin_unlock(ap->lock);
1990 
1991 	return IRQ_HANDLED;
1992 }
1993 
1994 u32 ahci_handle_port_intr(struct ata_host *host, u32 irq_masked)
1995 {
1996 	unsigned int i, handled = 0;
1997 
1998 	for (i = 0; i < host->n_ports; i++) {
1999 		struct ata_port *ap;
2000 
2001 		if (!(irq_masked & (1 << i)))
2002 			continue;
2003 
2004 		ap = host->ports[i];
2005 		if (ap) {
2006 			ahci_port_intr(ap);
2007 		} else {
2008 			if (ata_ratelimit())
2009 				dev_warn(host->dev,
2010 					 "interrupt on disabled port %u\n", i);
2011 		}
2012 
2013 		handled = 1;
2014 	}
2015 
2016 	return handled;
2017 }
2018 EXPORT_SYMBOL_GPL(ahci_handle_port_intr);
2019 
2020 static irqreturn_t ahci_single_level_irq_intr(int irq, void *dev_instance)
2021 {
2022 	struct ata_host *host = dev_instance;
2023 	struct ahci_host_priv *hpriv;
2024 	unsigned int rc = 0;
2025 	void __iomem *mmio;
2026 	u32 irq_stat, irq_masked;
2027 
2028 	hpriv = host->private_data;
2029 	mmio = hpriv->mmio;
2030 
2031 	/* sigh.  0xffffffff is a valid return from h/w */
2032 	irq_stat = readl(mmio + HOST_IRQ_STAT);
2033 	if (!irq_stat)
2034 		return IRQ_NONE;
2035 
2036 	irq_masked = irq_stat & hpriv->port_map;
2037 
2038 	spin_lock(&host->lock);
2039 
2040 	rc = ahci_handle_port_intr(host, irq_masked);
2041 
2042 	/* HOST_IRQ_STAT behaves as level triggered latch meaning that
2043 	 * it should be cleared after all the port events are cleared;
2044 	 * otherwise, it will raise a spurious interrupt after each
2045 	 * valid one.  Please read section 10.6.2 of ahci 1.1 for more
2046 	 * information.
2047 	 *
2048 	 * Also, use the unmasked value to clear interrupt as spurious
2049 	 * pending event on a dummy port might cause screaming IRQ.
2050 	 */
2051 	writel(irq_stat, mmio + HOST_IRQ_STAT);
2052 
2053 	spin_unlock(&host->lock);
2054 
2055 	return IRQ_RETVAL(rc);
2056 }
2057 
2058 unsigned int ahci_qc_issue(struct ata_queued_cmd *qc)
2059 {
2060 	struct ata_port *ap = qc->ap;
2061 	void __iomem *port_mmio = ahci_port_base(ap);
2062 	struct ahci_port_priv *pp = ap->private_data;
2063 
2064 	/* Keep track of the currently active link.  It will be used
2065 	 * in completion path to determine whether NCQ phase is in
2066 	 * progress.
2067 	 */
2068 	pp->active_link = qc->dev->link;
2069 
2070 	if (ata_is_ncq(qc->tf.protocol))
2071 		writel(1 << qc->hw_tag, port_mmio + PORT_SCR_ACT);
2072 
2073 	if (pp->fbs_enabled && pp->fbs_last_dev != qc->dev->link->pmp) {
2074 		u32 fbs = readl(port_mmio + PORT_FBS);
2075 		fbs &= ~(PORT_FBS_DEV_MASK | PORT_FBS_DEC);
2076 		fbs |= qc->dev->link->pmp << PORT_FBS_DEV_OFFSET;
2077 		writel(fbs, port_mmio + PORT_FBS);
2078 		pp->fbs_last_dev = qc->dev->link->pmp;
2079 	}
2080 
2081 	writel(1 << qc->hw_tag, port_mmio + PORT_CMD_ISSUE);
2082 
2083 	ahci_sw_activity(qc->dev->link);
2084 
2085 	return 0;
2086 }
2087 EXPORT_SYMBOL_GPL(ahci_qc_issue);
2088 
2089 static void ahci_qc_fill_rtf(struct ata_queued_cmd *qc)
2090 {
2091 	struct ahci_port_priv *pp = qc->ap->private_data;
2092 	u8 *rx_fis = pp->rx_fis;
2093 
2094 	if (pp->fbs_enabled)
2095 		rx_fis += qc->dev->link->pmp * AHCI_RX_FIS_SZ;
2096 
2097 	/*
2098 	 * After a successful execution of an ATA PIO data-in command,
2099 	 * the device doesn't send D2H Reg FIS to update the TF and
2100 	 * the host should take TF and E_Status from the preceding PIO
2101 	 * Setup FIS.
2102 	 */
2103 	if (qc->tf.protocol == ATA_PROT_PIO && qc->dma_dir == DMA_FROM_DEVICE &&
2104 	    !(qc->flags & ATA_QCFLAG_EH)) {
2105 		ata_tf_from_fis(rx_fis + RX_FIS_PIO_SETUP, &qc->result_tf);
2106 		qc->result_tf.status = (rx_fis + RX_FIS_PIO_SETUP)[15];
2107 		return;
2108 	}
2109 
2110 	/*
2111 	 * For NCQ commands, we never get a D2H FIS, so reading the D2H Register
2112 	 * FIS area of the Received FIS Structure (which contains a copy of the
2113 	 * last D2H FIS received) will contain an outdated status code.
2114 	 * For NCQ commands, we instead get a SDB FIS, so read the SDB FIS area
2115 	 * instead. However, the SDB FIS does not contain the LBA, so we can't
2116 	 * use the ata_tf_from_fis() helper.
2117 	 */
2118 	if (ata_is_ncq(qc->tf.protocol)) {
2119 		const u8 *fis = rx_fis + RX_FIS_SDB;
2120 
2121 		/*
2122 		 * Successful NCQ commands have been filled already.
2123 		 * A failed NCQ command will read the status here.
2124 		 * (Note that a failed NCQ command will get a more specific
2125 		 * error when reading the NCQ Command Error log.)
2126 		 */
2127 		qc->result_tf.status = fis[2];
2128 		qc->result_tf.error = fis[3];
2129 		return;
2130 	}
2131 
2132 	ata_tf_from_fis(rx_fis + RX_FIS_D2H_REG, &qc->result_tf);
2133 }
2134 
2135 static void ahci_qc_ncq_fill_rtf(struct ata_port *ap, u64 done_mask)
2136 {
2137 	struct ahci_port_priv *pp = ap->private_data;
2138 	const u8 *fis;
2139 
2140 	/* No outstanding commands. */
2141 	if (!ap->qc_active)
2142 		return;
2143 
2144 	/*
2145 	 * FBS not enabled, so read status and error once, since they are shared
2146 	 * for all QCs.
2147 	 */
2148 	if (!pp->fbs_enabled) {
2149 		u8 status, error;
2150 
2151 		/* No outstanding NCQ commands. */
2152 		if (!pp->active_link->sactive)
2153 			return;
2154 
2155 		fis = pp->rx_fis + RX_FIS_SDB;
2156 		status = fis[2];
2157 		error = fis[3];
2158 
2159 		while (done_mask) {
2160 			struct ata_queued_cmd *qc;
2161 			unsigned int tag = __ffs64(done_mask);
2162 
2163 			qc = ata_qc_from_tag(ap, tag);
2164 			if (qc && ata_is_ncq(qc->tf.protocol)) {
2165 				qc->result_tf.status = status;
2166 				qc->result_tf.error = error;
2167 				qc->result_tf.flags = qc->tf.flags;
2168 				qc->flags |= ATA_QCFLAG_RTF_FILLED;
2169 			}
2170 			done_mask &= ~(1ULL << tag);
2171 		}
2172 
2173 		return;
2174 	}
2175 
2176 	/*
2177 	 * FBS enabled, so read the status and error for each QC, since the QCs
2178 	 * can belong to different PMP links. (Each PMP link has its own FIS
2179 	 * Receive Area.)
2180 	 */
2181 	while (done_mask) {
2182 		struct ata_queued_cmd *qc;
2183 		unsigned int tag = __ffs64(done_mask);
2184 
2185 		qc = ata_qc_from_tag(ap, tag);
2186 		if (qc && ata_is_ncq(qc->tf.protocol)) {
2187 			fis = pp->rx_fis;
2188 			fis += qc->dev->link->pmp * AHCI_RX_FIS_SZ;
2189 			fis += RX_FIS_SDB;
2190 			qc->result_tf.status = fis[2];
2191 			qc->result_tf.error = fis[3];
2192 			qc->result_tf.flags = qc->tf.flags;
2193 			qc->flags |= ATA_QCFLAG_RTF_FILLED;
2194 		}
2195 		done_mask &= ~(1ULL << tag);
2196 	}
2197 }
2198 
2199 static void ahci_freeze(struct ata_port *ap)
2200 {
2201 	void __iomem *port_mmio = ahci_port_base(ap);
2202 
2203 	/* turn IRQ off */
2204 	writel(0, port_mmio + PORT_IRQ_MASK);
2205 }
2206 
2207 static void ahci_thaw(struct ata_port *ap)
2208 {
2209 	struct ahci_host_priv *hpriv = ap->host->private_data;
2210 	void __iomem *mmio = hpriv->mmio;
2211 	void __iomem *port_mmio = ahci_port_base(ap);
2212 	u32 tmp;
2213 	struct ahci_port_priv *pp = ap->private_data;
2214 
2215 	/* clear IRQ */
2216 	tmp = readl(port_mmio + PORT_IRQ_STAT);
2217 	writel(tmp, port_mmio + PORT_IRQ_STAT);
2218 	writel(1 << ap->port_no, mmio + HOST_IRQ_STAT);
2219 
2220 	/* turn IRQ back on */
2221 	writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
2222 }
2223 
2224 void ahci_error_handler(struct ata_port *ap)
2225 	__must_hold(&ap->host->eh_mutex)
2226 {
2227 	struct ahci_host_priv *hpriv = ap->host->private_data;
2228 
2229 	if (!ata_port_is_frozen(ap)) {
2230 		/* restart engine */
2231 		hpriv->stop_engine(ap);
2232 		hpriv->start_engine(ap);
2233 	}
2234 
2235 	sata_pmp_error_handler(ap);
2236 
2237 	/*
2238 	 * ahci_do_softreset() turns FBS off before resetting a fan-out link
2239 	 * and turns it back on only if that reset succeeds. When it fails
2240 	 * (e.g. a hot-plugged drive is still spinning up), EH escalates to a
2241 	 * PMP hardreset, which never re-enables FBS, so the port would keep
2242 	 * command-based switching until the PMP is attached again (reboot).
2243 	 * Restore FBS once recovery is done and the PMP is still attached.
2244 	 */
2245 	if (sata_pmp_attached(ap) && ata_dev_enabled(ap->link.device)) {
2246 		struct ahci_port_priv *pp = ap->private_data;
2247 
2248 		if (pp->fbs_supported && !pp->fbs_enabled)
2249 			ahci_enable_fbs(ap);
2250 	}
2251 
2252 	if (!ata_dev_enabled(ap->link.device))
2253 		hpriv->stop_engine(ap);
2254 }
2255 EXPORT_SYMBOL_GPL(ahci_error_handler);
2256 
2257 static void ahci_post_internal_cmd(struct ata_queued_cmd *qc)
2258 {
2259 	struct ata_port *ap = qc->ap;
2260 
2261 	/* make DMA engine forget about the failed command */
2262 	if (qc->flags & ATA_QCFLAG_EH)
2263 		ahci_kick_engine(ap);
2264 }
2265 
2266 static void ahci_set_aggressive_devslp(struct ata_port *ap, bool sleep)
2267 {
2268 	struct ahci_host_priv *hpriv = ap->host->private_data;
2269 	void __iomem *port_mmio = ahci_port_base(ap);
2270 	struct ata_device *dev = ap->link.device;
2271 	u32 devslp, dm, dito, mdat, deto, dito_conf;
2272 	int rc;
2273 	unsigned int err_mask;
2274 
2275 	devslp = readl(port_mmio + PORT_DEVSLP);
2276 	if (!(devslp & PORT_DEVSLP_DSP)) {
2277 		dev_info(ap->host->dev, "port does not support device sleep\n");
2278 		return;
2279 	}
2280 
2281 	/* disable device sleep */
2282 	if (!sleep) {
2283 		if (devslp & PORT_DEVSLP_ADSE) {
2284 			writel(devslp & ~PORT_DEVSLP_ADSE,
2285 			       port_mmio + PORT_DEVSLP);
2286 			err_mask = ata_dev_set_feature(dev,
2287 						       SETFEATURES_SATA_DISABLE,
2288 						       SATA_DEVSLP);
2289 			if (err_mask && err_mask != AC_ERR_DEV)
2290 				ata_dev_warn(dev, "failed to disable DEVSLP\n");
2291 		}
2292 		return;
2293 	}
2294 
2295 	dm = (devslp & PORT_DEVSLP_DM_MASK) >> PORT_DEVSLP_DM_OFFSET;
2296 	dito = devslp_idle_timeout / (dm + 1);
2297 	if (dito > 0x3ff)
2298 		dito = 0x3ff;
2299 
2300 	dito_conf = (devslp >> PORT_DEVSLP_DITO_OFFSET) & 0x3FF;
2301 
2302 	/* device sleep was already enabled and same dito */
2303 	if ((devslp & PORT_DEVSLP_ADSE) && (dito_conf == dito))
2304 		return;
2305 
2306 	/* set DITO, MDAT, DETO and enable DevSlp, need to stop engine first */
2307 	rc = hpriv->stop_engine(ap);
2308 	if (rc)
2309 		return;
2310 
2311 	/* Use the nominal value 10 ms if the read MDAT is zero,
2312 	 * the nominal value of DETO is 20 ms.
2313 	 */
2314 	if (dev->devslp_timing[ATA_LOG_DEVSLP_VALID] &
2315 	    ATA_LOG_DEVSLP_VALID_MASK) {
2316 		mdat = dev->devslp_timing[ATA_LOG_DEVSLP_MDAT] &
2317 		       ATA_LOG_DEVSLP_MDAT_MASK;
2318 		if (!mdat)
2319 			mdat = 10;
2320 		deto = dev->devslp_timing[ATA_LOG_DEVSLP_DETO];
2321 		if (!deto)
2322 			deto = 20;
2323 	} else {
2324 		mdat = 10;
2325 		deto = 20;
2326 	}
2327 
2328 	/* Make dito, mdat, deto bits to 0s */
2329 	devslp &= ~GENMASK_ULL(24, 2);
2330 	devslp |= ((dito << PORT_DEVSLP_DITO_OFFSET) |
2331 		   (mdat << PORT_DEVSLP_MDAT_OFFSET) |
2332 		   (deto << PORT_DEVSLP_DETO_OFFSET) |
2333 		   PORT_DEVSLP_ADSE);
2334 	writel(devslp, port_mmio + PORT_DEVSLP);
2335 
2336 	hpriv->start_engine(ap);
2337 
2338 	/* enable device sleep feature for the drive */
2339 	err_mask = ata_dev_set_feature(dev,
2340 				       SETFEATURES_SATA_ENABLE,
2341 				       SATA_DEVSLP);
2342 	if (err_mask && err_mask != AC_ERR_DEV)
2343 		ata_dev_warn(dev, "failed to enable DEVSLP\n");
2344 }
2345 
2346 static void ahci_enable_fbs(struct ata_port *ap)
2347 {
2348 	struct ahci_host_priv *hpriv = ap->host->private_data;
2349 	struct ahci_port_priv *pp = ap->private_data;
2350 	void __iomem *port_mmio = ahci_port_base(ap);
2351 	u32 fbs;
2352 	int rc;
2353 
2354 	if (!pp->fbs_supported)
2355 		return;
2356 
2357 	fbs = readl(port_mmio + PORT_FBS);
2358 	if (fbs & PORT_FBS_EN) {
2359 		pp->fbs_enabled = true;
2360 		pp->fbs_last_dev = -1; /* initialization */
2361 		return;
2362 	}
2363 
2364 	rc = hpriv->stop_engine(ap);
2365 	if (rc)
2366 		return;
2367 
2368 	writel(fbs | PORT_FBS_EN, port_mmio + PORT_FBS);
2369 	fbs = readl(port_mmio + PORT_FBS);
2370 	if (fbs & PORT_FBS_EN) {
2371 		dev_info(ap->host->dev, "FBS is enabled\n");
2372 		pp->fbs_enabled = true;
2373 		pp->fbs_last_dev = -1; /* initialization */
2374 	} else
2375 		dev_err(ap->host->dev, "Failed to enable FBS\n");
2376 
2377 	hpriv->start_engine(ap);
2378 }
2379 
2380 static void ahci_disable_fbs(struct ata_port *ap)
2381 {
2382 	struct ahci_host_priv *hpriv = ap->host->private_data;
2383 	struct ahci_port_priv *pp = ap->private_data;
2384 	void __iomem *port_mmio = ahci_port_base(ap);
2385 	u32 fbs;
2386 	int rc;
2387 
2388 	if (!pp->fbs_supported)
2389 		return;
2390 
2391 	fbs = readl(port_mmio + PORT_FBS);
2392 	if ((fbs & PORT_FBS_EN) == 0) {
2393 		pp->fbs_enabled = false;
2394 		return;
2395 	}
2396 
2397 	rc = hpriv->stop_engine(ap);
2398 	if (rc)
2399 		return;
2400 
2401 	writel(fbs & ~PORT_FBS_EN, port_mmio + PORT_FBS);
2402 	fbs = readl(port_mmio + PORT_FBS);
2403 	if (fbs & PORT_FBS_EN)
2404 		dev_err(ap->host->dev, "Failed to disable FBS\n");
2405 	else {
2406 		dev_info(ap->host->dev, "FBS is disabled\n");
2407 		pp->fbs_enabled = false;
2408 	}
2409 
2410 	hpriv->start_engine(ap);
2411 }
2412 
2413 static void ahci_pmp_attach(struct ata_port *ap)
2414 {
2415 	void __iomem *port_mmio = ahci_port_base(ap);
2416 	struct ahci_port_priv *pp = ap->private_data;
2417 	u32 cmd;
2418 
2419 	cmd = readl(port_mmio + PORT_CMD);
2420 	cmd |= PORT_CMD_PMP;
2421 	writel(cmd, port_mmio + PORT_CMD);
2422 
2423 	ahci_enable_fbs(ap);
2424 
2425 	pp->intr_mask |= PORT_IRQ_BAD_PMP;
2426 
2427 	/*
2428 	 * We must not change the port interrupt mask register if the
2429 	 * port is marked frozen, the value in pp->intr_mask will be
2430 	 * restored later when the port is thawed.
2431 	 *
2432 	 * Note that during initialization, the port is marked as
2433 	 * frozen since the irq handler is not yet registered.
2434 	 */
2435 	if (!ata_port_is_frozen(ap))
2436 		writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
2437 }
2438 
2439 static void ahci_pmp_detach(struct ata_port *ap)
2440 {
2441 	void __iomem *port_mmio = ahci_port_base(ap);
2442 	struct ahci_port_priv *pp = ap->private_data;
2443 	u32 cmd;
2444 
2445 	ahci_disable_fbs(ap);
2446 
2447 	cmd = readl(port_mmio + PORT_CMD);
2448 	cmd &= ~PORT_CMD_PMP;
2449 	writel(cmd, port_mmio + PORT_CMD);
2450 
2451 	pp->intr_mask &= ~PORT_IRQ_BAD_PMP;
2452 
2453 	/* see comment above in ahci_pmp_attach() */
2454 	if (!ata_port_is_frozen(ap))
2455 		writel(pp->intr_mask, port_mmio + PORT_IRQ_MASK);
2456 }
2457 
2458 int ahci_port_resume(struct ata_port *ap)
2459 {
2460 	ahci_rpm_get_port(ap);
2461 
2462 	ahci_power_up(ap);
2463 	ahci_start_port(ap);
2464 
2465 	if (sata_pmp_attached(ap))
2466 		ahci_pmp_attach(ap);
2467 	else
2468 		ahci_pmp_detach(ap);
2469 
2470 	return 0;
2471 }
2472 EXPORT_SYMBOL_GPL(ahci_port_resume);
2473 
2474 #ifdef CONFIG_PM
2475 static void ahci_handle_s2idle(struct ata_port *ap)
2476 {
2477 	void __iomem *port_mmio = ahci_port_base(ap);
2478 	u32 devslp;
2479 
2480 	if (pm_suspend_via_firmware())
2481 		return;
2482 	devslp = readl(port_mmio + PORT_DEVSLP);
2483 	if ((devslp & PORT_DEVSLP_ADSE))
2484 		ata_msleep(ap, devslp_idle_timeout);
2485 }
2486 
2487 static int ahci_port_suspend(struct ata_port *ap, pm_message_t mesg)
2488 {
2489 	const char *emsg = NULL;
2490 	int rc;
2491 
2492 	rc = ahci_deinit_port(ap, &emsg);
2493 	if (rc == 0)
2494 		ahci_power_down(ap);
2495 	else {
2496 		ata_port_err(ap, "%s (%d)\n", emsg, rc);
2497 		ata_port_freeze(ap);
2498 	}
2499 
2500 	if (acpi_storage_d3(ap->host->dev))
2501 		ahci_handle_s2idle(ap);
2502 
2503 	ahci_rpm_put_port(ap);
2504 	return rc;
2505 }
2506 #endif
2507 
2508 static int ahci_port_start(struct ata_port *ap)
2509 {
2510 	struct ahci_host_priv *hpriv = ap->host->private_data;
2511 	struct device *dev = ap->host->dev;
2512 	struct ahci_port_priv *pp;
2513 	void *mem;
2514 	dma_addr_t mem_dma;
2515 	size_t dma_sz, rx_fis_sz;
2516 
2517 	pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
2518 	if (!pp)
2519 		return -ENOMEM;
2520 
2521 	if (ap->host->n_ports > 1) {
2522 		pp->irq_desc = devm_kzalloc(dev, 8, GFP_KERNEL);
2523 		if (!pp->irq_desc) {
2524 			devm_kfree(dev, pp);
2525 			return -ENOMEM;
2526 		}
2527 		snprintf(pp->irq_desc, 8,
2528 			 "%s%d", dev_driver_string(dev), ap->port_no);
2529 	}
2530 
2531 	/* check FBS capability */
2532 	if ((hpriv->cap & HOST_CAP_FBS) && sata_pmp_supported(ap)) {
2533 		void __iomem *port_mmio = ahci_port_base(ap);
2534 		u32 cmd = readl(port_mmio + PORT_CMD);
2535 		if (cmd & PORT_CMD_FBSCP)
2536 			pp->fbs_supported = true;
2537 		else if (hpriv->flags & AHCI_HFLAG_YES_FBS) {
2538 			dev_info(dev, "port %d can do FBS, forcing FBSCP\n",
2539 				 ap->port_no);
2540 			pp->fbs_supported = true;
2541 		} else
2542 			dev_warn(dev, "port %d is not capable of FBS\n",
2543 				 ap->port_no);
2544 	}
2545 
2546 	if (pp->fbs_supported) {
2547 		dma_sz = AHCI_PORT_PRIV_FBS_DMA_SZ;
2548 		rx_fis_sz = AHCI_RX_FIS_SZ * 16;
2549 	} else {
2550 		dma_sz = AHCI_PORT_PRIV_DMA_SZ;
2551 		rx_fis_sz = AHCI_RX_FIS_SZ;
2552 	}
2553 
2554 	mem = dmam_alloc_coherent(dev, dma_sz, &mem_dma, GFP_KERNEL);
2555 	if (!mem)
2556 		return -ENOMEM;
2557 
2558 	/*
2559 	 * First item in chunk of DMA memory: 32-slot command table,
2560 	 * 32 bytes each in size
2561 	 */
2562 	pp->cmd_slot = mem;
2563 	pp->cmd_slot_dma = mem_dma;
2564 
2565 	mem += AHCI_CMD_SLOT_SZ;
2566 	mem_dma += AHCI_CMD_SLOT_SZ;
2567 
2568 	/*
2569 	 * Second item: Received-FIS area
2570 	 */
2571 	pp->rx_fis = mem;
2572 	pp->rx_fis_dma = mem_dma;
2573 
2574 	mem += rx_fis_sz;
2575 	mem_dma += rx_fis_sz;
2576 
2577 	/*
2578 	 * Third item: data area for storing a single command
2579 	 * and its scatter-gather table
2580 	 */
2581 	pp->cmd_tbl = mem;
2582 	pp->cmd_tbl_dma = mem_dma;
2583 
2584 	/*
2585 	 * Save off initial list of interrupts to be enabled.
2586 	 * This could be changed later
2587 	 */
2588 	pp->intr_mask = DEF_PORT_IRQ;
2589 
2590 	/*
2591 	 * Switch to per-port locking in case each port has its own MSI vector.
2592 	 */
2593 	if (hpriv->flags & AHCI_HFLAG_MULTI_MSI) {
2594 		spin_lock_init(&pp->lock);
2595 		ap->lock = &pp->lock;
2596 	}
2597 
2598 	ap->private_data = pp;
2599 
2600 	/* engage engines, captain */
2601 	return ahci_port_resume(ap);
2602 }
2603 
2604 static void ahci_port_stop(struct ata_port *ap)
2605 {
2606 	const char *emsg = NULL;
2607 	struct ahci_host_priv *hpriv = ap->host->private_data;
2608 	void __iomem *host_mmio = hpriv->mmio;
2609 	int rc;
2610 
2611 	/* de-initialize port */
2612 	rc = ahci_deinit_port(ap, &emsg);
2613 	if (rc)
2614 		ata_port_warn(ap, "%s (%d)\n", emsg, rc);
2615 
2616 	/*
2617 	 * Clear GHC.IS to prevent stuck INTx after disabling MSI and
2618 	 * re-enabling INTx.
2619 	 */
2620 	writel(1 << ap->port_no, host_mmio + HOST_IRQ_STAT);
2621 
2622 	ahci_rpm_put_port(ap);
2623 }
2624 
2625 void ahci_print_info(struct ata_host *host, const char *scc_s)
2626 {
2627 	struct ahci_host_priv *hpriv = host->private_data;
2628 	u32 vers, cap, cap2, impl, speed;
2629 	const char *speed_s;
2630 
2631 	vers = hpriv->version;
2632 	cap = hpriv->cap;
2633 	cap2 = hpriv->cap2;
2634 	impl = hpriv->port_map;
2635 
2636 	speed = (cap >> 20) & 0xf;
2637 	if (speed == 1)
2638 		speed_s = "1.5";
2639 	else if (speed == 2)
2640 		speed_s = "3";
2641 	else if (speed == 3)
2642 		speed_s = "6";
2643 	else
2644 		speed_s = "?";
2645 
2646 	dev_info(host->dev,
2647 		"AHCI vers %02x%02x.%02x%02x, "
2648 		"%u command slots, %s Gbps, %s mode\n"
2649 		,
2650 
2651 		(vers >> 24) & 0xff,
2652 		(vers >> 16) & 0xff,
2653 		(vers >> 8) & 0xff,
2654 		vers & 0xff,
2655 
2656 		((cap >> 8) & 0x1f) + 1,
2657 		speed_s,
2658 		scc_s);
2659 
2660 	dev_info(host->dev,
2661 		"%u/%u ports implemented (port mask 0x%x)\n"
2662 		,
2663 
2664 		hweight32(impl),
2665 		ahci_nr_ports(cap),
2666 		impl);
2667 
2668 	dev_info(host->dev,
2669 		"flags: "
2670 		"%s%s%s%s%s%s%s"
2671 		"%s%s%s%s%s%s%s"
2672 		"%s%s%s%s%s%s%s"
2673 		"%s%s\n"
2674 		,
2675 
2676 		cap & HOST_CAP_64 ? "64bit " : "",
2677 		cap & HOST_CAP_NCQ ? "ncq " : "",
2678 		cap & HOST_CAP_SNTF ? "sntf " : "",
2679 		cap & HOST_CAP_MPS ? "ilck " : "",
2680 		cap & HOST_CAP_SSS ? "stag " : "",
2681 		cap & HOST_CAP_ALPM ? "pm " : "",
2682 		cap & HOST_CAP_LED ? "led " : "",
2683 		cap & HOST_CAP_CLO ? "clo " : "",
2684 		cap & HOST_CAP_ONLY ? "only " : "",
2685 		cap & HOST_CAP_PMP ? "pmp " : "",
2686 		cap & HOST_CAP_FBS ? "fbs " : "",
2687 		cap & HOST_CAP_PIO_MULTI ? "pio " : "",
2688 		cap & HOST_CAP_SSC ? "slum " : "",
2689 		cap & HOST_CAP_PART ? "part " : "",
2690 		cap & HOST_CAP_CCC ? "ccc " : "",
2691 		cap & HOST_CAP_EMS ? "ems " : "",
2692 		cap & HOST_CAP_SXS ? "sxs " : "",
2693 		cap2 & HOST_CAP2_DESO ? "deso " : "",
2694 		cap2 & HOST_CAP2_SADM ? "sadm " : "",
2695 		cap2 & HOST_CAP2_SDS ? "sds " : "",
2696 		cap2 & HOST_CAP2_APST ? "apst " : "",
2697 		cap2 & HOST_CAP2_NVMHCI ? "nvmp " : "",
2698 		cap2 & HOST_CAP2_BOH ? "boh " : ""
2699 		);
2700 }
2701 EXPORT_SYMBOL_GPL(ahci_print_info);
2702 
2703 void ahci_set_em_messages(struct ahci_host_priv *hpriv,
2704 			  struct ata_port_info *pi)
2705 {
2706 	u8 messages;
2707 	void __iomem *mmio = hpriv->mmio;
2708 	u32 em_loc = readl(mmio + HOST_EM_LOC);
2709 	u32 em_ctl = readl(mmio + HOST_EM_CTL);
2710 
2711 	if (!ahci_em_messages || !(hpriv->cap & HOST_CAP_EMS))
2712 		return;
2713 
2714 	messages = (em_ctl & EM_CTRL_MSG_TYPE) >> 16;
2715 
2716 	if (messages) {
2717 		/* store em_loc */
2718 		hpriv->em_loc = ((em_loc >> 16) * 4);
2719 		hpriv->em_buf_sz = ((em_loc & 0xff) * 4);
2720 		hpriv->em_msg_type = messages;
2721 		pi->flags |= ATA_FLAG_EM;
2722 		if (!(em_ctl & EM_CTL_ALHD))
2723 			pi->flags |= ATA_FLAG_SW_ACTIVITY;
2724 	}
2725 }
2726 EXPORT_SYMBOL_GPL(ahci_set_em_messages);
2727 
2728 static int ahci_host_activate_multi_irqs(struct ata_host *host,
2729 					 const struct scsi_host_template *sht)
2730 {
2731 	struct ahci_host_priv *hpriv = host->private_data;
2732 	int i, rc;
2733 
2734 	rc = ata_host_start(host);
2735 	if (rc)
2736 		return rc;
2737 	/*
2738 	 * Requests IRQs according to AHCI-1.1 when multiple MSIs were
2739 	 * allocated. That is one MSI per port, starting from @irq.
2740 	 */
2741 	for (i = 0; i < host->n_ports; i++) {
2742 		struct ahci_port_priv *pp = host->ports[i]->private_data;
2743 		int irq = hpriv->get_irq_vector(host, i);
2744 
2745 		/* Do not receive interrupts sent by dummy ports */
2746 		if (!pp) {
2747 			disable_irq(irq);
2748 			continue;
2749 		}
2750 
2751 		rc = devm_request_irq(host->dev, irq, ahci_multi_irqs_intr_hard,
2752 				0, pp->irq_desc, host->ports[i]);
2753 
2754 		if (rc)
2755 			goto free_irqs;
2756 		ata_port_desc_misc(host->ports[i], irq);
2757 	}
2758 
2759 	rc = ata_host_register(host, sht);
2760 	if (rc)
2761 		goto free_irqs;
2762 
2763 	return 0;
2764 
2765 free_irqs:
2766 	/*
2767 	 * Free the IRQs which have been requested, so that the handlers can no
2768 	 * longer access the MMIO of the host once we return, e.g. after the
2769 	 * caller has disabled the clocks of the host.
2770 	 */
2771 	while (--i >= 0) {
2772 		struct ahci_port_priv *pp = host->ports[i]->private_data;
2773 
2774 		if (!pp)
2775 			continue;
2776 
2777 		devm_free_irq(host->dev, hpriv->get_irq_vector(host, i),
2778 			      host->ports[i]);
2779 	}
2780 
2781 	ata_host_undo_start(host);
2782 
2783 	return rc;
2784 }
2785 
2786 /**
2787  *	ahci_host_activate - start AHCI host, request IRQs and register it
2788  *	@host: target ATA host
2789  *	@sht: scsi_host_template to use when registering the host
2790  *
2791  *	LOCKING:
2792  *	Inherited from calling layer (may sleep).
2793  *
2794  *	RETURNS:
2795  *	0 on success, -errno otherwise.
2796  */
2797 int ahci_host_activate(struct ata_host *host, const struct scsi_host_template *sht)
2798 {
2799 	struct ahci_host_priv *hpriv = host->private_data;
2800 	int irq = hpriv->irq;
2801 	int rc;
2802 
2803 	if (hpriv->flags & AHCI_HFLAG_MULTI_MSI) {
2804 		if (hpriv->irq_handler &&
2805 		    hpriv->irq_handler != ahci_single_level_irq_intr)
2806 			dev_warn(host->dev,
2807 			         "both AHCI_HFLAG_MULTI_MSI flag set and custom irq handler implemented\n");
2808 		if (!hpriv->get_irq_vector) {
2809 			dev_err(host->dev,
2810 				"AHCI_HFLAG_MULTI_MSI requires ->get_irq_vector!\n");
2811 			return -EIO;
2812 		}
2813 
2814 		rc = ahci_host_activate_multi_irqs(host, sht);
2815 	} else {
2816 		rc = ata_host_activate(host, irq, hpriv->irq_handler,
2817 				       IRQF_SHARED, sht);
2818 	}
2819 
2820 
2821 	return rc;
2822 }
2823 EXPORT_SYMBOL_GPL(ahci_host_activate);
2824 
2825 MODULE_AUTHOR("Jeff Garzik");
2826 MODULE_DESCRIPTION("Common AHCI SATA low-level routines");
2827 MODULE_LICENSE("GPL");
2828