xref: /linux/drivers/ata/libata-sff.c (revision aec499c75cf8e0b599be4d559e6922b613085f8f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  libata-sff.c - helper library for PCI IDE BMDMA
4  *
5  *  Copyright 2003-2006 Red Hat, Inc.  All rights reserved.
6  *  Copyright 2003-2006 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 http://www.t13.org/ and
12  *  http://www.sata-io.org/
13  */
14 
15 #include <linux/kernel.h>
16 #include <linux/gfp.h>
17 #include <linux/pci.h>
18 #include <linux/module.h>
19 #include <linux/libata.h>
20 #include <linux/highmem.h>
21 #include <trace/events/libata.h>
22 #include "libata.h"
23 
24 static struct workqueue_struct *ata_sff_wq;
25 
26 const struct ata_port_operations ata_sff_port_ops = {
27 	.inherits		= &ata_base_port_ops,
28 
29 	.qc_prep		= ata_noop_qc_prep,
30 	.qc_issue		= ata_sff_qc_issue,
31 	.qc_fill_rtf		= ata_sff_qc_fill_rtf,
32 
33 	.freeze			= ata_sff_freeze,
34 	.thaw			= ata_sff_thaw,
35 	.prereset		= ata_sff_prereset,
36 	.softreset		= ata_sff_softreset,
37 	.hardreset		= sata_sff_hardreset,
38 	.postreset		= ata_sff_postreset,
39 	.error_handler		= ata_sff_error_handler,
40 
41 	.sff_dev_select		= ata_sff_dev_select,
42 	.sff_check_status	= ata_sff_check_status,
43 	.sff_tf_load		= ata_sff_tf_load,
44 	.sff_tf_read		= ata_sff_tf_read,
45 	.sff_exec_command	= ata_sff_exec_command,
46 	.sff_data_xfer		= ata_sff_data_xfer,
47 	.sff_drain_fifo		= ata_sff_drain_fifo,
48 
49 	.lost_interrupt		= ata_sff_lost_interrupt,
50 };
51 EXPORT_SYMBOL_GPL(ata_sff_port_ops);
52 
53 /**
54  *	ata_sff_check_status - Read device status reg & clear interrupt
55  *	@ap: port where the device is
56  *
57  *	Reads ATA taskfile status register for currently-selected device
58  *	and return its value. This also clears pending interrupts
59  *      from this device
60  *
61  *	LOCKING:
62  *	Inherited from caller.
63  */
64 u8 ata_sff_check_status(struct ata_port *ap)
65 {
66 	return ioread8(ap->ioaddr.status_addr);
67 }
68 EXPORT_SYMBOL_GPL(ata_sff_check_status);
69 
70 /**
71  *	ata_sff_altstatus - Read device alternate status reg
72  *	@ap: port where the device is
73  *
74  *	Reads ATA taskfile alternate status register for
75  *	currently-selected device and return its value.
76  *
77  *	Note: may NOT be used as the check_altstatus() entry in
78  *	ata_port_operations.
79  *
80  *	LOCKING:
81  *	Inherited from caller.
82  */
83 static u8 ata_sff_altstatus(struct ata_port *ap)
84 {
85 	if (ap->ops->sff_check_altstatus)
86 		return ap->ops->sff_check_altstatus(ap);
87 
88 	return ioread8(ap->ioaddr.altstatus_addr);
89 }
90 
91 /**
92  *	ata_sff_irq_status - Check if the device is busy
93  *	@ap: port where the device is
94  *
95  *	Determine if the port is currently busy. Uses altstatus
96  *	if available in order to avoid clearing shared IRQ status
97  *	when finding an IRQ source. Non ctl capable devices don't
98  *	share interrupt lines fortunately for us.
99  *
100  *	LOCKING:
101  *	Inherited from caller.
102  */
103 static u8 ata_sff_irq_status(struct ata_port *ap)
104 {
105 	u8 status;
106 
107 	if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
108 		status = ata_sff_altstatus(ap);
109 		/* Not us: We are busy */
110 		if (status & ATA_BUSY)
111 			return status;
112 	}
113 	/* Clear INTRQ latch */
114 	status = ap->ops->sff_check_status(ap);
115 	return status;
116 }
117 
118 /**
119  *	ata_sff_sync - Flush writes
120  *	@ap: Port to wait for.
121  *
122  *	CAUTION:
123  *	If we have an mmio device with no ctl and no altstatus
124  *	method this will fail. No such devices are known to exist.
125  *
126  *	LOCKING:
127  *	Inherited from caller.
128  */
129 
130 static void ata_sff_sync(struct ata_port *ap)
131 {
132 	if (ap->ops->sff_check_altstatus)
133 		ap->ops->sff_check_altstatus(ap);
134 	else if (ap->ioaddr.altstatus_addr)
135 		ioread8(ap->ioaddr.altstatus_addr);
136 }
137 
138 /**
139  *	ata_sff_pause		-	Flush writes and wait 400nS
140  *	@ap: Port to pause for.
141  *
142  *	CAUTION:
143  *	If we have an mmio device with no ctl and no altstatus
144  *	method this will fail. No such devices are known to exist.
145  *
146  *	LOCKING:
147  *	Inherited from caller.
148  */
149 
150 void ata_sff_pause(struct ata_port *ap)
151 {
152 	ata_sff_sync(ap);
153 	ndelay(400);
154 }
155 EXPORT_SYMBOL_GPL(ata_sff_pause);
156 
157 /**
158  *	ata_sff_dma_pause	-	Pause before commencing DMA
159  *	@ap: Port to pause for.
160  *
161  *	Perform I/O fencing and ensure sufficient cycle delays occur
162  *	for the HDMA1:0 transition
163  */
164 
165 void ata_sff_dma_pause(struct ata_port *ap)
166 {
167 	if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
168 		/* An altstatus read will cause the needed delay without
169 		   messing up the IRQ status */
170 		ata_sff_altstatus(ap);
171 		return;
172 	}
173 	/* There are no DMA controllers without ctl. BUG here to ensure
174 	   we never violate the HDMA1:0 transition timing and risk
175 	   corruption. */
176 	BUG();
177 }
178 EXPORT_SYMBOL_GPL(ata_sff_dma_pause);
179 
180 /**
181  *	ata_sff_busy_sleep - sleep until BSY clears, or timeout
182  *	@ap: port containing status register to be polled
183  *	@tmout_pat: impatience timeout in msecs
184  *	@tmout: overall timeout in msecs
185  *
186  *	Sleep until ATA Status register bit BSY clears,
187  *	or a timeout occurs.
188  *
189  *	LOCKING:
190  *	Kernel thread context (may sleep).
191  *
192  *	RETURNS:
193  *	0 on success, -errno otherwise.
194  */
195 int ata_sff_busy_sleep(struct ata_port *ap,
196 		       unsigned long tmout_pat, unsigned long tmout)
197 {
198 	unsigned long timer_start, timeout;
199 	u8 status;
200 
201 	status = ata_sff_busy_wait(ap, ATA_BUSY, 300);
202 	timer_start = jiffies;
203 	timeout = ata_deadline(timer_start, tmout_pat);
204 	while (status != 0xff && (status & ATA_BUSY) &&
205 	       time_before(jiffies, timeout)) {
206 		ata_msleep(ap, 50);
207 		status = ata_sff_busy_wait(ap, ATA_BUSY, 3);
208 	}
209 
210 	if (status != 0xff && (status & ATA_BUSY))
211 		ata_port_warn(ap,
212 			      "port is slow to respond, please be patient (Status 0x%x)\n",
213 			      status);
214 
215 	timeout = ata_deadline(timer_start, tmout);
216 	while (status != 0xff && (status & ATA_BUSY) &&
217 	       time_before(jiffies, timeout)) {
218 		ata_msleep(ap, 50);
219 		status = ap->ops->sff_check_status(ap);
220 	}
221 
222 	if (status == 0xff)
223 		return -ENODEV;
224 
225 	if (status & ATA_BUSY) {
226 		ata_port_err(ap,
227 			     "port failed to respond (%lu secs, Status 0x%x)\n",
228 			     DIV_ROUND_UP(tmout, 1000), status);
229 		return -EBUSY;
230 	}
231 
232 	return 0;
233 }
234 EXPORT_SYMBOL_GPL(ata_sff_busy_sleep);
235 
236 static int ata_sff_check_ready(struct ata_link *link)
237 {
238 	u8 status = link->ap->ops->sff_check_status(link->ap);
239 
240 	return ata_check_ready(status);
241 }
242 
243 /**
244  *	ata_sff_wait_ready - sleep until BSY clears, or timeout
245  *	@link: SFF link to wait ready status for
246  *	@deadline: deadline jiffies for the operation
247  *
248  *	Sleep until ATA Status register bit BSY clears, or timeout
249  *	occurs.
250  *
251  *	LOCKING:
252  *	Kernel thread context (may sleep).
253  *
254  *	RETURNS:
255  *	0 on success, -errno otherwise.
256  */
257 int ata_sff_wait_ready(struct ata_link *link, unsigned long deadline)
258 {
259 	return ata_wait_ready(link, deadline, ata_sff_check_ready);
260 }
261 EXPORT_SYMBOL_GPL(ata_sff_wait_ready);
262 
263 /**
264  *	ata_sff_set_devctl - Write device control reg
265  *	@ap: port where the device is
266  *	@ctl: value to write
267  *
268  *	Writes ATA taskfile device control register.
269  *
270  *	Note: may NOT be used as the sff_set_devctl() entry in
271  *	ata_port_operations.
272  *
273  *	LOCKING:
274  *	Inherited from caller.
275  */
276 static void ata_sff_set_devctl(struct ata_port *ap, u8 ctl)
277 {
278 	if (ap->ops->sff_set_devctl)
279 		ap->ops->sff_set_devctl(ap, ctl);
280 	else
281 		iowrite8(ctl, ap->ioaddr.ctl_addr);
282 }
283 
284 /**
285  *	ata_sff_dev_select - Select device 0/1 on ATA bus
286  *	@ap: ATA channel to manipulate
287  *	@device: ATA device (numbered from zero) to select
288  *
289  *	Use the method defined in the ATA specification to
290  *	make either device 0, or device 1, active on the
291  *	ATA channel.  Works with both PIO and MMIO.
292  *
293  *	May be used as the dev_select() entry in ata_port_operations.
294  *
295  *	LOCKING:
296  *	caller.
297  */
298 void ata_sff_dev_select(struct ata_port *ap, unsigned int device)
299 {
300 	u8 tmp;
301 
302 	if (device == 0)
303 		tmp = ATA_DEVICE_OBS;
304 	else
305 		tmp = ATA_DEVICE_OBS | ATA_DEV1;
306 
307 	iowrite8(tmp, ap->ioaddr.device_addr);
308 	ata_sff_pause(ap);	/* needed; also flushes, for mmio */
309 }
310 EXPORT_SYMBOL_GPL(ata_sff_dev_select);
311 
312 /**
313  *	ata_dev_select - Select device 0/1 on ATA bus
314  *	@ap: ATA channel to manipulate
315  *	@device: ATA device (numbered from zero) to select
316  *	@wait: non-zero to wait for Status register BSY bit to clear
317  *	@can_sleep: non-zero if context allows sleeping
318  *
319  *	Use the method defined in the ATA specification to
320  *	make either device 0, or device 1, active on the
321  *	ATA channel.
322  *
323  *	This is a high-level version of ata_sff_dev_select(), which
324  *	additionally provides the services of inserting the proper
325  *	pauses and status polling, where needed.
326  *
327  *	LOCKING:
328  *	caller.
329  */
330 static void ata_dev_select(struct ata_port *ap, unsigned int device,
331 			   unsigned int wait, unsigned int can_sleep)
332 {
333 	if (wait)
334 		ata_wait_idle(ap);
335 
336 	ap->ops->sff_dev_select(ap, device);
337 
338 	if (wait) {
339 		if (can_sleep && ap->link.device[device].class == ATA_DEV_ATAPI)
340 			ata_msleep(ap, 150);
341 		ata_wait_idle(ap);
342 	}
343 }
344 
345 /**
346  *	ata_sff_irq_on - Enable interrupts on a port.
347  *	@ap: Port on which interrupts are enabled.
348  *
349  *	Enable interrupts on a legacy IDE device using MMIO or PIO,
350  *	wait for idle, clear any pending interrupts.
351  *
352  *	Note: may NOT be used as the sff_irq_on() entry in
353  *	ata_port_operations.
354  *
355  *	LOCKING:
356  *	Inherited from caller.
357  */
358 void ata_sff_irq_on(struct ata_port *ap)
359 {
360 	struct ata_ioports *ioaddr = &ap->ioaddr;
361 
362 	if (ap->ops->sff_irq_on) {
363 		ap->ops->sff_irq_on(ap);
364 		return;
365 	}
366 
367 	ap->ctl &= ~ATA_NIEN;
368 	ap->last_ctl = ap->ctl;
369 
370 	if (ap->ops->sff_set_devctl || ioaddr->ctl_addr)
371 		ata_sff_set_devctl(ap, ap->ctl);
372 	ata_wait_idle(ap);
373 
374 	if (ap->ops->sff_irq_clear)
375 		ap->ops->sff_irq_clear(ap);
376 }
377 EXPORT_SYMBOL_GPL(ata_sff_irq_on);
378 
379 /**
380  *	ata_sff_tf_load - send taskfile registers to host controller
381  *	@ap: Port to which output is sent
382  *	@tf: ATA taskfile register set
383  *
384  *	Outputs ATA taskfile to standard ATA host controller.
385  *
386  *	LOCKING:
387  *	Inherited from caller.
388  */
389 void ata_sff_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
390 {
391 	struct ata_ioports *ioaddr = &ap->ioaddr;
392 	unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
393 
394 	if (tf->ctl != ap->last_ctl) {
395 		if (ioaddr->ctl_addr)
396 			iowrite8(tf->ctl, ioaddr->ctl_addr);
397 		ap->last_ctl = tf->ctl;
398 		ata_wait_idle(ap);
399 	}
400 
401 	if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
402 		WARN_ON_ONCE(!ioaddr->ctl_addr);
403 		iowrite8(tf->hob_feature, ioaddr->feature_addr);
404 		iowrite8(tf->hob_nsect, ioaddr->nsect_addr);
405 		iowrite8(tf->hob_lbal, ioaddr->lbal_addr);
406 		iowrite8(tf->hob_lbam, ioaddr->lbam_addr);
407 		iowrite8(tf->hob_lbah, ioaddr->lbah_addr);
408 	}
409 
410 	if (is_addr) {
411 		iowrite8(tf->feature, ioaddr->feature_addr);
412 		iowrite8(tf->nsect, ioaddr->nsect_addr);
413 		iowrite8(tf->lbal, ioaddr->lbal_addr);
414 		iowrite8(tf->lbam, ioaddr->lbam_addr);
415 		iowrite8(tf->lbah, ioaddr->lbah_addr);
416 	}
417 
418 	if (tf->flags & ATA_TFLAG_DEVICE)
419 		iowrite8(tf->device, ioaddr->device_addr);
420 
421 	ata_wait_idle(ap);
422 }
423 EXPORT_SYMBOL_GPL(ata_sff_tf_load);
424 
425 /**
426  *	ata_sff_tf_read - input device's ATA taskfile shadow registers
427  *	@ap: Port from which input is read
428  *	@tf: ATA taskfile register set for storing input
429  *
430  *	Reads ATA taskfile registers for currently-selected device
431  *	into @tf. Assumes the device has a fully SFF compliant task file
432  *	layout and behaviour. If you device does not (eg has a different
433  *	status method) then you will need to provide a replacement tf_read
434  *
435  *	LOCKING:
436  *	Inherited from caller.
437  */
438 void ata_sff_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
439 {
440 	struct ata_ioports *ioaddr = &ap->ioaddr;
441 
442 	tf->command = ata_sff_check_status(ap);
443 	tf->feature = ioread8(ioaddr->error_addr);
444 	tf->nsect = ioread8(ioaddr->nsect_addr);
445 	tf->lbal = ioread8(ioaddr->lbal_addr);
446 	tf->lbam = ioread8(ioaddr->lbam_addr);
447 	tf->lbah = ioread8(ioaddr->lbah_addr);
448 	tf->device = ioread8(ioaddr->device_addr);
449 
450 	if (tf->flags & ATA_TFLAG_LBA48) {
451 		if (likely(ioaddr->ctl_addr)) {
452 			iowrite8(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
453 			tf->hob_feature = ioread8(ioaddr->error_addr);
454 			tf->hob_nsect = ioread8(ioaddr->nsect_addr);
455 			tf->hob_lbal = ioread8(ioaddr->lbal_addr);
456 			tf->hob_lbam = ioread8(ioaddr->lbam_addr);
457 			tf->hob_lbah = ioread8(ioaddr->lbah_addr);
458 			iowrite8(tf->ctl, ioaddr->ctl_addr);
459 			ap->last_ctl = tf->ctl;
460 		} else
461 			WARN_ON_ONCE(1);
462 	}
463 }
464 EXPORT_SYMBOL_GPL(ata_sff_tf_read);
465 
466 /**
467  *	ata_sff_exec_command - issue ATA command to host controller
468  *	@ap: port to which command is being issued
469  *	@tf: ATA taskfile register set
470  *
471  *	Issues ATA command, with proper synchronization with interrupt
472  *	handler / other threads.
473  *
474  *	LOCKING:
475  *	spin_lock_irqsave(host lock)
476  */
477 void ata_sff_exec_command(struct ata_port *ap, const struct ata_taskfile *tf)
478 {
479 	iowrite8(tf->command, ap->ioaddr.command_addr);
480 	ata_sff_pause(ap);
481 }
482 EXPORT_SYMBOL_GPL(ata_sff_exec_command);
483 
484 /**
485  *	ata_tf_to_host - issue ATA taskfile to host controller
486  *	@ap: port to which command is being issued
487  *	@tf: ATA taskfile register set
488  *	@tag: tag of the associated command
489  *
490  *	Issues ATA taskfile register set to ATA host controller,
491  *	with proper synchronization with interrupt handler and
492  *	other threads.
493  *
494  *	LOCKING:
495  *	spin_lock_irqsave(host lock)
496  */
497 static inline void ata_tf_to_host(struct ata_port *ap,
498 				  const struct ata_taskfile *tf,
499 				  unsigned int tag)
500 {
501 	trace_ata_tf_load(ap, tf);
502 	ap->ops->sff_tf_load(ap, tf);
503 	trace_ata_exec_command(ap, tf, tag);
504 	ap->ops->sff_exec_command(ap, tf);
505 }
506 
507 /**
508  *	ata_sff_data_xfer - Transfer data by PIO
509  *	@qc: queued command
510  *	@buf: data buffer
511  *	@buflen: buffer length
512  *	@rw: read/write
513  *
514  *	Transfer data from/to the device data register by PIO.
515  *
516  *	LOCKING:
517  *	Inherited from caller.
518  *
519  *	RETURNS:
520  *	Bytes consumed.
521  */
522 unsigned int ata_sff_data_xfer(struct ata_queued_cmd *qc, unsigned char *buf,
523 			       unsigned int buflen, int rw)
524 {
525 	struct ata_port *ap = qc->dev->link->ap;
526 	void __iomem *data_addr = ap->ioaddr.data_addr;
527 	unsigned int words = buflen >> 1;
528 
529 	/* Transfer multiple of 2 bytes */
530 	if (rw == READ)
531 		ioread16_rep(data_addr, buf, words);
532 	else
533 		iowrite16_rep(data_addr, buf, words);
534 
535 	/* Transfer trailing byte, if any. */
536 	if (unlikely(buflen & 0x01)) {
537 		unsigned char pad[2] = { };
538 
539 		/* Point buf to the tail of buffer */
540 		buf += buflen - 1;
541 
542 		/*
543 		 * Use io*16_rep() accessors here as well to avoid pointlessly
544 		 * swapping bytes to and from on the big endian machines...
545 		 */
546 		if (rw == READ) {
547 			ioread16_rep(data_addr, pad, 1);
548 			*buf = pad[0];
549 		} else {
550 			pad[0] = *buf;
551 			iowrite16_rep(data_addr, pad, 1);
552 		}
553 		words++;
554 	}
555 
556 	return words << 1;
557 }
558 EXPORT_SYMBOL_GPL(ata_sff_data_xfer);
559 
560 /**
561  *	ata_sff_data_xfer32 - Transfer data by PIO
562  *	@qc: queued command
563  *	@buf: data buffer
564  *	@buflen: buffer length
565  *	@rw: read/write
566  *
567  *	Transfer data from/to the device data register by PIO using 32bit
568  *	I/O operations.
569  *
570  *	LOCKING:
571  *	Inherited from caller.
572  *
573  *	RETURNS:
574  *	Bytes consumed.
575  */
576 
577 unsigned int ata_sff_data_xfer32(struct ata_queued_cmd *qc, unsigned char *buf,
578 			       unsigned int buflen, int rw)
579 {
580 	struct ata_device *dev = qc->dev;
581 	struct ata_port *ap = dev->link->ap;
582 	void __iomem *data_addr = ap->ioaddr.data_addr;
583 	unsigned int words = buflen >> 2;
584 	int slop = buflen & 3;
585 
586 	if (!(ap->pflags & ATA_PFLAG_PIO32))
587 		return ata_sff_data_xfer(qc, buf, buflen, rw);
588 
589 	/* Transfer multiple of 4 bytes */
590 	if (rw == READ)
591 		ioread32_rep(data_addr, buf, words);
592 	else
593 		iowrite32_rep(data_addr, buf, words);
594 
595 	/* Transfer trailing bytes, if any */
596 	if (unlikely(slop)) {
597 		unsigned char pad[4] = { };
598 
599 		/* Point buf to the tail of buffer */
600 		buf += buflen - slop;
601 
602 		/*
603 		 * Use io*_rep() accessors here as well to avoid pointlessly
604 		 * swapping bytes to and from on the big endian machines...
605 		 */
606 		if (rw == READ) {
607 			if (slop < 3)
608 				ioread16_rep(data_addr, pad, 1);
609 			else
610 				ioread32_rep(data_addr, pad, 1);
611 			memcpy(buf, pad, slop);
612 		} else {
613 			memcpy(pad, buf, slop);
614 			if (slop < 3)
615 				iowrite16_rep(data_addr, pad, 1);
616 			else
617 				iowrite32_rep(data_addr, pad, 1);
618 		}
619 	}
620 	return (buflen + 1) & ~1;
621 }
622 EXPORT_SYMBOL_GPL(ata_sff_data_xfer32);
623 
624 static void ata_pio_xfer(struct ata_queued_cmd *qc, struct page *page,
625 		unsigned int offset, size_t xfer_size)
626 {
627 	bool do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
628 	unsigned char *buf;
629 
630 	buf = kmap_atomic(page);
631 	qc->ap->ops->sff_data_xfer(qc, buf + offset, xfer_size, do_write);
632 	kunmap_atomic(buf);
633 
634 	if (!do_write && !PageSlab(page))
635 		flush_dcache_page(page);
636 }
637 
638 /**
639  *	ata_pio_sector - Transfer a sector of data.
640  *	@qc: Command on going
641  *
642  *	Transfer qc->sect_size bytes of data from/to the ATA device.
643  *
644  *	LOCKING:
645  *	Inherited from caller.
646  */
647 static void ata_pio_sector(struct ata_queued_cmd *qc)
648 {
649 	struct ata_port *ap = qc->ap;
650 	struct page *page;
651 	unsigned int offset;
652 
653 	if (!qc->cursg) {
654 		qc->curbytes = qc->nbytes;
655 		return;
656 	}
657 	if (qc->curbytes == qc->nbytes - qc->sect_size)
658 		ap->hsm_task_state = HSM_ST_LAST;
659 
660 	page = sg_page(qc->cursg);
661 	offset = qc->cursg->offset + qc->cursg_ofs;
662 
663 	/* get the current page and offset */
664 	page = nth_page(page, (offset >> PAGE_SHIFT));
665 	offset %= PAGE_SIZE;
666 
667 	trace_ata_sff_pio_transfer_data(qc, offset, qc->sect_size);
668 
669 	/*
670 	 * Split the transfer when it splits a page boundary.  Note that the
671 	 * split still has to be dword aligned like all ATA data transfers.
672 	 */
673 	WARN_ON_ONCE(offset % 4);
674 	if (offset + qc->sect_size > PAGE_SIZE) {
675 		unsigned int split_len = PAGE_SIZE - offset;
676 
677 		ata_pio_xfer(qc, page, offset, split_len);
678 		ata_pio_xfer(qc, nth_page(page, 1), 0,
679 			     qc->sect_size - split_len);
680 	} else {
681 		ata_pio_xfer(qc, page, offset, qc->sect_size);
682 	}
683 
684 	qc->curbytes += qc->sect_size;
685 	qc->cursg_ofs += qc->sect_size;
686 
687 	if (qc->cursg_ofs == qc->cursg->length) {
688 		qc->cursg = sg_next(qc->cursg);
689 		if (!qc->cursg)
690 			ap->hsm_task_state = HSM_ST_LAST;
691 		qc->cursg_ofs = 0;
692 	}
693 }
694 
695 /**
696  *	ata_pio_sectors - Transfer one or many sectors.
697  *	@qc: Command on going
698  *
699  *	Transfer one or many sectors of data from/to the
700  *	ATA device for the DRQ request.
701  *
702  *	LOCKING:
703  *	Inherited from caller.
704  */
705 static void ata_pio_sectors(struct ata_queued_cmd *qc)
706 {
707 	if (is_multi_taskfile(&qc->tf)) {
708 		/* READ/WRITE MULTIPLE */
709 		unsigned int nsect;
710 
711 		WARN_ON_ONCE(qc->dev->multi_count == 0);
712 
713 		nsect = min((qc->nbytes - qc->curbytes) / qc->sect_size,
714 			    qc->dev->multi_count);
715 		while (nsect--)
716 			ata_pio_sector(qc);
717 	} else
718 		ata_pio_sector(qc);
719 
720 	ata_sff_sync(qc->ap); /* flush */
721 }
722 
723 /**
724  *	atapi_send_cdb - Write CDB bytes to hardware
725  *	@ap: Port to which ATAPI device is attached.
726  *	@qc: Taskfile currently active
727  *
728  *	When device has indicated its readiness to accept
729  *	a CDB, this function is called.  Send the CDB.
730  *
731  *	LOCKING:
732  *	caller.
733  */
734 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
735 {
736 	/* send SCSI cdb */
737 	trace_atapi_send_cdb(qc, 0, qc->dev->cdb_len);
738 	WARN_ON_ONCE(qc->dev->cdb_len < 12);
739 
740 	ap->ops->sff_data_xfer(qc, qc->cdb, qc->dev->cdb_len, 1);
741 	ata_sff_sync(ap);
742 	/* FIXME: If the CDB is for DMA do we need to do the transition delay
743 	   or is bmdma_start guaranteed to do it ? */
744 	switch (qc->tf.protocol) {
745 	case ATAPI_PROT_PIO:
746 		ap->hsm_task_state = HSM_ST;
747 		break;
748 	case ATAPI_PROT_NODATA:
749 		ap->hsm_task_state = HSM_ST_LAST;
750 		break;
751 #ifdef CONFIG_ATA_BMDMA
752 	case ATAPI_PROT_DMA:
753 		ap->hsm_task_state = HSM_ST_LAST;
754 		/* initiate bmdma */
755 		trace_ata_bmdma_start(ap, &qc->tf, qc->tag);
756 		ap->ops->bmdma_start(qc);
757 		break;
758 #endif /* CONFIG_ATA_BMDMA */
759 	default:
760 		BUG();
761 	}
762 }
763 
764 /**
765  *	__atapi_pio_bytes - Transfer data from/to the ATAPI device.
766  *	@qc: Command on going
767  *	@bytes: number of bytes
768  *
769  *	Transfer Transfer data from/to the ATAPI device.
770  *
771  *	LOCKING:
772  *	Inherited from caller.
773  *
774  */
775 static int __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
776 {
777 	int rw = (qc->tf.flags & ATA_TFLAG_WRITE) ? WRITE : READ;
778 	struct ata_port *ap = qc->ap;
779 	struct ata_device *dev = qc->dev;
780 	struct ata_eh_info *ehi = &dev->link->eh_info;
781 	struct scatterlist *sg;
782 	struct page *page;
783 	unsigned char *buf;
784 	unsigned int offset, count, consumed;
785 
786 next_sg:
787 	sg = qc->cursg;
788 	if (unlikely(!sg)) {
789 		ata_ehi_push_desc(ehi, "unexpected or too much trailing data "
790 				  "buf=%u cur=%u bytes=%u",
791 				  qc->nbytes, qc->curbytes, bytes);
792 		return -1;
793 	}
794 
795 	page = sg_page(sg);
796 	offset = sg->offset + qc->cursg_ofs;
797 
798 	/* get the current page and offset */
799 	page = nth_page(page, (offset >> PAGE_SHIFT));
800 	offset %= PAGE_SIZE;
801 
802 	/* don't overrun current sg */
803 	count = min(sg->length - qc->cursg_ofs, bytes);
804 
805 	/* don't cross page boundaries */
806 	count = min(count, (unsigned int)PAGE_SIZE - offset);
807 
808 	trace_atapi_pio_transfer_data(qc, offset, count);
809 
810 	/* do the actual data transfer */
811 	buf = kmap_atomic(page);
812 	consumed = ap->ops->sff_data_xfer(qc, buf + offset, count, rw);
813 	kunmap_atomic(buf);
814 
815 	bytes -= min(bytes, consumed);
816 	qc->curbytes += count;
817 	qc->cursg_ofs += count;
818 
819 	if (qc->cursg_ofs == sg->length) {
820 		qc->cursg = sg_next(qc->cursg);
821 		qc->cursg_ofs = 0;
822 	}
823 
824 	/*
825 	 * There used to be a  WARN_ON_ONCE(qc->cursg && count != consumed);
826 	 * Unfortunately __atapi_pio_bytes doesn't know enough to do the WARN
827 	 * check correctly as it doesn't know if it is the last request being
828 	 * made. Somebody should implement a proper sanity check.
829 	 */
830 	if (bytes)
831 		goto next_sg;
832 	return 0;
833 }
834 
835 /**
836  *	atapi_pio_bytes - Transfer data from/to the ATAPI device.
837  *	@qc: Command on going
838  *
839  *	Transfer Transfer data from/to the ATAPI device.
840  *
841  *	LOCKING:
842  *	Inherited from caller.
843  */
844 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
845 {
846 	struct ata_port *ap = qc->ap;
847 	struct ata_device *dev = qc->dev;
848 	struct ata_eh_info *ehi = &dev->link->eh_info;
849 	unsigned int ireason, bc_lo, bc_hi, bytes;
850 	int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
851 
852 	/* Abuse qc->result_tf for temp storage of intermediate TF
853 	 * here to save some kernel stack usage.
854 	 * For normal completion, qc->result_tf is not relevant. For
855 	 * error, qc->result_tf is later overwritten by ata_qc_complete().
856 	 * So, the correctness of qc->result_tf is not affected.
857 	 */
858 	ap->ops->sff_tf_read(ap, &qc->result_tf);
859 	ireason = qc->result_tf.nsect;
860 	bc_lo = qc->result_tf.lbam;
861 	bc_hi = qc->result_tf.lbah;
862 	bytes = (bc_hi << 8) | bc_lo;
863 
864 	/* shall be cleared to zero, indicating xfer of data */
865 	if (unlikely(ireason & ATAPI_COD))
866 		goto atapi_check;
867 
868 	/* make sure transfer direction matches expected */
869 	i_write = ((ireason & ATAPI_IO) == 0) ? 1 : 0;
870 	if (unlikely(do_write != i_write))
871 		goto atapi_check;
872 
873 	if (unlikely(!bytes))
874 		goto atapi_check;
875 
876 	if (unlikely(__atapi_pio_bytes(qc, bytes)))
877 		goto err_out;
878 	ata_sff_sync(ap); /* flush */
879 
880 	return;
881 
882  atapi_check:
883 	ata_ehi_push_desc(ehi, "ATAPI check failed (ireason=0x%x bytes=%u)",
884 			  ireason, bytes);
885  err_out:
886 	qc->err_mask |= AC_ERR_HSM;
887 	ap->hsm_task_state = HSM_ST_ERR;
888 }
889 
890 /**
891  *	ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
892  *	@ap: the target ata_port
893  *	@qc: qc on going
894  *
895  *	RETURNS:
896  *	1 if ok in workqueue, 0 otherwise.
897  */
898 static inline int ata_hsm_ok_in_wq(struct ata_port *ap,
899 						struct ata_queued_cmd *qc)
900 {
901 	if (qc->tf.flags & ATA_TFLAG_POLLING)
902 		return 1;
903 
904 	if (ap->hsm_task_state == HSM_ST_FIRST) {
905 		if (qc->tf.protocol == ATA_PROT_PIO &&
906 		   (qc->tf.flags & ATA_TFLAG_WRITE))
907 		    return 1;
908 
909 		if (ata_is_atapi(qc->tf.protocol) &&
910 		   !(qc->dev->flags & ATA_DFLAG_CDB_INTR))
911 			return 1;
912 	}
913 
914 	return 0;
915 }
916 
917 /**
918  *	ata_hsm_qc_complete - finish a qc running on standard HSM
919  *	@qc: Command to complete
920  *	@in_wq: 1 if called from workqueue, 0 otherwise
921  *
922  *	Finish @qc which is running on standard HSM.
923  *
924  *	LOCKING:
925  *	If @in_wq is zero, spin_lock_irqsave(host lock).
926  *	Otherwise, none on entry and grabs host lock.
927  */
928 static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
929 {
930 	struct ata_port *ap = qc->ap;
931 
932 	if (ap->ops->error_handler) {
933 		if (in_wq) {
934 			/* EH might have kicked in while host lock is
935 			 * released.
936 			 */
937 			qc = ata_qc_from_tag(ap, qc->tag);
938 			if (qc) {
939 				if (likely(!(qc->err_mask & AC_ERR_HSM))) {
940 					ata_sff_irq_on(ap);
941 					ata_qc_complete(qc);
942 				} else
943 					ata_port_freeze(ap);
944 			}
945 		} else {
946 			if (likely(!(qc->err_mask & AC_ERR_HSM)))
947 				ata_qc_complete(qc);
948 			else
949 				ata_port_freeze(ap);
950 		}
951 	} else {
952 		if (in_wq) {
953 			ata_sff_irq_on(ap);
954 			ata_qc_complete(qc);
955 		} else
956 			ata_qc_complete(qc);
957 	}
958 }
959 
960 /**
961  *	ata_sff_hsm_move - move the HSM to the next state.
962  *	@ap: the target ata_port
963  *	@qc: qc on going
964  *	@status: current device status
965  *	@in_wq: 1 if called from workqueue, 0 otherwise
966  *
967  *	RETURNS:
968  *	1 when poll next status needed, 0 otherwise.
969  */
970 int ata_sff_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
971 		     u8 status, int in_wq)
972 {
973 	struct ata_link *link = qc->dev->link;
974 	struct ata_eh_info *ehi = &link->eh_info;
975 	int poll_next;
976 
977 	lockdep_assert_held(ap->lock);
978 
979 	WARN_ON_ONCE((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
980 
981 	/* Make sure ata_sff_qc_issue() does not throw things
982 	 * like DMA polling into the workqueue. Notice that
983 	 * in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
984 	 */
985 	WARN_ON_ONCE(in_wq != ata_hsm_ok_in_wq(ap, qc));
986 
987 fsm_start:
988 	trace_ata_sff_hsm_state(qc, status);
989 
990 	switch (ap->hsm_task_state) {
991 	case HSM_ST_FIRST:
992 		/* Send first data block or PACKET CDB */
993 
994 		/* If polling, we will stay in the work queue after
995 		 * sending the data. Otherwise, interrupt handler
996 		 * takes over after sending the data.
997 		 */
998 		poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
999 
1000 		/* check device status */
1001 		if (unlikely((status & ATA_DRQ) == 0)) {
1002 			/* handle BSY=0, DRQ=0 as error */
1003 			if (likely(status & (ATA_ERR | ATA_DF)))
1004 				/* device stops HSM for abort/error */
1005 				qc->err_mask |= AC_ERR_DEV;
1006 			else {
1007 				/* HSM violation. Let EH handle this */
1008 				ata_ehi_push_desc(ehi,
1009 					"ST_FIRST: !(DRQ|ERR|DF)");
1010 				qc->err_mask |= AC_ERR_HSM;
1011 			}
1012 
1013 			ap->hsm_task_state = HSM_ST_ERR;
1014 			goto fsm_start;
1015 		}
1016 
1017 		/* Device should not ask for data transfer (DRQ=1)
1018 		 * when it finds something wrong.
1019 		 * We ignore DRQ here and stop the HSM by
1020 		 * changing hsm_task_state to HSM_ST_ERR and
1021 		 * let the EH abort the command or reset the device.
1022 		 */
1023 		if (unlikely(status & (ATA_ERR | ATA_DF))) {
1024 			/* Some ATAPI tape drives forget to clear the ERR bit
1025 			 * when doing the next command (mostly request sense).
1026 			 * We ignore ERR here to workaround and proceed sending
1027 			 * the CDB.
1028 			 */
1029 			if (!(qc->dev->horkage & ATA_HORKAGE_STUCK_ERR)) {
1030 				ata_ehi_push_desc(ehi, "ST_FIRST: "
1031 					"DRQ=1 with device error, "
1032 					"dev_stat 0x%X", status);
1033 				qc->err_mask |= AC_ERR_HSM;
1034 				ap->hsm_task_state = HSM_ST_ERR;
1035 				goto fsm_start;
1036 			}
1037 		}
1038 
1039 		if (qc->tf.protocol == ATA_PROT_PIO) {
1040 			/* PIO data out protocol.
1041 			 * send first data block.
1042 			 */
1043 
1044 			/* ata_pio_sectors() might change the state
1045 			 * to HSM_ST_LAST. so, the state is changed here
1046 			 * before ata_pio_sectors().
1047 			 */
1048 			ap->hsm_task_state = HSM_ST;
1049 			ata_pio_sectors(qc);
1050 		} else
1051 			/* send CDB */
1052 			atapi_send_cdb(ap, qc);
1053 
1054 		/* if polling, ata_sff_pio_task() handles the rest.
1055 		 * otherwise, interrupt handler takes over from here.
1056 		 */
1057 		break;
1058 
1059 	case HSM_ST:
1060 		/* complete command or read/write the data register */
1061 		if (qc->tf.protocol == ATAPI_PROT_PIO) {
1062 			/* ATAPI PIO protocol */
1063 			if ((status & ATA_DRQ) == 0) {
1064 				/* No more data to transfer or device error.
1065 				 * Device error will be tagged in HSM_ST_LAST.
1066 				 */
1067 				ap->hsm_task_state = HSM_ST_LAST;
1068 				goto fsm_start;
1069 			}
1070 
1071 			/* Device should not ask for data transfer (DRQ=1)
1072 			 * when it finds something wrong.
1073 			 * We ignore DRQ here and stop the HSM by
1074 			 * changing hsm_task_state to HSM_ST_ERR and
1075 			 * let the EH abort the command or reset the device.
1076 			 */
1077 			if (unlikely(status & (ATA_ERR | ATA_DF))) {
1078 				ata_ehi_push_desc(ehi, "ST-ATAPI: "
1079 					"DRQ=1 with device error, "
1080 					"dev_stat 0x%X", status);
1081 				qc->err_mask |= AC_ERR_HSM;
1082 				ap->hsm_task_state = HSM_ST_ERR;
1083 				goto fsm_start;
1084 			}
1085 
1086 			atapi_pio_bytes(qc);
1087 
1088 			if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
1089 				/* bad ireason reported by device */
1090 				goto fsm_start;
1091 
1092 		} else {
1093 			/* ATA PIO protocol */
1094 			if (unlikely((status & ATA_DRQ) == 0)) {
1095 				/* handle BSY=0, DRQ=0 as error */
1096 				if (likely(status & (ATA_ERR | ATA_DF))) {
1097 					/* device stops HSM for abort/error */
1098 					qc->err_mask |= AC_ERR_DEV;
1099 
1100 					/* If diagnostic failed and this is
1101 					 * IDENTIFY, it's likely a phantom
1102 					 * device.  Mark hint.
1103 					 */
1104 					if (qc->dev->horkage &
1105 					    ATA_HORKAGE_DIAGNOSTIC)
1106 						qc->err_mask |=
1107 							AC_ERR_NODEV_HINT;
1108 				} else {
1109 					/* HSM violation. Let EH handle this.
1110 					 * Phantom devices also trigger this
1111 					 * condition.  Mark hint.
1112 					 */
1113 					ata_ehi_push_desc(ehi, "ST-ATA: "
1114 						"DRQ=0 without device error, "
1115 						"dev_stat 0x%X", status);
1116 					qc->err_mask |= AC_ERR_HSM |
1117 							AC_ERR_NODEV_HINT;
1118 				}
1119 
1120 				ap->hsm_task_state = HSM_ST_ERR;
1121 				goto fsm_start;
1122 			}
1123 
1124 			/* For PIO reads, some devices may ask for
1125 			 * data transfer (DRQ=1) alone with ERR=1.
1126 			 * We respect DRQ here and transfer one
1127 			 * block of junk data before changing the
1128 			 * hsm_task_state to HSM_ST_ERR.
1129 			 *
1130 			 * For PIO writes, ERR=1 DRQ=1 doesn't make
1131 			 * sense since the data block has been
1132 			 * transferred to the device.
1133 			 */
1134 			if (unlikely(status & (ATA_ERR | ATA_DF))) {
1135 				/* data might be corrputed */
1136 				qc->err_mask |= AC_ERR_DEV;
1137 
1138 				if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
1139 					ata_pio_sectors(qc);
1140 					status = ata_wait_idle(ap);
1141 				}
1142 
1143 				if (status & (ATA_BUSY | ATA_DRQ)) {
1144 					ata_ehi_push_desc(ehi, "ST-ATA: "
1145 						"BUSY|DRQ persists on ERR|DF, "
1146 						"dev_stat 0x%X", status);
1147 					qc->err_mask |= AC_ERR_HSM;
1148 				}
1149 
1150 				/* There are oddball controllers with
1151 				 * status register stuck at 0x7f and
1152 				 * lbal/m/h at zero which makes it
1153 				 * pass all other presence detection
1154 				 * mechanisms we have.  Set NODEV_HINT
1155 				 * for it.  Kernel bz#7241.
1156 				 */
1157 				if (status == 0x7f)
1158 					qc->err_mask |= AC_ERR_NODEV_HINT;
1159 
1160 				/* ata_pio_sectors() might change the
1161 				 * state to HSM_ST_LAST. so, the state
1162 				 * is changed after ata_pio_sectors().
1163 				 */
1164 				ap->hsm_task_state = HSM_ST_ERR;
1165 				goto fsm_start;
1166 			}
1167 
1168 			ata_pio_sectors(qc);
1169 
1170 			if (ap->hsm_task_state == HSM_ST_LAST &&
1171 			    (!(qc->tf.flags & ATA_TFLAG_WRITE))) {
1172 				/* all data read */
1173 				status = ata_wait_idle(ap);
1174 				goto fsm_start;
1175 			}
1176 		}
1177 
1178 		poll_next = 1;
1179 		break;
1180 
1181 	case HSM_ST_LAST:
1182 		if (unlikely(!ata_ok(status))) {
1183 			qc->err_mask |= __ac_err_mask(status);
1184 			ap->hsm_task_state = HSM_ST_ERR;
1185 			goto fsm_start;
1186 		}
1187 
1188 		/* no more data to transfer */
1189 		trace_ata_sff_hsm_command_complete(qc, status);
1190 
1191 		WARN_ON_ONCE(qc->err_mask & (AC_ERR_DEV | AC_ERR_HSM));
1192 
1193 		ap->hsm_task_state = HSM_ST_IDLE;
1194 
1195 		/* complete taskfile transaction */
1196 		ata_hsm_qc_complete(qc, in_wq);
1197 
1198 		poll_next = 0;
1199 		break;
1200 
1201 	case HSM_ST_ERR:
1202 		ap->hsm_task_state = HSM_ST_IDLE;
1203 
1204 		/* complete taskfile transaction */
1205 		ata_hsm_qc_complete(qc, in_wq);
1206 
1207 		poll_next = 0;
1208 		break;
1209 	default:
1210 		poll_next = 0;
1211 		WARN(true, "ata%d: SFF host state machine in invalid state %d",
1212 		     ap->print_id, ap->hsm_task_state);
1213 	}
1214 
1215 	return poll_next;
1216 }
1217 EXPORT_SYMBOL_GPL(ata_sff_hsm_move);
1218 
1219 void ata_sff_queue_work(struct work_struct *work)
1220 {
1221 	queue_work(ata_sff_wq, work);
1222 }
1223 EXPORT_SYMBOL_GPL(ata_sff_queue_work);
1224 
1225 void ata_sff_queue_delayed_work(struct delayed_work *dwork, unsigned long delay)
1226 {
1227 	queue_delayed_work(ata_sff_wq, dwork, delay);
1228 }
1229 EXPORT_SYMBOL_GPL(ata_sff_queue_delayed_work);
1230 
1231 void ata_sff_queue_pio_task(struct ata_link *link, unsigned long delay)
1232 {
1233 	struct ata_port *ap = link->ap;
1234 
1235 	WARN_ON((ap->sff_pio_task_link != NULL) &&
1236 		(ap->sff_pio_task_link != link));
1237 	ap->sff_pio_task_link = link;
1238 
1239 	/* may fail if ata_sff_flush_pio_task() in progress */
1240 	ata_sff_queue_delayed_work(&ap->sff_pio_task, msecs_to_jiffies(delay));
1241 }
1242 EXPORT_SYMBOL_GPL(ata_sff_queue_pio_task);
1243 
1244 void ata_sff_flush_pio_task(struct ata_port *ap)
1245 {
1246 	trace_ata_sff_flush_pio_task(ap);
1247 
1248 	cancel_delayed_work_sync(&ap->sff_pio_task);
1249 
1250 	/*
1251 	 * We wanna reset the HSM state to IDLE.  If we do so without
1252 	 * grabbing the port lock, critical sections protected by it which
1253 	 * expect the HSM state to stay stable may get surprised.  For
1254 	 * example, we may set IDLE in between the time
1255 	 * __ata_sff_port_intr() checks for HSM_ST_IDLE and before it calls
1256 	 * ata_sff_hsm_move() causing ata_sff_hsm_move() to BUG().
1257 	 */
1258 	spin_lock_irq(ap->lock);
1259 	ap->hsm_task_state = HSM_ST_IDLE;
1260 	spin_unlock_irq(ap->lock);
1261 
1262 	ap->sff_pio_task_link = NULL;
1263 }
1264 
1265 static void ata_sff_pio_task(struct work_struct *work)
1266 {
1267 	struct ata_port *ap =
1268 		container_of(work, struct ata_port, sff_pio_task.work);
1269 	struct ata_link *link = ap->sff_pio_task_link;
1270 	struct ata_queued_cmd *qc;
1271 	u8 status;
1272 	int poll_next;
1273 
1274 	spin_lock_irq(ap->lock);
1275 
1276 	BUG_ON(ap->sff_pio_task_link == NULL);
1277 	/* qc can be NULL if timeout occurred */
1278 	qc = ata_qc_from_tag(ap, link->active_tag);
1279 	if (!qc) {
1280 		ap->sff_pio_task_link = NULL;
1281 		goto out_unlock;
1282 	}
1283 
1284 fsm_start:
1285 	WARN_ON_ONCE(ap->hsm_task_state == HSM_ST_IDLE);
1286 
1287 	/*
1288 	 * This is purely heuristic.  This is a fast path.
1289 	 * Sometimes when we enter, BSY will be cleared in
1290 	 * a chk-status or two.  If not, the drive is probably seeking
1291 	 * or something.  Snooze for a couple msecs, then
1292 	 * chk-status again.  If still busy, queue delayed work.
1293 	 */
1294 	status = ata_sff_busy_wait(ap, ATA_BUSY, 5);
1295 	if (status & ATA_BUSY) {
1296 		spin_unlock_irq(ap->lock);
1297 		ata_msleep(ap, 2);
1298 		spin_lock_irq(ap->lock);
1299 
1300 		status = ata_sff_busy_wait(ap, ATA_BUSY, 10);
1301 		if (status & ATA_BUSY) {
1302 			ata_sff_queue_pio_task(link, ATA_SHORT_PAUSE);
1303 			goto out_unlock;
1304 		}
1305 	}
1306 
1307 	/*
1308 	 * hsm_move() may trigger another command to be processed.
1309 	 * clean the link beforehand.
1310 	 */
1311 	ap->sff_pio_task_link = NULL;
1312 	/* move the HSM */
1313 	poll_next = ata_sff_hsm_move(ap, qc, status, 1);
1314 
1315 	/* another command or interrupt handler
1316 	 * may be running at this point.
1317 	 */
1318 	if (poll_next)
1319 		goto fsm_start;
1320 out_unlock:
1321 	spin_unlock_irq(ap->lock);
1322 }
1323 
1324 /**
1325  *	ata_sff_qc_issue - issue taskfile to a SFF controller
1326  *	@qc: command to issue to device
1327  *
1328  *	This function issues a PIO or NODATA command to a SFF
1329  *	controller.
1330  *
1331  *	LOCKING:
1332  *	spin_lock_irqsave(host lock)
1333  *
1334  *	RETURNS:
1335  *	Zero on success, AC_ERR_* mask on failure
1336  */
1337 unsigned int ata_sff_qc_issue(struct ata_queued_cmd *qc)
1338 {
1339 	struct ata_port *ap = qc->ap;
1340 	struct ata_link *link = qc->dev->link;
1341 
1342 	/* Use polling pio if the LLD doesn't handle
1343 	 * interrupt driven pio and atapi CDB interrupt.
1344 	 */
1345 	if (ap->flags & ATA_FLAG_PIO_POLLING)
1346 		qc->tf.flags |= ATA_TFLAG_POLLING;
1347 
1348 	/* select the device */
1349 	ata_dev_select(ap, qc->dev->devno, 1, 0);
1350 
1351 	/* start the command */
1352 	switch (qc->tf.protocol) {
1353 	case ATA_PROT_NODATA:
1354 		if (qc->tf.flags & ATA_TFLAG_POLLING)
1355 			ata_qc_set_polling(qc);
1356 
1357 		ata_tf_to_host(ap, &qc->tf, qc->tag);
1358 		ap->hsm_task_state = HSM_ST_LAST;
1359 
1360 		if (qc->tf.flags & ATA_TFLAG_POLLING)
1361 			ata_sff_queue_pio_task(link, 0);
1362 
1363 		break;
1364 
1365 	case ATA_PROT_PIO:
1366 		if (qc->tf.flags & ATA_TFLAG_POLLING)
1367 			ata_qc_set_polling(qc);
1368 
1369 		ata_tf_to_host(ap, &qc->tf, qc->tag);
1370 
1371 		if (qc->tf.flags & ATA_TFLAG_WRITE) {
1372 			/* PIO data out protocol */
1373 			ap->hsm_task_state = HSM_ST_FIRST;
1374 			ata_sff_queue_pio_task(link, 0);
1375 
1376 			/* always send first data block using the
1377 			 * ata_sff_pio_task() codepath.
1378 			 */
1379 		} else {
1380 			/* PIO data in protocol */
1381 			ap->hsm_task_state = HSM_ST;
1382 
1383 			if (qc->tf.flags & ATA_TFLAG_POLLING)
1384 				ata_sff_queue_pio_task(link, 0);
1385 
1386 			/* if polling, ata_sff_pio_task() handles the
1387 			 * rest.  otherwise, interrupt handler takes
1388 			 * over from here.
1389 			 */
1390 		}
1391 
1392 		break;
1393 
1394 	case ATAPI_PROT_PIO:
1395 	case ATAPI_PROT_NODATA:
1396 		if (qc->tf.flags & ATA_TFLAG_POLLING)
1397 			ata_qc_set_polling(qc);
1398 
1399 		ata_tf_to_host(ap, &qc->tf, qc->tag);
1400 
1401 		ap->hsm_task_state = HSM_ST_FIRST;
1402 
1403 		/* send cdb by polling if no cdb interrupt */
1404 		if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
1405 		    (qc->tf.flags & ATA_TFLAG_POLLING))
1406 			ata_sff_queue_pio_task(link, 0);
1407 		break;
1408 
1409 	default:
1410 		return AC_ERR_SYSTEM;
1411 	}
1412 
1413 	return 0;
1414 }
1415 EXPORT_SYMBOL_GPL(ata_sff_qc_issue);
1416 
1417 /**
1418  *	ata_sff_qc_fill_rtf - fill result TF using ->sff_tf_read
1419  *	@qc: qc to fill result TF for
1420  *
1421  *	@qc is finished and result TF needs to be filled.  Fill it
1422  *	using ->sff_tf_read.
1423  *
1424  *	LOCKING:
1425  *	spin_lock_irqsave(host lock)
1426  *
1427  *	RETURNS:
1428  *	true indicating that result TF is successfully filled.
1429  */
1430 bool ata_sff_qc_fill_rtf(struct ata_queued_cmd *qc)
1431 {
1432 	qc->ap->ops->sff_tf_read(qc->ap, &qc->result_tf);
1433 	return true;
1434 }
1435 EXPORT_SYMBOL_GPL(ata_sff_qc_fill_rtf);
1436 
1437 static unsigned int ata_sff_idle_irq(struct ata_port *ap)
1438 {
1439 	ap->stats.idle_irq++;
1440 
1441 #ifdef ATA_IRQ_TRAP
1442 	if ((ap->stats.idle_irq % 1000) == 0) {
1443 		ap->ops->sff_check_status(ap);
1444 		if (ap->ops->sff_irq_clear)
1445 			ap->ops->sff_irq_clear(ap);
1446 		ata_port_warn(ap, "irq trap\n");
1447 		return 1;
1448 	}
1449 #endif
1450 	return 0;	/* irq not handled */
1451 }
1452 
1453 static unsigned int __ata_sff_port_intr(struct ata_port *ap,
1454 					struct ata_queued_cmd *qc,
1455 					bool hsmv_on_idle)
1456 {
1457 	u8 status;
1458 
1459 	trace_ata_sff_port_intr(qc, hsmv_on_idle);
1460 
1461 	/* Check whether we are expecting interrupt in this state */
1462 	switch (ap->hsm_task_state) {
1463 	case HSM_ST_FIRST:
1464 		/* Some pre-ATAPI-4 devices assert INTRQ
1465 		 * at this state when ready to receive CDB.
1466 		 */
1467 
1468 		/* Check the ATA_DFLAG_CDB_INTR flag is enough here.
1469 		 * The flag was turned on only for atapi devices.  No
1470 		 * need to check ata_is_atapi(qc->tf.protocol) again.
1471 		 */
1472 		if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
1473 			return ata_sff_idle_irq(ap);
1474 		break;
1475 	case HSM_ST_IDLE:
1476 		return ata_sff_idle_irq(ap);
1477 	default:
1478 		break;
1479 	}
1480 
1481 	/* check main status, clearing INTRQ if needed */
1482 	status = ata_sff_irq_status(ap);
1483 	if (status & ATA_BUSY) {
1484 		if (hsmv_on_idle) {
1485 			/* BMDMA engine is already stopped, we're screwed */
1486 			qc->err_mask |= AC_ERR_HSM;
1487 			ap->hsm_task_state = HSM_ST_ERR;
1488 		} else
1489 			return ata_sff_idle_irq(ap);
1490 	}
1491 
1492 	/* clear irq events */
1493 	if (ap->ops->sff_irq_clear)
1494 		ap->ops->sff_irq_clear(ap);
1495 
1496 	ata_sff_hsm_move(ap, qc, status, 0);
1497 
1498 	return 1;	/* irq handled */
1499 }
1500 
1501 /**
1502  *	ata_sff_port_intr - Handle SFF port interrupt
1503  *	@ap: Port on which interrupt arrived (possibly...)
1504  *	@qc: Taskfile currently active in engine
1505  *
1506  *	Handle port interrupt for given queued command.
1507  *
1508  *	LOCKING:
1509  *	spin_lock_irqsave(host lock)
1510  *
1511  *	RETURNS:
1512  *	One if interrupt was handled, zero if not (shared irq).
1513  */
1514 unsigned int ata_sff_port_intr(struct ata_port *ap, struct ata_queued_cmd *qc)
1515 {
1516 	return __ata_sff_port_intr(ap, qc, false);
1517 }
1518 EXPORT_SYMBOL_GPL(ata_sff_port_intr);
1519 
1520 static inline irqreturn_t __ata_sff_interrupt(int irq, void *dev_instance,
1521 	unsigned int (*port_intr)(struct ata_port *, struct ata_queued_cmd *))
1522 {
1523 	struct ata_host *host = dev_instance;
1524 	bool retried = false;
1525 	unsigned int i;
1526 	unsigned int handled, idle, polling;
1527 	unsigned long flags;
1528 
1529 	/* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
1530 	spin_lock_irqsave(&host->lock, flags);
1531 
1532 retry:
1533 	handled = idle = polling = 0;
1534 	for (i = 0; i < host->n_ports; i++) {
1535 		struct ata_port *ap = host->ports[i];
1536 		struct ata_queued_cmd *qc;
1537 
1538 		qc = ata_qc_from_tag(ap, ap->link.active_tag);
1539 		if (qc) {
1540 			if (!(qc->tf.flags & ATA_TFLAG_POLLING))
1541 				handled |= port_intr(ap, qc);
1542 			else
1543 				polling |= 1 << i;
1544 		} else
1545 			idle |= 1 << i;
1546 	}
1547 
1548 	/*
1549 	 * If no port was expecting IRQ but the controller is actually
1550 	 * asserting IRQ line, nobody cared will ensue.  Check IRQ
1551 	 * pending status if available and clear spurious IRQ.
1552 	 */
1553 	if (!handled && !retried) {
1554 		bool retry = false;
1555 
1556 		for (i = 0; i < host->n_ports; i++) {
1557 			struct ata_port *ap = host->ports[i];
1558 
1559 			if (polling & (1 << i))
1560 				continue;
1561 
1562 			if (!ap->ops->sff_irq_check ||
1563 			    !ap->ops->sff_irq_check(ap))
1564 				continue;
1565 
1566 			if (idle & (1 << i)) {
1567 				ap->ops->sff_check_status(ap);
1568 				if (ap->ops->sff_irq_clear)
1569 					ap->ops->sff_irq_clear(ap);
1570 			} else {
1571 				/* clear INTRQ and check if BUSY cleared */
1572 				if (!(ap->ops->sff_check_status(ap) & ATA_BUSY))
1573 					retry |= true;
1574 				/*
1575 				 * With command in flight, we can't do
1576 				 * sff_irq_clear() w/o racing with completion.
1577 				 */
1578 			}
1579 		}
1580 
1581 		if (retry) {
1582 			retried = true;
1583 			goto retry;
1584 		}
1585 	}
1586 
1587 	spin_unlock_irqrestore(&host->lock, flags);
1588 
1589 	return IRQ_RETVAL(handled);
1590 }
1591 
1592 /**
1593  *	ata_sff_interrupt - Default SFF ATA host interrupt handler
1594  *	@irq: irq line (unused)
1595  *	@dev_instance: pointer to our ata_host information structure
1596  *
1597  *	Default interrupt handler for PCI IDE devices.  Calls
1598  *	ata_sff_port_intr() for each port that is not disabled.
1599  *
1600  *	LOCKING:
1601  *	Obtains host lock during operation.
1602  *
1603  *	RETURNS:
1604  *	IRQ_NONE or IRQ_HANDLED.
1605  */
1606 irqreturn_t ata_sff_interrupt(int irq, void *dev_instance)
1607 {
1608 	return __ata_sff_interrupt(irq, dev_instance, ata_sff_port_intr);
1609 }
1610 EXPORT_SYMBOL_GPL(ata_sff_interrupt);
1611 
1612 /**
1613  *	ata_sff_lost_interrupt	-	Check for an apparent lost interrupt
1614  *	@ap: port that appears to have timed out
1615  *
1616  *	Called from the libata error handlers when the core code suspects
1617  *	an interrupt has been lost. If it has complete anything we can and
1618  *	then return. Interface must support altstatus for this faster
1619  *	recovery to occur.
1620  *
1621  *	Locking:
1622  *	Caller holds host lock
1623  */
1624 
1625 void ata_sff_lost_interrupt(struct ata_port *ap)
1626 {
1627 	u8 status;
1628 	struct ata_queued_cmd *qc;
1629 
1630 	/* Only one outstanding command per SFF channel */
1631 	qc = ata_qc_from_tag(ap, ap->link.active_tag);
1632 	/* We cannot lose an interrupt on a non-existent or polled command */
1633 	if (!qc || qc->tf.flags & ATA_TFLAG_POLLING)
1634 		return;
1635 	/* See if the controller thinks it is still busy - if so the command
1636 	   isn't a lost IRQ but is still in progress */
1637 	status = ata_sff_altstatus(ap);
1638 	if (status & ATA_BUSY)
1639 		return;
1640 
1641 	/* There was a command running, we are no longer busy and we have
1642 	   no interrupt. */
1643 	ata_port_warn(ap, "lost interrupt (Status 0x%x)\n",
1644 								status);
1645 	/* Run the host interrupt logic as if the interrupt had not been
1646 	   lost */
1647 	ata_sff_port_intr(ap, qc);
1648 }
1649 EXPORT_SYMBOL_GPL(ata_sff_lost_interrupt);
1650 
1651 /**
1652  *	ata_sff_freeze - Freeze SFF controller port
1653  *	@ap: port to freeze
1654  *
1655  *	Freeze SFF controller port.
1656  *
1657  *	LOCKING:
1658  *	Inherited from caller.
1659  */
1660 void ata_sff_freeze(struct ata_port *ap)
1661 {
1662 	ap->ctl |= ATA_NIEN;
1663 	ap->last_ctl = ap->ctl;
1664 
1665 	if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr)
1666 		ata_sff_set_devctl(ap, ap->ctl);
1667 
1668 	/* Under certain circumstances, some controllers raise IRQ on
1669 	 * ATA_NIEN manipulation.  Also, many controllers fail to mask
1670 	 * previously pending IRQ on ATA_NIEN assertion.  Clear it.
1671 	 */
1672 	ap->ops->sff_check_status(ap);
1673 
1674 	if (ap->ops->sff_irq_clear)
1675 		ap->ops->sff_irq_clear(ap);
1676 }
1677 EXPORT_SYMBOL_GPL(ata_sff_freeze);
1678 
1679 /**
1680  *	ata_sff_thaw - Thaw SFF controller port
1681  *	@ap: port to thaw
1682  *
1683  *	Thaw SFF controller port.
1684  *
1685  *	LOCKING:
1686  *	Inherited from caller.
1687  */
1688 void ata_sff_thaw(struct ata_port *ap)
1689 {
1690 	/* clear & re-enable interrupts */
1691 	ap->ops->sff_check_status(ap);
1692 	if (ap->ops->sff_irq_clear)
1693 		ap->ops->sff_irq_clear(ap);
1694 	ata_sff_irq_on(ap);
1695 }
1696 EXPORT_SYMBOL_GPL(ata_sff_thaw);
1697 
1698 /**
1699  *	ata_sff_prereset - prepare SFF link for reset
1700  *	@link: SFF link to be reset
1701  *	@deadline: deadline jiffies for the operation
1702  *
1703  *	SFF link @link is about to be reset.  Initialize it.  It first
1704  *	calls ata_std_prereset() and wait for !BSY if the port is
1705  *	being softreset.
1706  *
1707  *	LOCKING:
1708  *	Kernel thread context (may sleep)
1709  *
1710  *	RETURNS:
1711  *	0 on success, -errno otherwise.
1712  */
1713 int ata_sff_prereset(struct ata_link *link, unsigned long deadline)
1714 {
1715 	struct ata_eh_context *ehc = &link->eh_context;
1716 	int rc;
1717 
1718 	rc = ata_std_prereset(link, deadline);
1719 	if (rc)
1720 		return rc;
1721 
1722 	/* if we're about to do hardreset, nothing more to do */
1723 	if (ehc->i.action & ATA_EH_HARDRESET)
1724 		return 0;
1725 
1726 	/* wait for !BSY if we don't know that no device is attached */
1727 	if (!ata_link_offline(link)) {
1728 		rc = ata_sff_wait_ready(link, deadline);
1729 		if (rc && rc != -ENODEV) {
1730 			ata_link_warn(link,
1731 				      "device not ready (errno=%d), forcing hardreset\n",
1732 				      rc);
1733 			ehc->i.action |= ATA_EH_HARDRESET;
1734 		}
1735 	}
1736 
1737 	return 0;
1738 }
1739 EXPORT_SYMBOL_GPL(ata_sff_prereset);
1740 
1741 /**
1742  *	ata_devchk - PATA device presence detection
1743  *	@ap: ATA channel to examine
1744  *	@device: Device to examine (starting at zero)
1745  *
1746  *	This technique was originally described in
1747  *	Hale Landis's ATADRVR (www.ata-atapi.com), and
1748  *	later found its way into the ATA/ATAPI spec.
1749  *
1750  *	Write a pattern to the ATA shadow registers,
1751  *	and if a device is present, it will respond by
1752  *	correctly storing and echoing back the
1753  *	ATA shadow register contents.
1754  *
1755  *	LOCKING:
1756  *	caller.
1757  */
1758 static unsigned int ata_devchk(struct ata_port *ap, unsigned int device)
1759 {
1760 	struct ata_ioports *ioaddr = &ap->ioaddr;
1761 	u8 nsect, lbal;
1762 
1763 	ap->ops->sff_dev_select(ap, device);
1764 
1765 	iowrite8(0x55, ioaddr->nsect_addr);
1766 	iowrite8(0xaa, ioaddr->lbal_addr);
1767 
1768 	iowrite8(0xaa, ioaddr->nsect_addr);
1769 	iowrite8(0x55, ioaddr->lbal_addr);
1770 
1771 	iowrite8(0x55, ioaddr->nsect_addr);
1772 	iowrite8(0xaa, ioaddr->lbal_addr);
1773 
1774 	nsect = ioread8(ioaddr->nsect_addr);
1775 	lbal = ioread8(ioaddr->lbal_addr);
1776 
1777 	if ((nsect == 0x55) && (lbal == 0xaa))
1778 		return 1;	/* we found a device */
1779 
1780 	return 0;		/* nothing found */
1781 }
1782 
1783 /**
1784  *	ata_sff_dev_classify - Parse returned ATA device signature
1785  *	@dev: ATA device to classify (starting at zero)
1786  *	@present: device seems present
1787  *	@r_err: Value of error register on completion
1788  *
1789  *	After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
1790  *	an ATA/ATAPI-defined set of values is placed in the ATA
1791  *	shadow registers, indicating the results of device detection
1792  *	and diagnostics.
1793  *
1794  *	Select the ATA device, and read the values from the ATA shadow
1795  *	registers.  Then parse according to the Error register value,
1796  *	and the spec-defined values examined by ata_dev_classify().
1797  *
1798  *	LOCKING:
1799  *	caller.
1800  *
1801  *	RETURNS:
1802  *	Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
1803  */
1804 unsigned int ata_sff_dev_classify(struct ata_device *dev, int present,
1805 				  u8 *r_err)
1806 {
1807 	struct ata_port *ap = dev->link->ap;
1808 	struct ata_taskfile tf;
1809 	unsigned int class;
1810 	u8 err;
1811 
1812 	ap->ops->sff_dev_select(ap, dev->devno);
1813 
1814 	memset(&tf, 0, sizeof(tf));
1815 
1816 	ap->ops->sff_tf_read(ap, &tf);
1817 	err = tf.feature;
1818 	if (r_err)
1819 		*r_err = err;
1820 
1821 	/* see if device passed diags: continue and warn later */
1822 	if (err == 0)
1823 		/* diagnostic fail : do nothing _YET_ */
1824 		dev->horkage |= ATA_HORKAGE_DIAGNOSTIC;
1825 	else if (err == 1)
1826 		/* do nothing */ ;
1827 	else if ((dev->devno == 0) && (err == 0x81))
1828 		/* do nothing */ ;
1829 	else
1830 		return ATA_DEV_NONE;
1831 
1832 	/* determine if device is ATA or ATAPI */
1833 	class = ata_port_classify(ap, &tf);
1834 
1835 	if (class == ATA_DEV_UNKNOWN) {
1836 		/* If the device failed diagnostic, it's likely to
1837 		 * have reported incorrect device signature too.
1838 		 * Assume ATA device if the device seems present but
1839 		 * device signature is invalid with diagnostic
1840 		 * failure.
1841 		 */
1842 		if (present && (dev->horkage & ATA_HORKAGE_DIAGNOSTIC))
1843 			class = ATA_DEV_ATA;
1844 		else
1845 			class = ATA_DEV_NONE;
1846 	} else if ((class == ATA_DEV_ATA) &&
1847 		   (ap->ops->sff_check_status(ap) == 0))
1848 		class = ATA_DEV_NONE;
1849 
1850 	return class;
1851 }
1852 EXPORT_SYMBOL_GPL(ata_sff_dev_classify);
1853 
1854 /**
1855  *	ata_sff_wait_after_reset - wait for devices to become ready after reset
1856  *	@link: SFF link which is just reset
1857  *	@devmask: mask of present devices
1858  *	@deadline: deadline jiffies for the operation
1859  *
1860  *	Wait devices attached to SFF @link to become ready after
1861  *	reset.  It contains preceding 150ms wait to avoid accessing TF
1862  *	status register too early.
1863  *
1864  *	LOCKING:
1865  *	Kernel thread context (may sleep).
1866  *
1867  *	RETURNS:
1868  *	0 on success, -ENODEV if some or all of devices in @devmask
1869  *	don't seem to exist.  -errno on other errors.
1870  */
1871 int ata_sff_wait_after_reset(struct ata_link *link, unsigned int devmask,
1872 			     unsigned long deadline)
1873 {
1874 	struct ata_port *ap = link->ap;
1875 	struct ata_ioports *ioaddr = &ap->ioaddr;
1876 	unsigned int dev0 = devmask & (1 << 0);
1877 	unsigned int dev1 = devmask & (1 << 1);
1878 	int rc, ret = 0;
1879 
1880 	ata_msleep(ap, ATA_WAIT_AFTER_RESET);
1881 
1882 	/* always check readiness of the master device */
1883 	rc = ata_sff_wait_ready(link, deadline);
1884 	/* -ENODEV means the odd clown forgot the D7 pulldown resistor
1885 	 * and TF status is 0xff, bail out on it too.
1886 	 */
1887 	if (rc)
1888 		return rc;
1889 
1890 	/* if device 1 was found in ata_devchk, wait for register
1891 	 * access briefly, then wait for BSY to clear.
1892 	 */
1893 	if (dev1) {
1894 		int i;
1895 
1896 		ap->ops->sff_dev_select(ap, 1);
1897 
1898 		/* Wait for register access.  Some ATAPI devices fail
1899 		 * to set nsect/lbal after reset, so don't waste too
1900 		 * much time on it.  We're gonna wait for !BSY anyway.
1901 		 */
1902 		for (i = 0; i < 2; i++) {
1903 			u8 nsect, lbal;
1904 
1905 			nsect = ioread8(ioaddr->nsect_addr);
1906 			lbal = ioread8(ioaddr->lbal_addr);
1907 			if ((nsect == 1) && (lbal == 1))
1908 				break;
1909 			ata_msleep(ap, 50);	/* give drive a breather */
1910 		}
1911 
1912 		rc = ata_sff_wait_ready(link, deadline);
1913 		if (rc) {
1914 			if (rc != -ENODEV)
1915 				return rc;
1916 			ret = rc;
1917 		}
1918 	}
1919 
1920 	/* is all this really necessary? */
1921 	ap->ops->sff_dev_select(ap, 0);
1922 	if (dev1)
1923 		ap->ops->sff_dev_select(ap, 1);
1924 	if (dev0)
1925 		ap->ops->sff_dev_select(ap, 0);
1926 
1927 	return ret;
1928 }
1929 EXPORT_SYMBOL_GPL(ata_sff_wait_after_reset);
1930 
1931 static int ata_bus_softreset(struct ata_port *ap, unsigned int devmask,
1932 			     unsigned long deadline)
1933 {
1934 	struct ata_ioports *ioaddr = &ap->ioaddr;
1935 
1936 	if (ap->ioaddr.ctl_addr) {
1937 		/* software reset.  causes dev0 to be selected */
1938 		iowrite8(ap->ctl, ioaddr->ctl_addr);
1939 		udelay(20);	/* FIXME: flush */
1940 		iowrite8(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
1941 		udelay(20);	/* FIXME: flush */
1942 		iowrite8(ap->ctl, ioaddr->ctl_addr);
1943 		ap->last_ctl = ap->ctl;
1944 	}
1945 
1946 	/* wait the port to become ready */
1947 	return ata_sff_wait_after_reset(&ap->link, devmask, deadline);
1948 }
1949 
1950 /**
1951  *	ata_sff_softreset - reset host port via ATA SRST
1952  *	@link: ATA link to reset
1953  *	@classes: resulting classes of attached devices
1954  *	@deadline: deadline jiffies for the operation
1955  *
1956  *	Reset host port using ATA SRST.
1957  *
1958  *	LOCKING:
1959  *	Kernel thread context (may sleep)
1960  *
1961  *	RETURNS:
1962  *	0 on success, -errno otherwise.
1963  */
1964 int ata_sff_softreset(struct ata_link *link, unsigned int *classes,
1965 		      unsigned long deadline)
1966 {
1967 	struct ata_port *ap = link->ap;
1968 	unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
1969 	unsigned int devmask = 0;
1970 	int rc;
1971 	u8 err;
1972 
1973 	/* determine if device 0/1 are present */
1974 	if (ata_devchk(ap, 0))
1975 		devmask |= (1 << 0);
1976 	if (slave_possible && ata_devchk(ap, 1))
1977 		devmask |= (1 << 1);
1978 
1979 	/* select device 0 again */
1980 	ap->ops->sff_dev_select(ap, 0);
1981 
1982 	/* issue bus reset */
1983 	rc = ata_bus_softreset(ap, devmask, deadline);
1984 	/* if link is occupied, -ENODEV too is an error */
1985 	if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
1986 		ata_link_err(link, "SRST failed (errno=%d)\n", rc);
1987 		return rc;
1988 	}
1989 
1990 	/* determine by signature whether we have ATA or ATAPI devices */
1991 	classes[0] = ata_sff_dev_classify(&link->device[0],
1992 					  devmask & (1 << 0), &err);
1993 	if (slave_possible && err != 0x81)
1994 		classes[1] = ata_sff_dev_classify(&link->device[1],
1995 						  devmask & (1 << 1), &err);
1996 
1997 	return 0;
1998 }
1999 EXPORT_SYMBOL_GPL(ata_sff_softreset);
2000 
2001 /**
2002  *	sata_sff_hardreset - reset host port via SATA phy reset
2003  *	@link: link to reset
2004  *	@class: resulting class of attached device
2005  *	@deadline: deadline jiffies for the operation
2006  *
2007  *	SATA phy-reset host port using DET bits of SControl register,
2008  *	wait for !BSY and classify the attached device.
2009  *
2010  *	LOCKING:
2011  *	Kernel thread context (may sleep)
2012  *
2013  *	RETURNS:
2014  *	0 on success, -errno otherwise.
2015  */
2016 int sata_sff_hardreset(struct ata_link *link, unsigned int *class,
2017 		       unsigned long deadline)
2018 {
2019 	struct ata_eh_context *ehc = &link->eh_context;
2020 	const unsigned long *timing = sata_ehc_deb_timing(ehc);
2021 	bool online;
2022 	int rc;
2023 
2024 	rc = sata_link_hardreset(link, timing, deadline, &online,
2025 				 ata_sff_check_ready);
2026 	if (online)
2027 		*class = ata_sff_dev_classify(link->device, 1, NULL);
2028 
2029 	return rc;
2030 }
2031 EXPORT_SYMBOL_GPL(sata_sff_hardreset);
2032 
2033 /**
2034  *	ata_sff_postreset - SFF postreset callback
2035  *	@link: the target SFF ata_link
2036  *	@classes: classes of attached devices
2037  *
2038  *	This function is invoked after a successful reset.  It first
2039  *	calls ata_std_postreset() and performs SFF specific postreset
2040  *	processing.
2041  *
2042  *	LOCKING:
2043  *	Kernel thread context (may sleep)
2044  */
2045 void ata_sff_postreset(struct ata_link *link, unsigned int *classes)
2046 {
2047 	struct ata_port *ap = link->ap;
2048 
2049 	ata_std_postreset(link, classes);
2050 
2051 	/* is double-select really necessary? */
2052 	if (classes[0] != ATA_DEV_NONE)
2053 		ap->ops->sff_dev_select(ap, 1);
2054 	if (classes[1] != ATA_DEV_NONE)
2055 		ap->ops->sff_dev_select(ap, 0);
2056 
2057 	/* bail out if no device is present */
2058 	if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE)
2059 		return;
2060 
2061 	/* set up device control */
2062 	if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr) {
2063 		ata_sff_set_devctl(ap, ap->ctl);
2064 		ap->last_ctl = ap->ctl;
2065 	}
2066 }
2067 EXPORT_SYMBOL_GPL(ata_sff_postreset);
2068 
2069 /**
2070  *	ata_sff_drain_fifo - Stock FIFO drain logic for SFF controllers
2071  *	@qc: command
2072  *
2073  *	Drain the FIFO and device of any stuck data following a command
2074  *	failing to complete. In some cases this is necessary before a
2075  *	reset will recover the device.
2076  *
2077  */
2078 
2079 void ata_sff_drain_fifo(struct ata_queued_cmd *qc)
2080 {
2081 	int count;
2082 	struct ata_port *ap;
2083 
2084 	/* We only need to flush incoming data when a command was running */
2085 	if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE)
2086 		return;
2087 
2088 	ap = qc->ap;
2089 	/* Drain up to 64K of data before we give up this recovery method */
2090 	for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ)
2091 						&& count < 65536; count += 2)
2092 		ioread16(ap->ioaddr.data_addr);
2093 
2094 	if (count)
2095 		ata_port_dbg(ap, "drained %d bytes to clear DRQ\n", count);
2096 
2097 }
2098 EXPORT_SYMBOL_GPL(ata_sff_drain_fifo);
2099 
2100 /**
2101  *	ata_sff_error_handler - Stock error handler for SFF controller
2102  *	@ap: port to handle error for
2103  *
2104  *	Stock error handler for SFF controller.  It can handle both
2105  *	PATA and SATA controllers.  Many controllers should be able to
2106  *	use this EH as-is or with some added handling before and
2107  *	after.
2108  *
2109  *	LOCKING:
2110  *	Kernel thread context (may sleep)
2111  */
2112 void ata_sff_error_handler(struct ata_port *ap)
2113 {
2114 	ata_reset_fn_t softreset = ap->ops->softreset;
2115 	ata_reset_fn_t hardreset = ap->ops->hardreset;
2116 	struct ata_queued_cmd *qc;
2117 	unsigned long flags;
2118 
2119 	qc = __ata_qc_from_tag(ap, ap->link.active_tag);
2120 	if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
2121 		qc = NULL;
2122 
2123 	spin_lock_irqsave(ap->lock, flags);
2124 
2125 	/*
2126 	 * We *MUST* do FIFO draining before we issue a reset as
2127 	 * several devices helpfully clear their internal state and
2128 	 * will lock solid if we touch the data port post reset. Pass
2129 	 * qc in case anyone wants to do different PIO/DMA recovery or
2130 	 * has per command fixups
2131 	 */
2132 	if (ap->ops->sff_drain_fifo)
2133 		ap->ops->sff_drain_fifo(qc);
2134 
2135 	spin_unlock_irqrestore(ap->lock, flags);
2136 
2137 	/* ignore built-in hardresets if SCR access is not available */
2138 	if ((hardreset == sata_std_hardreset ||
2139 	     hardreset == sata_sff_hardreset) && !sata_scr_valid(&ap->link))
2140 		hardreset = NULL;
2141 
2142 	ata_do_eh(ap, ap->ops->prereset, softreset, hardreset,
2143 		  ap->ops->postreset);
2144 }
2145 EXPORT_SYMBOL_GPL(ata_sff_error_handler);
2146 
2147 /**
2148  *	ata_sff_std_ports - initialize ioaddr with standard port offsets.
2149  *	@ioaddr: IO address structure to be initialized
2150  *
2151  *	Utility function which initializes data_addr, error_addr,
2152  *	feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
2153  *	device_addr, status_addr, and command_addr to standard offsets
2154  *	relative to cmd_addr.
2155  *
2156  *	Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
2157  */
2158 void ata_sff_std_ports(struct ata_ioports *ioaddr)
2159 {
2160 	ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
2161 	ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
2162 	ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
2163 	ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
2164 	ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
2165 	ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
2166 	ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
2167 	ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
2168 	ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
2169 	ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
2170 }
2171 EXPORT_SYMBOL_GPL(ata_sff_std_ports);
2172 
2173 #ifdef CONFIG_PCI
2174 
2175 static int ata_resources_present(struct pci_dev *pdev, int port)
2176 {
2177 	int i;
2178 
2179 	/* Check the PCI resources for this channel are enabled */
2180 	port = port * 2;
2181 	for (i = 0; i < 2; i++) {
2182 		if (pci_resource_start(pdev, port + i) == 0 ||
2183 		    pci_resource_len(pdev, port + i) == 0)
2184 			return 0;
2185 	}
2186 	return 1;
2187 }
2188 
2189 /**
2190  *	ata_pci_sff_init_host - acquire native PCI ATA resources and init host
2191  *	@host: target ATA host
2192  *
2193  *	Acquire native PCI ATA resources for @host and initialize the
2194  *	first two ports of @host accordingly.  Ports marked dummy are
2195  *	skipped and allocation failure makes the port dummy.
2196  *
2197  *	Note that native PCI resources are valid even for legacy hosts
2198  *	as we fix up pdev resources array early in boot, so this
2199  *	function can be used for both native and legacy SFF hosts.
2200  *
2201  *	LOCKING:
2202  *	Inherited from calling layer (may sleep).
2203  *
2204  *	RETURNS:
2205  *	0 if at least one port is initialized, -ENODEV if no port is
2206  *	available.
2207  */
2208 int ata_pci_sff_init_host(struct ata_host *host)
2209 {
2210 	struct device *gdev = host->dev;
2211 	struct pci_dev *pdev = to_pci_dev(gdev);
2212 	unsigned int mask = 0;
2213 	int i, rc;
2214 
2215 	/* request, iomap BARs and init port addresses accordingly */
2216 	for (i = 0; i < 2; i++) {
2217 		struct ata_port *ap = host->ports[i];
2218 		int base = i * 2;
2219 		void __iomem * const *iomap;
2220 
2221 		if (ata_port_is_dummy(ap))
2222 			continue;
2223 
2224 		/* Discard disabled ports.  Some controllers show
2225 		 * their unused channels this way.  Disabled ports are
2226 		 * made dummy.
2227 		 */
2228 		if (!ata_resources_present(pdev, i)) {
2229 			ap->ops = &ata_dummy_port_ops;
2230 			continue;
2231 		}
2232 
2233 		rc = pcim_iomap_regions(pdev, 0x3 << base,
2234 					dev_driver_string(gdev));
2235 		if (rc) {
2236 			dev_warn(gdev,
2237 				 "failed to request/iomap BARs for port %d (errno=%d)\n",
2238 				 i, rc);
2239 			if (rc == -EBUSY)
2240 				pcim_pin_device(pdev);
2241 			ap->ops = &ata_dummy_port_ops;
2242 			continue;
2243 		}
2244 		host->iomap = iomap = pcim_iomap_table(pdev);
2245 
2246 		ap->ioaddr.cmd_addr = iomap[base];
2247 		ap->ioaddr.altstatus_addr =
2248 		ap->ioaddr.ctl_addr = (void __iomem *)
2249 			((unsigned long)iomap[base + 1] | ATA_PCI_CTL_OFS);
2250 		ata_sff_std_ports(&ap->ioaddr);
2251 
2252 		ata_port_desc(ap, "cmd 0x%llx ctl 0x%llx",
2253 			(unsigned long long)pci_resource_start(pdev, base),
2254 			(unsigned long long)pci_resource_start(pdev, base + 1));
2255 
2256 		mask |= 1 << i;
2257 	}
2258 
2259 	if (!mask) {
2260 		dev_err(gdev, "no available native port\n");
2261 		return -ENODEV;
2262 	}
2263 
2264 	return 0;
2265 }
2266 EXPORT_SYMBOL_GPL(ata_pci_sff_init_host);
2267 
2268 /**
2269  *	ata_pci_sff_prepare_host - helper to prepare PCI PIO-only SFF ATA host
2270  *	@pdev: target PCI device
2271  *	@ppi: array of port_info, must be enough for two ports
2272  *	@r_host: out argument for the initialized ATA host
2273  *
2274  *	Helper to allocate PIO-only SFF ATA host for @pdev, acquire
2275  *	all PCI resources and initialize it accordingly in one go.
2276  *
2277  *	LOCKING:
2278  *	Inherited from calling layer (may sleep).
2279  *
2280  *	RETURNS:
2281  *	0 on success, -errno otherwise.
2282  */
2283 int ata_pci_sff_prepare_host(struct pci_dev *pdev,
2284 			     const struct ata_port_info * const *ppi,
2285 			     struct ata_host **r_host)
2286 {
2287 	struct ata_host *host;
2288 	int rc;
2289 
2290 	if (!devres_open_group(&pdev->dev, NULL, GFP_KERNEL))
2291 		return -ENOMEM;
2292 
2293 	host = ata_host_alloc_pinfo(&pdev->dev, ppi, 2);
2294 	if (!host) {
2295 		dev_err(&pdev->dev, "failed to allocate ATA host\n");
2296 		rc = -ENOMEM;
2297 		goto err_out;
2298 	}
2299 
2300 	rc = ata_pci_sff_init_host(host);
2301 	if (rc)
2302 		goto err_out;
2303 
2304 	devres_remove_group(&pdev->dev, NULL);
2305 	*r_host = host;
2306 	return 0;
2307 
2308 err_out:
2309 	devres_release_group(&pdev->dev, NULL);
2310 	return rc;
2311 }
2312 EXPORT_SYMBOL_GPL(ata_pci_sff_prepare_host);
2313 
2314 /**
2315  *	ata_pci_sff_activate_host - start SFF host, request IRQ and register it
2316  *	@host: target SFF ATA host
2317  *	@irq_handler: irq_handler used when requesting IRQ(s)
2318  *	@sht: scsi_host_template to use when registering the host
2319  *
2320  *	This is the counterpart of ata_host_activate() for SFF ATA
2321  *	hosts.  This separate helper is necessary because SFF hosts
2322  *	use two separate interrupts in legacy mode.
2323  *
2324  *	LOCKING:
2325  *	Inherited from calling layer (may sleep).
2326  *
2327  *	RETURNS:
2328  *	0 on success, -errno otherwise.
2329  */
2330 int ata_pci_sff_activate_host(struct ata_host *host,
2331 			      irq_handler_t irq_handler,
2332 			      struct scsi_host_template *sht)
2333 {
2334 	struct device *dev = host->dev;
2335 	struct pci_dev *pdev = to_pci_dev(dev);
2336 	const char *drv_name = dev_driver_string(host->dev);
2337 	int legacy_mode = 0, rc;
2338 
2339 	rc = ata_host_start(host);
2340 	if (rc)
2341 		return rc;
2342 
2343 	if ((pdev->class >> 8) == PCI_CLASS_STORAGE_IDE) {
2344 		u8 tmp8, mask = 0;
2345 
2346 		/*
2347 		 * ATA spec says we should use legacy mode when one
2348 		 * port is in legacy mode, but disabled ports on some
2349 		 * PCI hosts appear as fixed legacy ports, e.g SB600/700
2350 		 * on which the secondary port is not wired, so
2351 		 * ignore ports that are marked as 'dummy' during
2352 		 * this check
2353 		 */
2354 		pci_read_config_byte(pdev, PCI_CLASS_PROG, &tmp8);
2355 		if (!ata_port_is_dummy(host->ports[0]))
2356 			mask |= (1 << 0);
2357 		if (!ata_port_is_dummy(host->ports[1]))
2358 			mask |= (1 << 2);
2359 		if ((tmp8 & mask) != mask)
2360 			legacy_mode = 1;
2361 	}
2362 
2363 	if (!devres_open_group(dev, NULL, GFP_KERNEL))
2364 		return -ENOMEM;
2365 
2366 	if (!legacy_mode && pdev->irq) {
2367 		int i;
2368 
2369 		rc = devm_request_irq(dev, pdev->irq, irq_handler,
2370 				      IRQF_SHARED, drv_name, host);
2371 		if (rc)
2372 			goto out;
2373 
2374 		for (i = 0; i < 2; i++) {
2375 			if (ata_port_is_dummy(host->ports[i]))
2376 				continue;
2377 			ata_port_desc(host->ports[i], "irq %d", pdev->irq);
2378 		}
2379 	} else if (legacy_mode) {
2380 		if (!ata_port_is_dummy(host->ports[0])) {
2381 			rc = devm_request_irq(dev, ATA_PRIMARY_IRQ(pdev),
2382 					      irq_handler, IRQF_SHARED,
2383 					      drv_name, host);
2384 			if (rc)
2385 				goto out;
2386 
2387 			ata_port_desc(host->ports[0], "irq %d",
2388 				      ATA_PRIMARY_IRQ(pdev));
2389 		}
2390 
2391 		if (!ata_port_is_dummy(host->ports[1])) {
2392 			rc = devm_request_irq(dev, ATA_SECONDARY_IRQ(pdev),
2393 					      irq_handler, IRQF_SHARED,
2394 					      drv_name, host);
2395 			if (rc)
2396 				goto out;
2397 
2398 			ata_port_desc(host->ports[1], "irq %d",
2399 				      ATA_SECONDARY_IRQ(pdev));
2400 		}
2401 	}
2402 
2403 	rc = ata_host_register(host, sht);
2404 out:
2405 	if (rc == 0)
2406 		devres_remove_group(dev, NULL);
2407 	else
2408 		devres_release_group(dev, NULL);
2409 
2410 	return rc;
2411 }
2412 EXPORT_SYMBOL_GPL(ata_pci_sff_activate_host);
2413 
2414 static const struct ata_port_info *ata_sff_find_valid_pi(
2415 					const struct ata_port_info * const *ppi)
2416 {
2417 	int i;
2418 
2419 	/* look up the first valid port_info */
2420 	for (i = 0; i < 2 && ppi[i]; i++)
2421 		if (ppi[i]->port_ops != &ata_dummy_port_ops)
2422 			return ppi[i];
2423 
2424 	return NULL;
2425 }
2426 
2427 static int ata_pci_init_one(struct pci_dev *pdev,
2428 		const struct ata_port_info * const *ppi,
2429 		struct scsi_host_template *sht, void *host_priv,
2430 		int hflags, bool bmdma)
2431 {
2432 	struct device *dev = &pdev->dev;
2433 	const struct ata_port_info *pi;
2434 	struct ata_host *host = NULL;
2435 	int rc;
2436 
2437 	pi = ata_sff_find_valid_pi(ppi);
2438 	if (!pi) {
2439 		dev_err(&pdev->dev, "no valid port_info specified\n");
2440 		return -EINVAL;
2441 	}
2442 
2443 	if (!devres_open_group(dev, NULL, GFP_KERNEL))
2444 		return -ENOMEM;
2445 
2446 	rc = pcim_enable_device(pdev);
2447 	if (rc)
2448 		goto out;
2449 
2450 #ifdef CONFIG_ATA_BMDMA
2451 	if (bmdma)
2452 		/* prepare and activate BMDMA host */
2453 		rc = ata_pci_bmdma_prepare_host(pdev, ppi, &host);
2454 	else
2455 #endif
2456 		/* prepare and activate SFF host */
2457 		rc = ata_pci_sff_prepare_host(pdev, ppi, &host);
2458 	if (rc)
2459 		goto out;
2460 	host->private_data = host_priv;
2461 	host->flags |= hflags;
2462 
2463 #ifdef CONFIG_ATA_BMDMA
2464 	if (bmdma) {
2465 		pci_set_master(pdev);
2466 		rc = ata_pci_sff_activate_host(host, ata_bmdma_interrupt, sht);
2467 	} else
2468 #endif
2469 		rc = ata_pci_sff_activate_host(host, ata_sff_interrupt, sht);
2470 out:
2471 	if (rc == 0)
2472 		devres_remove_group(&pdev->dev, NULL);
2473 	else
2474 		devres_release_group(&pdev->dev, NULL);
2475 
2476 	return rc;
2477 }
2478 
2479 /**
2480  *	ata_pci_sff_init_one - Initialize/register PIO-only PCI IDE controller
2481  *	@pdev: Controller to be initialized
2482  *	@ppi: array of port_info, must be enough for two ports
2483  *	@sht: scsi_host_template to use when registering the host
2484  *	@host_priv: host private_data
2485  *	@hflag: host flags
2486  *
2487  *	This is a helper function which can be called from a driver's
2488  *	xxx_init_one() probe function if the hardware uses traditional
2489  *	IDE taskfile registers and is PIO only.
2490  *
2491  *	ASSUMPTION:
2492  *	Nobody makes a single channel controller that appears solely as
2493  *	the secondary legacy port on PCI.
2494  *
2495  *	LOCKING:
2496  *	Inherited from PCI layer (may sleep).
2497  *
2498  *	RETURNS:
2499  *	Zero on success, negative on errno-based value on error.
2500  */
2501 int ata_pci_sff_init_one(struct pci_dev *pdev,
2502 		 const struct ata_port_info * const *ppi,
2503 		 struct scsi_host_template *sht, void *host_priv, int hflag)
2504 {
2505 	return ata_pci_init_one(pdev, ppi, sht, host_priv, hflag, 0);
2506 }
2507 EXPORT_SYMBOL_GPL(ata_pci_sff_init_one);
2508 
2509 #endif /* CONFIG_PCI */
2510 
2511 /*
2512  *	BMDMA support
2513  */
2514 
2515 #ifdef CONFIG_ATA_BMDMA
2516 
2517 const struct ata_port_operations ata_bmdma_port_ops = {
2518 	.inherits		= &ata_sff_port_ops,
2519 
2520 	.error_handler		= ata_bmdma_error_handler,
2521 	.post_internal_cmd	= ata_bmdma_post_internal_cmd,
2522 
2523 	.qc_prep		= ata_bmdma_qc_prep,
2524 	.qc_issue		= ata_bmdma_qc_issue,
2525 
2526 	.sff_irq_clear		= ata_bmdma_irq_clear,
2527 	.bmdma_setup		= ata_bmdma_setup,
2528 	.bmdma_start		= ata_bmdma_start,
2529 	.bmdma_stop		= ata_bmdma_stop,
2530 	.bmdma_status		= ata_bmdma_status,
2531 
2532 	.port_start		= ata_bmdma_port_start,
2533 };
2534 EXPORT_SYMBOL_GPL(ata_bmdma_port_ops);
2535 
2536 const struct ata_port_operations ata_bmdma32_port_ops = {
2537 	.inherits		= &ata_bmdma_port_ops,
2538 
2539 	.sff_data_xfer		= ata_sff_data_xfer32,
2540 	.port_start		= ata_bmdma_port_start32,
2541 };
2542 EXPORT_SYMBOL_GPL(ata_bmdma32_port_ops);
2543 
2544 /**
2545  *	ata_bmdma_fill_sg - Fill PCI IDE PRD table
2546  *	@qc: Metadata associated with taskfile to be transferred
2547  *
2548  *	Fill PCI IDE PRD (scatter-gather) table with segments
2549  *	associated with the current disk command.
2550  *
2551  *	LOCKING:
2552  *	spin_lock_irqsave(host lock)
2553  *
2554  */
2555 static void ata_bmdma_fill_sg(struct ata_queued_cmd *qc)
2556 {
2557 	struct ata_port *ap = qc->ap;
2558 	struct ata_bmdma_prd *prd = ap->bmdma_prd;
2559 	struct scatterlist *sg;
2560 	unsigned int si, pi;
2561 
2562 	pi = 0;
2563 	for_each_sg(qc->sg, sg, qc->n_elem, si) {
2564 		u32 addr, offset;
2565 		u32 sg_len, len;
2566 
2567 		/* determine if physical DMA addr spans 64K boundary.
2568 		 * Note h/w doesn't support 64-bit, so we unconditionally
2569 		 * truncate dma_addr_t to u32.
2570 		 */
2571 		addr = (u32) sg_dma_address(sg);
2572 		sg_len = sg_dma_len(sg);
2573 
2574 		while (sg_len) {
2575 			offset = addr & 0xffff;
2576 			len = sg_len;
2577 			if ((offset + sg_len) > 0x10000)
2578 				len = 0x10000 - offset;
2579 
2580 			prd[pi].addr = cpu_to_le32(addr);
2581 			prd[pi].flags_len = cpu_to_le32(len & 0xffff);
2582 
2583 			pi++;
2584 			sg_len -= len;
2585 			addr += len;
2586 		}
2587 	}
2588 
2589 	prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
2590 }
2591 
2592 /**
2593  *	ata_bmdma_fill_sg_dumb - Fill PCI IDE PRD table
2594  *	@qc: Metadata associated with taskfile to be transferred
2595  *
2596  *	Fill PCI IDE PRD (scatter-gather) table with segments
2597  *	associated with the current disk command. Perform the fill
2598  *	so that we avoid writing any length 64K records for
2599  *	controllers that don't follow the spec.
2600  *
2601  *	LOCKING:
2602  *	spin_lock_irqsave(host lock)
2603  *
2604  */
2605 static void ata_bmdma_fill_sg_dumb(struct ata_queued_cmd *qc)
2606 {
2607 	struct ata_port *ap = qc->ap;
2608 	struct ata_bmdma_prd *prd = ap->bmdma_prd;
2609 	struct scatterlist *sg;
2610 	unsigned int si, pi;
2611 
2612 	pi = 0;
2613 	for_each_sg(qc->sg, sg, qc->n_elem, si) {
2614 		u32 addr, offset;
2615 		u32 sg_len, len, blen;
2616 
2617 		/* determine if physical DMA addr spans 64K boundary.
2618 		 * Note h/w doesn't support 64-bit, so we unconditionally
2619 		 * truncate dma_addr_t to u32.
2620 		 */
2621 		addr = (u32) sg_dma_address(sg);
2622 		sg_len = sg_dma_len(sg);
2623 
2624 		while (sg_len) {
2625 			offset = addr & 0xffff;
2626 			len = sg_len;
2627 			if ((offset + sg_len) > 0x10000)
2628 				len = 0x10000 - offset;
2629 
2630 			blen = len & 0xffff;
2631 			prd[pi].addr = cpu_to_le32(addr);
2632 			if (blen == 0) {
2633 				/* Some PATA chipsets like the CS5530 can't
2634 				   cope with 0x0000 meaning 64K as the spec
2635 				   says */
2636 				prd[pi].flags_len = cpu_to_le32(0x8000);
2637 				blen = 0x8000;
2638 				prd[++pi].addr = cpu_to_le32(addr + 0x8000);
2639 			}
2640 			prd[pi].flags_len = cpu_to_le32(blen);
2641 
2642 			pi++;
2643 			sg_len -= len;
2644 			addr += len;
2645 		}
2646 	}
2647 
2648 	prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
2649 }
2650 
2651 /**
2652  *	ata_bmdma_qc_prep - Prepare taskfile for submission
2653  *	@qc: Metadata associated with taskfile to be prepared
2654  *
2655  *	Prepare ATA taskfile for submission.
2656  *
2657  *	LOCKING:
2658  *	spin_lock_irqsave(host lock)
2659  */
2660 enum ata_completion_errors ata_bmdma_qc_prep(struct ata_queued_cmd *qc)
2661 {
2662 	if (!(qc->flags & ATA_QCFLAG_DMAMAP))
2663 		return AC_ERR_OK;
2664 
2665 	ata_bmdma_fill_sg(qc);
2666 
2667 	return AC_ERR_OK;
2668 }
2669 EXPORT_SYMBOL_GPL(ata_bmdma_qc_prep);
2670 
2671 /**
2672  *	ata_bmdma_dumb_qc_prep - Prepare taskfile for submission
2673  *	@qc: Metadata associated with taskfile to be prepared
2674  *
2675  *	Prepare ATA taskfile for submission.
2676  *
2677  *	LOCKING:
2678  *	spin_lock_irqsave(host lock)
2679  */
2680 enum ata_completion_errors ata_bmdma_dumb_qc_prep(struct ata_queued_cmd *qc)
2681 {
2682 	if (!(qc->flags & ATA_QCFLAG_DMAMAP))
2683 		return AC_ERR_OK;
2684 
2685 	ata_bmdma_fill_sg_dumb(qc);
2686 
2687 	return AC_ERR_OK;
2688 }
2689 EXPORT_SYMBOL_GPL(ata_bmdma_dumb_qc_prep);
2690 
2691 /**
2692  *	ata_bmdma_qc_issue - issue taskfile to a BMDMA controller
2693  *	@qc: command to issue to device
2694  *
2695  *	This function issues a PIO, NODATA or DMA command to a
2696  *	SFF/BMDMA controller.  PIO and NODATA are handled by
2697  *	ata_sff_qc_issue().
2698  *
2699  *	LOCKING:
2700  *	spin_lock_irqsave(host lock)
2701  *
2702  *	RETURNS:
2703  *	Zero on success, AC_ERR_* mask on failure
2704  */
2705 unsigned int ata_bmdma_qc_issue(struct ata_queued_cmd *qc)
2706 {
2707 	struct ata_port *ap = qc->ap;
2708 	struct ata_link *link = qc->dev->link;
2709 
2710 	/* defer PIO handling to sff_qc_issue */
2711 	if (!ata_is_dma(qc->tf.protocol))
2712 		return ata_sff_qc_issue(qc);
2713 
2714 	/* select the device */
2715 	ata_dev_select(ap, qc->dev->devno, 1, 0);
2716 
2717 	/* start the command */
2718 	switch (qc->tf.protocol) {
2719 	case ATA_PROT_DMA:
2720 		WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
2721 
2722 		trace_ata_tf_load(ap, &qc->tf);
2723 		ap->ops->sff_tf_load(ap, &qc->tf);  /* load tf registers */
2724 		trace_ata_bmdma_setup(ap, &qc->tf, qc->tag);
2725 		ap->ops->bmdma_setup(qc);	    /* set up bmdma */
2726 		trace_ata_bmdma_start(ap, &qc->tf, qc->tag);
2727 		ap->ops->bmdma_start(qc);	    /* initiate bmdma */
2728 		ap->hsm_task_state = HSM_ST_LAST;
2729 		break;
2730 
2731 	case ATAPI_PROT_DMA:
2732 		WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
2733 
2734 		trace_ata_tf_load(ap, &qc->tf);
2735 		ap->ops->sff_tf_load(ap, &qc->tf);  /* load tf registers */
2736 		trace_ata_bmdma_setup(ap, &qc->tf, qc->tag);
2737 		ap->ops->bmdma_setup(qc);	    /* set up bmdma */
2738 		ap->hsm_task_state = HSM_ST_FIRST;
2739 
2740 		/* send cdb by polling if no cdb interrupt */
2741 		if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
2742 			ata_sff_queue_pio_task(link, 0);
2743 		break;
2744 
2745 	default:
2746 		WARN_ON(1);
2747 		return AC_ERR_SYSTEM;
2748 	}
2749 
2750 	return 0;
2751 }
2752 EXPORT_SYMBOL_GPL(ata_bmdma_qc_issue);
2753 
2754 /**
2755  *	ata_bmdma_port_intr - Handle BMDMA port interrupt
2756  *	@ap: Port on which interrupt arrived (possibly...)
2757  *	@qc: Taskfile currently active in engine
2758  *
2759  *	Handle port interrupt for given queued command.
2760  *
2761  *	LOCKING:
2762  *	spin_lock_irqsave(host lock)
2763  *
2764  *	RETURNS:
2765  *	One if interrupt was handled, zero if not (shared irq).
2766  */
2767 unsigned int ata_bmdma_port_intr(struct ata_port *ap, struct ata_queued_cmd *qc)
2768 {
2769 	struct ata_eh_info *ehi = &ap->link.eh_info;
2770 	u8 host_stat = 0;
2771 	bool bmdma_stopped = false;
2772 	unsigned int handled;
2773 
2774 	if (ap->hsm_task_state == HSM_ST_LAST && ata_is_dma(qc->tf.protocol)) {
2775 		/* check status of DMA engine */
2776 		host_stat = ap->ops->bmdma_status(ap);
2777 		trace_ata_bmdma_status(ap, host_stat);
2778 
2779 		/* if it's not our irq... */
2780 		if (!(host_stat & ATA_DMA_INTR))
2781 			return ata_sff_idle_irq(ap);
2782 
2783 		/* before we do anything else, clear DMA-Start bit */
2784 		trace_ata_bmdma_stop(ap, &qc->tf, qc->tag);
2785 		ap->ops->bmdma_stop(qc);
2786 		bmdma_stopped = true;
2787 
2788 		if (unlikely(host_stat & ATA_DMA_ERR)) {
2789 			/* error when transferring data to/from memory */
2790 			qc->err_mask |= AC_ERR_HOST_BUS;
2791 			ap->hsm_task_state = HSM_ST_ERR;
2792 		}
2793 	}
2794 
2795 	handled = __ata_sff_port_intr(ap, qc, bmdma_stopped);
2796 
2797 	if (unlikely(qc->err_mask) && ata_is_dma(qc->tf.protocol))
2798 		ata_ehi_push_desc(ehi, "BMDMA stat 0x%x", host_stat);
2799 
2800 	return handled;
2801 }
2802 EXPORT_SYMBOL_GPL(ata_bmdma_port_intr);
2803 
2804 /**
2805  *	ata_bmdma_interrupt - Default BMDMA ATA host interrupt handler
2806  *	@irq: irq line (unused)
2807  *	@dev_instance: pointer to our ata_host information structure
2808  *
2809  *	Default interrupt handler for PCI IDE devices.  Calls
2810  *	ata_bmdma_port_intr() for each port that is not disabled.
2811  *
2812  *	LOCKING:
2813  *	Obtains host lock during operation.
2814  *
2815  *	RETURNS:
2816  *	IRQ_NONE or IRQ_HANDLED.
2817  */
2818 irqreturn_t ata_bmdma_interrupt(int irq, void *dev_instance)
2819 {
2820 	return __ata_sff_interrupt(irq, dev_instance, ata_bmdma_port_intr);
2821 }
2822 EXPORT_SYMBOL_GPL(ata_bmdma_interrupt);
2823 
2824 /**
2825  *	ata_bmdma_error_handler - Stock error handler for BMDMA controller
2826  *	@ap: port to handle error for
2827  *
2828  *	Stock error handler for BMDMA controller.  It can handle both
2829  *	PATA and SATA controllers.  Most BMDMA controllers should be
2830  *	able to use this EH as-is or with some added handling before
2831  *	and after.
2832  *
2833  *	LOCKING:
2834  *	Kernel thread context (may sleep)
2835  */
2836 void ata_bmdma_error_handler(struct ata_port *ap)
2837 {
2838 	struct ata_queued_cmd *qc;
2839 	unsigned long flags;
2840 	bool thaw = false;
2841 
2842 	qc = __ata_qc_from_tag(ap, ap->link.active_tag);
2843 	if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
2844 		qc = NULL;
2845 
2846 	/* reset PIO HSM and stop DMA engine */
2847 	spin_lock_irqsave(ap->lock, flags);
2848 
2849 	if (qc && ata_is_dma(qc->tf.protocol)) {
2850 		u8 host_stat;
2851 
2852 		host_stat = ap->ops->bmdma_status(ap);
2853 		trace_ata_bmdma_status(ap, host_stat);
2854 
2855 		/* BMDMA controllers indicate host bus error by
2856 		 * setting DMA_ERR bit and timing out.  As it wasn't
2857 		 * really a timeout event, adjust error mask and
2858 		 * cancel frozen state.
2859 		 */
2860 		if (qc->err_mask == AC_ERR_TIMEOUT && (host_stat & ATA_DMA_ERR)) {
2861 			qc->err_mask = AC_ERR_HOST_BUS;
2862 			thaw = true;
2863 		}
2864 
2865 		trace_ata_bmdma_stop(ap, &qc->tf, qc->tag);
2866 		ap->ops->bmdma_stop(qc);
2867 
2868 		/* if we're gonna thaw, make sure IRQ is clear */
2869 		if (thaw) {
2870 			ap->ops->sff_check_status(ap);
2871 			if (ap->ops->sff_irq_clear)
2872 				ap->ops->sff_irq_clear(ap);
2873 		}
2874 	}
2875 
2876 	spin_unlock_irqrestore(ap->lock, flags);
2877 
2878 	if (thaw)
2879 		ata_eh_thaw_port(ap);
2880 
2881 	ata_sff_error_handler(ap);
2882 }
2883 EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
2884 
2885 /**
2886  *	ata_bmdma_post_internal_cmd - Stock post_internal_cmd for BMDMA
2887  *	@qc: internal command to clean up
2888  *
2889  *	LOCKING:
2890  *	Kernel thread context (may sleep)
2891  */
2892 void ata_bmdma_post_internal_cmd(struct ata_queued_cmd *qc)
2893 {
2894 	struct ata_port *ap = qc->ap;
2895 	unsigned long flags;
2896 
2897 	if (ata_is_dma(qc->tf.protocol)) {
2898 		spin_lock_irqsave(ap->lock, flags);
2899 		trace_ata_bmdma_stop(ap, &qc->tf, qc->tag);
2900 		ap->ops->bmdma_stop(qc);
2901 		spin_unlock_irqrestore(ap->lock, flags);
2902 	}
2903 }
2904 EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
2905 
2906 /**
2907  *	ata_bmdma_irq_clear - Clear PCI IDE BMDMA interrupt.
2908  *	@ap: Port associated with this ATA transaction.
2909  *
2910  *	Clear interrupt and error flags in DMA status register.
2911  *
2912  *	May be used as the irq_clear() entry in ata_port_operations.
2913  *
2914  *	LOCKING:
2915  *	spin_lock_irqsave(host lock)
2916  */
2917 void ata_bmdma_irq_clear(struct ata_port *ap)
2918 {
2919 	void __iomem *mmio = ap->ioaddr.bmdma_addr;
2920 
2921 	if (!mmio)
2922 		return;
2923 
2924 	iowrite8(ioread8(mmio + ATA_DMA_STATUS), mmio + ATA_DMA_STATUS);
2925 }
2926 EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
2927 
2928 /**
2929  *	ata_bmdma_setup - Set up PCI IDE BMDMA transaction
2930  *	@qc: Info associated with this ATA transaction.
2931  *
2932  *	LOCKING:
2933  *	spin_lock_irqsave(host lock)
2934  */
2935 void ata_bmdma_setup(struct ata_queued_cmd *qc)
2936 {
2937 	struct ata_port *ap = qc->ap;
2938 	unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
2939 	u8 dmactl;
2940 
2941 	/* load PRD table addr. */
2942 	mb();	/* make sure PRD table writes are visible to controller */
2943 	iowrite32(ap->bmdma_prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
2944 
2945 	/* specify data direction, triple-check start bit is clear */
2946 	dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2947 	dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
2948 	if (!rw)
2949 		dmactl |= ATA_DMA_WR;
2950 	iowrite8(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2951 
2952 	/* issue r/w command */
2953 	ap->ops->sff_exec_command(ap, &qc->tf);
2954 }
2955 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
2956 
2957 /**
2958  *	ata_bmdma_start - Start a PCI IDE BMDMA transaction
2959  *	@qc: Info associated with this ATA transaction.
2960  *
2961  *	LOCKING:
2962  *	spin_lock_irqsave(host lock)
2963  */
2964 void ata_bmdma_start(struct ata_queued_cmd *qc)
2965 {
2966 	struct ata_port *ap = qc->ap;
2967 	u8 dmactl;
2968 
2969 	/* start host DMA transaction */
2970 	dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2971 	iowrite8(dmactl | ATA_DMA_START, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2972 
2973 	/* Strictly, one may wish to issue an ioread8() here, to
2974 	 * flush the mmio write.  However, control also passes
2975 	 * to the hardware at this point, and it will interrupt
2976 	 * us when we are to resume control.  So, in effect,
2977 	 * we don't care when the mmio write flushes.
2978 	 * Further, a read of the DMA status register _immediately_
2979 	 * following the write may not be what certain flaky hardware
2980 	 * is expected, so I think it is best to not add a readb()
2981 	 * without first all the MMIO ATA cards/mobos.
2982 	 * Or maybe I'm just being paranoid.
2983 	 *
2984 	 * FIXME: The posting of this write means I/O starts are
2985 	 * unnecessarily delayed for MMIO
2986 	 */
2987 }
2988 EXPORT_SYMBOL_GPL(ata_bmdma_start);
2989 
2990 /**
2991  *	ata_bmdma_stop - Stop PCI IDE BMDMA transfer
2992  *	@qc: Command we are ending DMA for
2993  *
2994  *	Clears the ATA_DMA_START flag in the dma control register
2995  *
2996  *	May be used as the bmdma_stop() entry in ata_port_operations.
2997  *
2998  *	LOCKING:
2999  *	spin_lock_irqsave(host lock)
3000  */
3001 void ata_bmdma_stop(struct ata_queued_cmd *qc)
3002 {
3003 	struct ata_port *ap = qc->ap;
3004 	void __iomem *mmio = ap->ioaddr.bmdma_addr;
3005 
3006 	/* clear start/stop bit */
3007 	iowrite8(ioread8(mmio + ATA_DMA_CMD) & ~ATA_DMA_START,
3008 		 mmio + ATA_DMA_CMD);
3009 
3010 	/* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
3011 	ata_sff_dma_pause(ap);
3012 }
3013 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
3014 
3015 /**
3016  *	ata_bmdma_status - Read PCI IDE BMDMA status
3017  *	@ap: Port associated with this ATA transaction.
3018  *
3019  *	Read and return BMDMA status register.
3020  *
3021  *	May be used as the bmdma_status() entry in ata_port_operations.
3022  *
3023  *	LOCKING:
3024  *	spin_lock_irqsave(host lock)
3025  */
3026 u8 ata_bmdma_status(struct ata_port *ap)
3027 {
3028 	return ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
3029 }
3030 EXPORT_SYMBOL_GPL(ata_bmdma_status);
3031 
3032 
3033 /**
3034  *	ata_bmdma_port_start - Set port up for bmdma.
3035  *	@ap: Port to initialize
3036  *
3037  *	Called just after data structures for each port are
3038  *	initialized.  Allocates space for PRD table.
3039  *
3040  *	May be used as the port_start() entry in ata_port_operations.
3041  *
3042  *	LOCKING:
3043  *	Inherited from caller.
3044  */
3045 int ata_bmdma_port_start(struct ata_port *ap)
3046 {
3047 	if (ap->mwdma_mask || ap->udma_mask) {
3048 		ap->bmdma_prd =
3049 			dmam_alloc_coherent(ap->host->dev, ATA_PRD_TBL_SZ,
3050 					    &ap->bmdma_prd_dma, GFP_KERNEL);
3051 		if (!ap->bmdma_prd)
3052 			return -ENOMEM;
3053 	}
3054 
3055 	return 0;
3056 }
3057 EXPORT_SYMBOL_GPL(ata_bmdma_port_start);
3058 
3059 /**
3060  *	ata_bmdma_port_start32 - Set port up for dma.
3061  *	@ap: Port to initialize
3062  *
3063  *	Called just after data structures for each port are
3064  *	initialized.  Enables 32bit PIO and allocates space for PRD
3065  *	table.
3066  *
3067  *	May be used as the port_start() entry in ata_port_operations for
3068  *	devices that are capable of 32bit PIO.
3069  *
3070  *	LOCKING:
3071  *	Inherited from caller.
3072  */
3073 int ata_bmdma_port_start32(struct ata_port *ap)
3074 {
3075 	ap->pflags |= ATA_PFLAG_PIO32 | ATA_PFLAG_PIO32CHANGE;
3076 	return ata_bmdma_port_start(ap);
3077 }
3078 EXPORT_SYMBOL_GPL(ata_bmdma_port_start32);
3079 
3080 #ifdef CONFIG_PCI
3081 
3082 /**
3083  *	ata_pci_bmdma_clear_simplex -	attempt to kick device out of simplex
3084  *	@pdev: PCI device
3085  *
3086  *	Some PCI ATA devices report simplex mode but in fact can be told to
3087  *	enter non simplex mode. This implements the necessary logic to
3088  *	perform the task on such devices. Calling it on other devices will
3089  *	have -undefined- behaviour.
3090  */
3091 int ata_pci_bmdma_clear_simplex(struct pci_dev *pdev)
3092 {
3093 	unsigned long bmdma = pci_resource_start(pdev, 4);
3094 	u8 simplex;
3095 
3096 	if (bmdma == 0)
3097 		return -ENOENT;
3098 
3099 	simplex = inb(bmdma + 0x02);
3100 	outb(simplex & 0x60, bmdma + 0x02);
3101 	simplex = inb(bmdma + 0x02);
3102 	if (simplex & 0x80)
3103 		return -EOPNOTSUPP;
3104 	return 0;
3105 }
3106 EXPORT_SYMBOL_GPL(ata_pci_bmdma_clear_simplex);
3107 
3108 static void ata_bmdma_nodma(struct ata_host *host, const char *reason)
3109 {
3110 	int i;
3111 
3112 	dev_err(host->dev, "BMDMA: %s, falling back to PIO\n", reason);
3113 
3114 	for (i = 0; i < 2; i++) {
3115 		host->ports[i]->mwdma_mask = 0;
3116 		host->ports[i]->udma_mask = 0;
3117 	}
3118 }
3119 
3120 /**
3121  *	ata_pci_bmdma_init - acquire PCI BMDMA resources and init ATA host
3122  *	@host: target ATA host
3123  *
3124  *	Acquire PCI BMDMA resources and initialize @host accordingly.
3125  *
3126  *	LOCKING:
3127  *	Inherited from calling layer (may sleep).
3128  */
3129 void ata_pci_bmdma_init(struct ata_host *host)
3130 {
3131 	struct device *gdev = host->dev;
3132 	struct pci_dev *pdev = to_pci_dev(gdev);
3133 	int i, rc;
3134 
3135 	/* No BAR4 allocation: No DMA */
3136 	if (pci_resource_start(pdev, 4) == 0) {
3137 		ata_bmdma_nodma(host, "BAR4 is zero");
3138 		return;
3139 	}
3140 
3141 	/*
3142 	 * Some controllers require BMDMA region to be initialized
3143 	 * even if DMA is not in use to clear IRQ status via
3144 	 * ->sff_irq_clear method.  Try to initialize bmdma_addr
3145 	 * regardless of dma masks.
3146 	 */
3147 	rc = dma_set_mask_and_coherent(&pdev->dev, ATA_DMA_MASK);
3148 	if (rc)
3149 		ata_bmdma_nodma(host, "failed to set dma mask");
3150 
3151 	/* request and iomap DMA region */
3152 	rc = pcim_iomap_regions(pdev, 1 << 4, dev_driver_string(gdev));
3153 	if (rc) {
3154 		ata_bmdma_nodma(host, "failed to request/iomap BAR4");
3155 		return;
3156 	}
3157 	host->iomap = pcim_iomap_table(pdev);
3158 
3159 	for (i = 0; i < 2; i++) {
3160 		struct ata_port *ap = host->ports[i];
3161 		void __iomem *bmdma = host->iomap[4] + 8 * i;
3162 
3163 		if (ata_port_is_dummy(ap))
3164 			continue;
3165 
3166 		ap->ioaddr.bmdma_addr = bmdma;
3167 		if ((!(ap->flags & ATA_FLAG_IGN_SIMPLEX)) &&
3168 		    (ioread8(bmdma + 2) & 0x80))
3169 			host->flags |= ATA_HOST_SIMPLEX;
3170 
3171 		ata_port_desc(ap, "bmdma 0x%llx",
3172 		    (unsigned long long)pci_resource_start(pdev, 4) + 8 * i);
3173 	}
3174 }
3175 EXPORT_SYMBOL_GPL(ata_pci_bmdma_init);
3176 
3177 /**
3178  *	ata_pci_bmdma_prepare_host - helper to prepare PCI BMDMA ATA host
3179  *	@pdev: target PCI device
3180  *	@ppi: array of port_info, must be enough for two ports
3181  *	@r_host: out argument for the initialized ATA host
3182  *
3183  *	Helper to allocate BMDMA ATA host for @pdev, acquire all PCI
3184  *	resources and initialize it accordingly in one go.
3185  *
3186  *	LOCKING:
3187  *	Inherited from calling layer (may sleep).
3188  *
3189  *	RETURNS:
3190  *	0 on success, -errno otherwise.
3191  */
3192 int ata_pci_bmdma_prepare_host(struct pci_dev *pdev,
3193 			       const struct ata_port_info * const * ppi,
3194 			       struct ata_host **r_host)
3195 {
3196 	int rc;
3197 
3198 	rc = ata_pci_sff_prepare_host(pdev, ppi, r_host);
3199 	if (rc)
3200 		return rc;
3201 
3202 	ata_pci_bmdma_init(*r_host);
3203 	return 0;
3204 }
3205 EXPORT_SYMBOL_GPL(ata_pci_bmdma_prepare_host);
3206 
3207 /**
3208  *	ata_pci_bmdma_init_one - Initialize/register BMDMA PCI IDE controller
3209  *	@pdev: Controller to be initialized
3210  *	@ppi: array of port_info, must be enough for two ports
3211  *	@sht: scsi_host_template to use when registering the host
3212  *	@host_priv: host private_data
3213  *	@hflags: host flags
3214  *
3215  *	This function is similar to ata_pci_sff_init_one() but also
3216  *	takes care of BMDMA initialization.
3217  *
3218  *	LOCKING:
3219  *	Inherited from PCI layer (may sleep).
3220  *
3221  *	RETURNS:
3222  *	Zero on success, negative on errno-based value on error.
3223  */
3224 int ata_pci_bmdma_init_one(struct pci_dev *pdev,
3225 			   const struct ata_port_info * const * ppi,
3226 			   struct scsi_host_template *sht, void *host_priv,
3227 			   int hflags)
3228 {
3229 	return ata_pci_init_one(pdev, ppi, sht, host_priv, hflags, 1);
3230 }
3231 EXPORT_SYMBOL_GPL(ata_pci_bmdma_init_one);
3232 
3233 #endif /* CONFIG_PCI */
3234 #endif /* CONFIG_ATA_BMDMA */
3235 
3236 /**
3237  *	ata_sff_port_init - Initialize SFF/BMDMA ATA port
3238  *	@ap: Port to initialize
3239  *
3240  *	Called on port allocation to initialize SFF/BMDMA specific
3241  *	fields.
3242  *
3243  *	LOCKING:
3244  *	None.
3245  */
3246 void ata_sff_port_init(struct ata_port *ap)
3247 {
3248 	INIT_DELAYED_WORK(&ap->sff_pio_task, ata_sff_pio_task);
3249 	ap->ctl = ATA_DEVCTL_OBS;
3250 	ap->last_ctl = 0xFF;
3251 }
3252 
3253 int __init ata_sff_init(void)
3254 {
3255 	ata_sff_wq = alloc_workqueue("ata_sff", WQ_MEM_RECLAIM, WQ_MAX_ACTIVE);
3256 	if (!ata_sff_wq)
3257 		return -ENOMEM;
3258 
3259 	return 0;
3260 }
3261 
3262 void ata_sff_exit(void)
3263 {
3264 	destroy_workqueue(ata_sff_wq);
3265 }
3266