Linux Audio

Check our new training course

Loading...
v6.13.7
  1========================
  2libATA Developer's Guide
  3========================
  4
  5:Author: Jeff Garzik
  6
  7Introduction
  8============
  9
 10libATA is a library used inside the Linux kernel to support ATA host
 11controllers and devices. libATA provides an ATA driver API, class
 12transports for ATA and ATAPI devices, and SCSI<->ATA translation for ATA
 13devices according to the T10 SAT specification.
 14
 15This Guide documents the libATA driver API, library functions, library
 16internals, and a couple sample ATA low-level drivers.
 17
 18libata Driver API
 19=================
 20
 21:c:type:`struct ata_port_operations <ata_port_operations>`
 22is defined for every low-level libata
 23hardware driver, and it controls how the low-level driver interfaces
 24with the ATA and SCSI layers.
 25
 26FIS-based drivers will hook into the system with ``->qc_prep()`` and
 27``->qc_issue()`` high-level hooks. Hardware which behaves in a manner
 28similar to PCI IDE hardware may utilize several generic helpers,
 29defining at a bare minimum the bus I/O addresses of the ATA shadow
 30register blocks.
 31
 32:c:type:`struct ata_port_operations <ata_port_operations>`
 33----------------------------------------------------------
 34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 35Post-IDENTIFY device configuration
 36~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 37
 38::
 39
 40    void (*dev_config) (struct ata_port *, struct ata_device *);
 41
 42
 43Called after IDENTIFY [PACKET] DEVICE is issued to each device found.
 44Typically used to apply device-specific fixups prior to issue of SET
 45FEATURES - XFER MODE, and prior to operation.
 46
 47This entry may be specified as NULL in ata_port_operations.
 48
 49Set PIO/DMA mode
 50~~~~~~~~~~~~~~~~
 51
 52::
 53
 54    void (*set_piomode) (struct ata_port *, struct ata_device *);
 55    void (*set_dmamode) (struct ata_port *, struct ata_device *);
 56    void (*post_set_mode) (struct ata_port *);
 57    unsigned int (*mode_filter) (struct ata_port *, struct ata_device *, unsigned int);
 58
 59
 60Hooks called prior to the issue of SET FEATURES - XFER MODE command. The
 61optional ``->mode_filter()`` hook is called when libata has built a mask of
 62the possible modes. This is passed to the ``->mode_filter()`` function
 63which should return a mask of valid modes after filtering those
 64unsuitable due to hardware limits. It is not valid to use this interface
 65to add modes.
 66
 67``dev->pio_mode`` and ``dev->dma_mode`` are guaranteed to be valid when
 68``->set_piomode()`` and when ``->set_dmamode()`` is called. The timings for
 69any other drive sharing the cable will also be valid at this point. That
 70is the library records the decisions for the modes of each drive on a
 71channel before it attempts to set any of them.
 72
 73``->post_set_mode()`` is called unconditionally, after the SET FEATURES -
 74XFER MODE command completes successfully.
 75
 76``->set_piomode()`` is always called (if present), but ``->set_dma_mode()``
 77is only called if DMA is possible.
 78
 79Taskfile read/write
 80~~~~~~~~~~~~~~~~~~~
 81
 82::
 83
 84    void (*sff_tf_load) (struct ata_port *ap, struct ata_taskfile *tf);
 85    void (*sff_tf_read) (struct ata_port *ap, struct ata_taskfile *tf);
 86
 87
 88``->tf_load()`` is called to load the given taskfile into hardware
 89registers / DMA buffers. ``->tf_read()`` is called to read the hardware
 90registers / DMA buffers, to obtain the current set of taskfile register
 91values. Most drivers for taskfile-based hardware (PIO or MMIO) use
 92:c:func:`ata_sff_tf_load` and :c:func:`ata_sff_tf_read` for these hooks.
 93
 94PIO data read/write
 95~~~~~~~~~~~~~~~~~~~
 96
 97::
 98
 99    void (*sff_data_xfer) (struct ata_device *, unsigned char *, unsigned int, int);
100
101
102All bmdma-style drivers must implement this hook. This is the low-level
103operation that actually copies the data bytes during a PIO data
104transfer. Typically the driver will choose one of
105:c:func:`ata_sff_data_xfer`, or :c:func:`ata_sff_data_xfer32`.
106
107ATA command execute
108~~~~~~~~~~~~~~~~~~~
109
110::
111
112    void (*sff_exec_command)(struct ata_port *ap, struct ata_taskfile *tf);
113
114
115causes an ATA command, previously loaded with ``->tf_load()``, to be
116initiated in hardware. Most drivers for taskfile-based hardware use
117:c:func:`ata_sff_exec_command` for this hook.
118
119Per-cmd ATAPI DMA capabilities filter
120~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
121
122::
123
124    int (*check_atapi_dma) (struct ata_queued_cmd *qc);
125
126
127Allow low-level driver to filter ATA PACKET commands, returning a status
128indicating whether or not it is OK to use DMA for the supplied PACKET
129command.
130
131This hook may be specified as NULL, in which case libata will assume
132that atapi dma can be supported.
133
134Read specific ATA shadow registers
135~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136
137::
138
139    u8   (*sff_check_status)(struct ata_port *ap);
140    u8   (*sff_check_altstatus)(struct ata_port *ap);
141
142
143Reads the Status/AltStatus ATA shadow register from hardware. On some
144hardware, reading the Status register has the side effect of clearing
145the interrupt condition. Most drivers for taskfile-based hardware use
146:c:func:`ata_sff_check_status` for this hook.
147
148Write specific ATA shadow register
149~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150
151::
152
153    void (*sff_set_devctl)(struct ata_port *ap, u8 ctl);
154
155
156Write the device control ATA shadow register to the hardware. Most
157drivers don't need to define this.
158
159Select ATA device on bus
160~~~~~~~~~~~~~~~~~~~~~~~~
161
162::
163
164    void (*sff_dev_select)(struct ata_port *ap, unsigned int device);
165
166
167Issues the low-level hardware command(s) that causes one of N hardware
168devices to be considered 'selected' (active and available for use) on
169the ATA bus. This generally has no meaning on FIS-based devices.
170
171Most drivers for taskfile-based hardware use :c:func:`ata_sff_dev_select` for
172this hook.
173
174Private tuning method
175~~~~~~~~~~~~~~~~~~~~~
176
177::
178
179    void (*set_mode) (struct ata_port *ap);
180
181
182By default libata performs drive and controller tuning in accordance
183with the ATA timing rules and also applies blacklists and cable limits.
184Some controllers need special handling and have custom tuning rules,
185typically raid controllers that use ATA commands but do not actually do
186drive timing.
187
188    **Warning**
189
190    This hook should not be used to replace the standard controller
191    tuning logic when a controller has quirks. Replacing the default
192    tuning logic in that case would bypass handling for drive and bridge
193    quirks that may be important to data reliability. If a controller
194    needs to filter the mode selection it should use the mode_filter
195    hook instead.
196
197Control PCI IDE BMDMA engine
198~~~~~~~~~~~~~~~~~~~~~~~~~~~~
199
200::
201
202    void (*bmdma_setup) (struct ata_queued_cmd *qc);
203    void (*bmdma_start) (struct ata_queued_cmd *qc);
204    void (*bmdma_stop) (struct ata_port *ap);
205    u8   (*bmdma_status) (struct ata_port *ap);
206
207
208When setting up an IDE BMDMA transaction, these hooks arm
209(``->bmdma_setup``), fire (``->bmdma_start``), and halt (``->bmdma_stop``) the
210hardware's DMA engine. ``->bmdma_status`` is used to read the standard PCI
211IDE DMA Status register.
212
213These hooks are typically either no-ops, or simply not implemented, in
214FIS-based drivers.
215
216Most legacy IDE drivers use :c:func:`ata_bmdma_setup` for the
217:c:func:`bmdma_setup` hook. :c:func:`ata_bmdma_setup` will write the pointer
218to the PRD table to the IDE PRD Table Address register, enable DMA in the DMA
219Command register, and call :c:func:`exec_command` to begin the transfer.
220
221Most legacy IDE drivers use :c:func:`ata_bmdma_start` for the
222:c:func:`bmdma_start` hook. :c:func:`ata_bmdma_start` will write the
223ATA_DMA_START flag to the DMA Command register.
224
225Many legacy IDE drivers use :c:func:`ata_bmdma_stop` for the
226:c:func:`bmdma_stop` hook. :c:func:`ata_bmdma_stop` clears the ATA_DMA_START
227flag in the DMA command register.
228
229Many legacy IDE drivers use :c:func:`ata_bmdma_status` as the
230:c:func:`bmdma_status` hook.
231
232High-level taskfile hooks
233~~~~~~~~~~~~~~~~~~~~~~~~~
234
235::
236
237    enum ata_completion_errors (*qc_prep) (struct ata_queued_cmd *qc);
238    int (*qc_issue) (struct ata_queued_cmd *qc);
239
240
241Higher-level hooks, these two hooks can potentially supersede several of
242the above taskfile/DMA engine hooks. ``->qc_prep`` is called after the
243buffers have been DMA-mapped, and is typically used to populate the
244hardware's DMA scatter-gather table. Some drivers use the standard
245:c:func:`ata_bmdma_qc_prep` and :c:func:`ata_bmdma_dumb_qc_prep` helper
246functions, but more advanced drivers roll their own.
247
248``->qc_issue`` is used to make a command active, once the hardware and S/G
249tables have been prepared. IDE BMDMA drivers use the helper function
250:c:func:`ata_sff_qc_issue` for taskfile protocol-based dispatch. More
251advanced drivers implement their own ``->qc_issue``.
252
253:c:func:`ata_sff_qc_issue` calls ``->sff_tf_load()``, ``->bmdma_setup()``, and
254``->bmdma_start()`` as necessary to initiate a transfer.
255
256Exception and probe handling (EH)
257~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
258
259::
260
 
 
 
 
 
 
 
 
261    void (*freeze) (struct ata_port *ap);
262    void (*thaw) (struct ata_port *ap);
263
264
265:c:func:`ata_port_freeze` is called when HSM violations or some other
266condition disrupts normal operation of the port. A frozen port is not
267allowed to perform any operation until the port is thawed, which usually
268follows a successful reset.
269
270The optional ``->freeze()`` callback can be used for freezing the port
271hardware-wise (e.g. mask interrupt and stop DMA engine). If a port
272cannot be frozen hardware-wise, the interrupt handler must ack and clear
273interrupts unconditionally while the port is frozen.
274
275The optional ``->thaw()`` callback is called to perform the opposite of
276``->freeze()``: prepare the port for normal operation once again. Unmask
277interrupts, start DMA engine, etc.
278
279::
280
281    void (*error_handler) (struct ata_port *ap);
282
283
284``->error_handler()`` is a driver's hook into probe, hotplug, and recovery
285and other exceptional conditions. The primary responsibility of an
286implementation is to call :c:func:`ata_do_eh` or :c:func:`ata_bmdma_drive_eh`
287with a set of EH hooks as arguments:
288
289'prereset' hook (may be NULL) is called during an EH reset, before any
290other actions are taken.
291
292'postreset' hook (may be NULL) is called after the EH reset is
293performed. Based on existing conditions, severity of the problem, and
294hardware capabilities,
295
296Either 'softreset' (may be NULL) or 'hardreset' (may be NULL) will be
297called to perform the low-level EH reset.
298
299::
300
301    void (*post_internal_cmd) (struct ata_queued_cmd *qc);
302
303
304Perform any hardware-specific actions necessary to finish processing
305after executing a probe-time or EH-time command via
306:c:func:`ata_exec_internal`.
307
308Hardware interrupt handling
309~~~~~~~~~~~~~~~~~~~~~~~~~~~
310
311::
312
313    irqreturn_t (*irq_handler)(int, void *, struct pt_regs *);
314    void (*irq_clear) (struct ata_port *);
315
316
317``->irq_handler`` is the interrupt handling routine registered with the
318system, by libata. ``->irq_clear`` is called during probe just before the
319interrupt handler is registered, to be sure hardware is quiet.
320
321The second argument, dev_instance, should be cast to a pointer to
322:c:type:`struct ata_host_set <ata_host_set>`.
323
324Most legacy IDE drivers use :c:func:`ata_sff_interrupt` for the irq_handler
325hook, which scans all ports in the host_set, determines which queued
326command was active (if any), and calls ata_sff_host_intr(ap,qc).
327
328Most legacy IDE drivers use :c:func:`ata_sff_irq_clear` for the
329:c:func:`irq_clear` hook, which simply clears the interrupt and error flags
330in the DMA status register.
331
332SATA phy read/write
333~~~~~~~~~~~~~~~~~~~
334
335::
336
337    int (*scr_read) (struct ata_port *ap, unsigned int sc_reg,
338             u32 *val);
339    int (*scr_write) (struct ata_port *ap, unsigned int sc_reg,
340                       u32 val);
341
342
343Read and write standard SATA phy registers.
 
344sc_reg is one of SCR_STATUS, SCR_CONTROL, SCR_ERROR, or SCR_ACTIVE.
345
346Init and shutdown
347~~~~~~~~~~~~~~~~~
348
349::
350
351    int (*port_start) (struct ata_port *ap);
352    void (*port_stop) (struct ata_port *ap);
353    void (*host_stop) (struct ata_host_set *host_set);
354
355
356``->port_start()`` is called just after the data structures for each port
357are initialized. Typically this is used to alloc per-port DMA buffers /
358tables / rings, enable DMA engines, and similar tasks. Some drivers also
359use this entry point as a chance to allocate driver-private memory for
360``ap->private_data``.
361
362Many drivers use :c:func:`ata_port_start` as this hook or call it from their
363own :c:func:`port_start` hooks. :c:func:`ata_port_start` allocates space for
364a legacy IDE PRD table and returns.
365
366``->port_stop()`` is called after ``->host_stop()``. Its sole function is to
367release DMA/memory resources, now that they are no longer actively being
368used. Many drivers also free driver-private data from port at this time.
369
370``->host_stop()`` is called after all ``->port_stop()`` calls have completed.
371The hook must finalize hardware shutdown, release DMA and other
372resources, etc. This hook may be specified as NULL, in which case it is
373not called.
374
375Error handling
376==============
377
378This chapter describes how errors are handled under libata. Readers are
379advised to read SCSI EH (Documentation/scsi/scsi_eh.rst) and ATA
380exceptions doc first.
381
382Origins of commands
383-------------------
384
385In libata, a command is represented with
386:c:type:`struct ata_queued_cmd <ata_queued_cmd>` or qc.
387qc's are preallocated during port initialization and repetitively used
388for command executions. Currently only one qc is allocated per port but
389yet-to-be-merged NCQ branch allocates one for each tag and maps each qc
390to NCQ tag 1-to-1.
391
392libata commands can originate from two sources - libata itself and SCSI
393midlayer. libata internal commands are used for initialization and error
394handling. All normal blk requests and commands for SCSI emulation are
395passed as SCSI commands through queuecommand callback of SCSI host
396template.
397
398How commands are issued
399-----------------------
400
401Internal commands
 
 
 
 
 
 
402    Once allocated qc's taskfile is initialized for the command to be
403    executed. qc currently has two mechanisms to notify completion. One
404    is via ``qc->complete_fn()`` callback and the other is completion
405    ``qc->waiting``. ``qc->complete_fn()`` callback is the asynchronous path
406    used by normal SCSI translated commands and ``qc->waiting`` is the
407    synchronous (issuer sleeps in process context) path used by internal
408    commands.
409
410    Once initialization is complete, host_set lock is acquired and the
411    qc is issued.
412
413SCSI commands
414    All libata drivers use :c:func:`ata_scsi_queuecmd` as
415    ``hostt->queuecommand`` callback. scmds can either be simulated or
416    translated. No qc is involved in processing a simulated scmd. The
417    result is computed right away and the scmd is completed.
418
 
 
 
 
 
419    ``qc->complete_fn()`` callback is used for completion notification. ATA
420    commands use :c:func:`ata_scsi_qc_complete` while ATAPI commands use
421    :c:func:`atapi_qc_complete`. Both functions end up calling ``qc->scsidone``
422    to notify upper layer when the qc is finished. After translation is
423    completed, the qc is issued with :c:func:`ata_qc_issue`.
424
425    Note that SCSI midlayer invokes hostt->queuecommand while holding
426    host_set lock, so all above occur while holding host_set lock.
427
428How commands are processed
429--------------------------
430
431Depending on which protocol and which controller are used, commands are
432processed differently. For the purpose of discussion, a controller which
433uses taskfile interface and all standard callbacks is assumed.
434
435Currently 6 ATA command protocols are used. They can be sorted into the
436following four categories according to how they are processed.
437
438ATA NO DATA or DMA
439    ATA_PROT_NODATA and ATA_PROT_DMA fall into this category. These
440    types of commands don't require any software intervention once
441    issued. Device will raise interrupt on completion.
442
443ATA PIO
444    ATA_PROT_PIO is in this category. libata currently implements PIO
445    with polling. ATA_NIEN bit is set to turn off interrupt and
446    pio_task on ata_wq performs polling and IO.
447
448ATAPI NODATA or DMA
449    ATA_PROT_ATAPI_NODATA and ATA_PROT_ATAPI_DMA are in this
450    category. packet_task is used to poll BSY bit after issuing PACKET
451    command. Once BSY is turned off by the device, packet_task
452    transfers CDB and hands off processing to interrupt handler.
453
454ATAPI PIO
455    ATA_PROT_ATAPI is in this category. ATA_NIEN bit is set and, as
456    in ATAPI NODATA or DMA, packet_task submits cdb. However, after
457    submitting cdb, further processing (data transfer) is handed off to
458    pio_task.
459
460How commands are completed
461--------------------------
462
463Once issued, all qc's are either completed with :c:func:`ata_qc_complete` or
464time out. For commands which are handled by interrupts,
465:c:func:`ata_host_intr` invokes :c:func:`ata_qc_complete`, and, for PIO tasks,
466pio_task invokes :c:func:`ata_qc_complete`. In error cases, packet_task may
467also complete commands.
468
469:c:func:`ata_qc_complete` does the following.
470
4711. DMA memory is unmapped.
472
4732. ATA_QCFLAG_ACTIVE is cleared from qc->flags.
474
4753. :c:expr:`qc->complete_fn` callback is invoked. If the return value of the
476   callback is not zero. Completion is short circuited and
477   :c:func:`ata_qc_complete` returns.
478
4794. :c:func:`__ata_qc_complete` is called, which does
480
481   1. ``qc->flags`` is cleared to zero.
482
483   2. ``ap->active_tag`` and ``qc->tag`` are poisoned.
484
485   3. ``qc->waiting`` is cleared & completed (in that order).
486
487   4. qc is deallocated by clearing appropriate bit in ``ap->qactive``.
488
489So, it basically notifies upper layer and deallocates qc. One exception
490is short-circuit path in #3 which is used by :c:func:`atapi_qc_complete`.
491
492For all non-ATAPI commands, whether it fails or not, almost the same
493code path is taken and very little error handling takes place. A qc is
494completed with success status if it succeeded, with failed status
495otherwise.
496
497However, failed ATAPI commands require more handling as REQUEST SENSE is
498needed to acquire sense data. If an ATAPI command fails,
499:c:func:`ata_qc_complete` is invoked with error status, which in turn invokes
500:c:func:`atapi_qc_complete` via ``qc->complete_fn()`` callback.
501
502This makes :c:func:`atapi_qc_complete` set ``scmd->result`` to
503SAM_STAT_CHECK_CONDITION, complete the scmd and return 1. As the
504sense data is empty but ``scmd->result`` is CHECK CONDITION, SCSI midlayer
505will invoke EH for the scmd, and returning 1 makes :c:func:`ata_qc_complete`
506to return without deallocating the qc. This leads us to
507:c:func:`ata_scsi_error` with partially completed qc.
508
509:c:func:`ata_scsi_error`
510------------------------
511
512:c:func:`ata_scsi_error` is the current ``transportt->eh_strategy_handler()``
513for libata. As discussed above, this will be entered in two cases -
514timeout and ATAPI error completion. This function will check if a qc is active
515and has not failed yet. Such a qc will be marked with AC_ERR_TIMEOUT such that
516EH will know to handle it later. Then it calls low level libata driver's
517:c:func:`error_handler` callback.
 
518
519When the :c:func:`error_handler` callback is invoked it stops BMDMA and
520completes the qc. Note that as we're currently in EH, we cannot call
521scsi_done. As described in SCSI EH doc, a recovered scmd should be
522either retried with :c:func:`scsi_queue_insert` or finished with
523:c:func:`scsi_finish_command`. Here, we override ``qc->scsidone`` with
524:c:func:`scsi_finish_command` and calls :c:func:`ata_qc_complete`.
525
526If EH is invoked due to a failed ATAPI qc, the qc here is completed but
527not deallocated. The purpose of this half-completion is to use the qc as
528place holder to make EH code reach this place. This is a bit hackish,
529but it works.
530
531Once control reaches here, the qc is deallocated by invoking
532:c:func:`__ata_qc_complete` explicitly. Then, internal qc for REQUEST SENSE
533is issued. Once sense data is acquired, scmd is finished by directly
534invoking :c:func:`scsi_finish_command` on the scmd. Note that as we already
535have completed and deallocated the qc which was associated with the
536scmd, we don't need to/cannot call :c:func:`ata_qc_complete` again.
537
538Problems with the current EH
539----------------------------
540
541-  Error representation is too crude. Currently any and all error
542   conditions are represented with ATA STATUS and ERROR registers.
543   Errors which aren't ATA device errors are treated as ATA device
544   errors by setting ATA_ERR bit. Better error descriptor which can
545   properly represent ATA and other errors/exceptions is needed.
546
547-  When handling timeouts, no action is taken to make device forget
548   about the timed out command and ready for new commands.
549
550-  EH handling via :c:func:`ata_scsi_error` is not properly protected from
551   usual command processing. On EH entrance, the device is not in
552   quiescent state. Timed out commands may succeed or fail any time.
553   pio_task and atapi_task may still be running.
554
555-  Too weak error recovery. Devices / controllers causing HSM mismatch
556   errors and other errors quite often require reset to return to known
557   state. Also, advanced error handling is necessary to support features
558   like NCQ and hotplug.
559
560-  ATA errors are directly handled in the interrupt handler and PIO
561   errors in pio_task. This is problematic for advanced error handling
562   for the following reasons.
563
564   First, advanced error handling often requires context and internal qc
565   execution.
566
567   Second, even a simple failure (say, CRC error) needs information
568   gathering and could trigger complex error handling (say, resetting &
569   reconfiguring). Having multiple code paths to gather information,
570   enter EH and trigger actions makes life painful.
571
572   Third, scattered EH code makes implementing low level drivers
573   difficult. Low level drivers override libata callbacks. If EH is
574   scattered over several places, each affected callbacks should perform
575   its part of error handling. This can be error prone and painful.
576
577libata Library
578==============
579
580.. kernel-doc:: drivers/ata/libata-core.c
581   :export:
582
583libata Core Internals
584=====================
585
586.. kernel-doc:: drivers/ata/libata-core.c
587   :internal:
588
589.. kernel-doc:: drivers/ata/libata-eh.c
590
591libata SCSI translation/emulation
592=================================
593
594.. kernel-doc:: drivers/ata/libata-scsi.c
595   :export:
596
597.. kernel-doc:: drivers/ata/libata-scsi.c
598   :internal:
599
600ATA errors and exceptions
601=========================
602
603This chapter tries to identify what error/exception conditions exist for
604ATA/ATAPI devices and describe how they should be handled in
605implementation-neutral way.
606
607The term 'error' is used to describe conditions where either an explicit
608error condition is reported from device or a command has timed out.
609
610The term 'exception' is either used to describe exceptional conditions
611which are not errors (say, power or hotplug events), or to describe both
612errors and non-error exceptional conditions. Where explicit distinction
613between error and exception is necessary, the term 'non-error exception'
614is used.
615
616Exception categories
617--------------------
618
619Exceptions are described primarily with respect to legacy taskfile + bus
620master IDE interface. If a controller provides other better mechanism
621for error reporting, mapping those into categories described below
622shouldn't be difficult.
623
624In the following sections, two recovery actions - reset and
625reconfiguring transport - are mentioned. These are described further in
626`EH recovery actions <#exrec>`__.
627
628HSM violation
629~~~~~~~~~~~~~
630
631This error is indicated when STATUS value doesn't match HSM requirement
632during issuing or execution any ATA/ATAPI command.
633
634-  ATA_STATUS doesn't contain !BSY && DRDY && !DRQ while trying to
635   issue a command.
636
637-  !BSY && !DRQ during PIO data transfer.
638
639-  DRQ on command completion.
640
641-  !BSY && ERR after CDB transfer starts but before the last byte of CDB
642   is transferred. ATA/ATAPI standard states that "The device shall not
643   terminate the PACKET command with an error before the last byte of
644   the command packet has been written" in the error outputs description
645   of PACKET command and the state diagram doesn't include such
646   transitions.
647
648In these cases, HSM is violated and not much information regarding the
649error can be acquired from STATUS or ERROR register. IOW, this error can
650be anything - driver bug, faulty device, controller and/or cable.
651
652As HSM is violated, reset is necessary to restore known state.
653Reconfiguring transport for lower speed might be helpful too as
654transmission errors sometimes cause this kind of errors.
655
656ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)
657~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
658
659These are errors detected and reported by ATA/ATAPI devices indicating
660device problems. For this type of errors, STATUS and ERROR register
661values are valid and describe error condition. Note that some of ATA bus
662errors are detected by ATA/ATAPI devices and reported using the same
663mechanism as device errors. Those cases are described later in this
664section.
665
666For ATA commands, this type of errors are indicated by !BSY && ERR
667during command execution and on completion.
668
669For ATAPI commands,
670
671-  !BSY && ERR && ABRT right after issuing PACKET indicates that PACKET
672   command is not supported and falls in this category.
673
674-  !BSY && ERR(==CHK) && !ABRT after the last byte of CDB is transferred
675   indicates CHECK CONDITION and doesn't fall in this category.
676
677-  !BSY && ERR(==CHK) && ABRT after the last byte of CDB is transferred
678   \*probably\* indicates CHECK CONDITION and doesn't fall in this
679   category.
680
681Of errors detected as above, the following are not ATA/ATAPI device
682errors but ATA bus errors and should be handled according to
683`ATA bus error <#excatATAbusErr>`__.
684
685CRC error during data transfer
686    This is indicated by ICRC bit in the ERROR register and means that
687    corruption occurred during data transfer. Up to ATA/ATAPI-7, the
688    standard specifies that this bit is only applicable to UDMA
689    transfers but ATA/ATAPI-8 draft revision 1f says that the bit may be
690    applicable to multiword DMA and PIO.
691
692ABRT error during data transfer or on completion
693    Up to ATA/ATAPI-7, the standard specifies that ABRT could be set on
694    ICRC errors and on cases where a device is not able to complete a
695    command. Combined with the fact that MWDMA and PIO transfer errors
696    aren't allowed to use ICRC bit up to ATA/ATAPI-7, it seems to imply
697    that ABRT bit alone could indicate transfer errors.
698
699    However, ATA/ATAPI-8 draft revision 1f removes the part that ICRC
700    errors can turn on ABRT. So, this is kind of gray area. Some
701    heuristics are needed here.
702
703ATA/ATAPI device errors can be further categorized as follows.
704
705Media errors
706    This is indicated by UNC bit in the ERROR register. ATA devices
707    reports UNC error only after certain number of retries cannot
708    recover the data, so there's nothing much else to do other than
709    notifying upper layer.
710
711    READ and WRITE commands report CHS or LBA of the first failed sector
712    but ATA/ATAPI standard specifies that the amount of transferred data
713    on error completion is indeterminate, so we cannot assume that
714    sectors preceding the failed sector have been transferred and thus
715    cannot complete those sectors successfully as SCSI does.
716
717Media changed / media change requested error
718    <<TODO: fill here>>
719
720Address error
721    This is indicated by IDNF bit in the ERROR register. Report to upper
722    layer.
723
724Other errors
725    This can be invalid command or parameter indicated by ABRT ERROR bit
726    or some other error condition. Note that ABRT bit can indicate a lot
727    of things including ICRC and Address errors. Heuristics needed.
728
729Depending on commands, not all STATUS/ERROR bits are applicable. These
730non-applicable bits are marked with "na" in the output descriptions but
731up to ATA/ATAPI-7 no definition of "na" can be found. However,
732ATA/ATAPI-8 draft revision 1f describes "N/A" as follows.
733
734    3.2.3.3a N/A
735        A keyword the indicates a field has no defined value in this
736        standard and should not be checked by the host or device. N/A
737        fields should be cleared to zero.
738
739So, it seems reasonable to assume that "na" bits are cleared to zero by
740devices and thus need no explicit masking.
741
742ATAPI device CHECK CONDITION
743~~~~~~~~~~~~~~~~~~~~~~~~~~~~
744
745ATAPI device CHECK CONDITION error is indicated by set CHK bit (ERR bit)
746in the STATUS register after the last byte of CDB is transferred for a
747PACKET command. For this kind of errors, sense data should be acquired
748to gather information regarding the errors. REQUEST SENSE packet command
749should be used to acquire sense data.
750
751Once sense data is acquired, this type of errors can be handled
752similarly to other SCSI errors. Note that sense data may indicate ATA
753bus error (e.g. Sense Key 04h HARDWARE ERROR && ASC/ASCQ 47h/00h SCSI
754PARITY ERROR). In such cases, the error should be considered as an ATA
755bus error and handled according to `ATA bus error <#excatATAbusErr>`__.
756
757ATA device error (NCQ)
758~~~~~~~~~~~~~~~~~~~~~~
759
760NCQ command error is indicated by cleared BSY and set ERR bit during NCQ
761command phase (one or more NCQ commands outstanding). Although STATUS
762and ERROR registers will contain valid values describing the error, READ
763LOG EXT is required to clear the error condition, determine which
764command has failed and acquire more information.
765
766READ LOG EXT Log Page 10h reports which tag has failed and taskfile
767register values describing the error. With this information the failed
768command can be handled as a normal ATA command error as in
769`ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION) <#excatDevErr>`__
770and all other in-flight commands must be retried. Note that this retry
771should not be counted - it's likely that commands retried this way would
772have completed normally if it were not for the failed command.
773
774Note that ATA bus errors can be reported as ATA device NCQ errors. This
775should be handled as described in `ATA bus error <#excatATAbusErr>`__.
776
777If READ LOG EXT Log Page 10h fails or reports NQ, we're thoroughly
778screwed. This condition should be treated according to
779`HSM violation <#excatHSMviolation>`__.
780
781ATA bus error
782~~~~~~~~~~~~~
783
784ATA bus error means that data corruption occurred during transmission
785over ATA bus (SATA or PATA). This type of errors can be indicated by
786
787-  ICRC or ABRT error as described in
788   `ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION) <#excatDevErr>`__.
789
790-  Controller-specific error completion with error information
791   indicating transmission error.
792
793-  On some controllers, command timeout. In this case, there may be a
794   mechanism to determine that the timeout is due to transmission error.
795
796-  Unknown/random errors, timeouts and all sorts of weirdities.
797
798As described above, transmission errors can cause wide variety of
799symptoms ranging from device ICRC error to random device lockup, and,
800for many cases, there is no way to tell if an error condition is due to
801transmission error or not; therefore, it's necessary to employ some kind
802of heuristic when dealing with errors and timeouts. For example,
803encountering repetitive ABRT errors for known supported command is
804likely to indicate ATA bus error.
805
806Once it's determined that ATA bus errors have possibly occurred,
807lowering ATA bus transmission speed is one of actions which may
808alleviate the problem. See `Reconfigure transport <#exrecReconf>`__ for
809more information.
810
811PCI bus error
812~~~~~~~~~~~~~
813
814Data corruption or other failures during transmission over PCI (or other
815system bus). For standard BMDMA, this is indicated by Error bit in the
816BMDMA Status register. This type of errors must be logged as it
817indicates something is very wrong with the system. Resetting host
818controller is recommended.
819
820Late completion
821~~~~~~~~~~~~~~~
822
823This occurs when timeout occurs and the timeout handler finds out that
824the timed out command has completed successfully or with error. This is
825usually caused by lost interrupts. This type of errors must be logged.
826Resetting host controller is recommended.
827
828Unknown error (timeout)
829~~~~~~~~~~~~~~~~~~~~~~~
830
831This is when timeout occurs and the command is still processing or the
832host and device are in unknown state. When this occurs, HSM could be in
833any valid or invalid state. To bring the device to known state and make
834it forget about the timed out command, resetting is necessary. The timed
835out command may be retried.
836
837Timeouts can also be caused by transmission errors. Refer to
838`ATA bus error <#excatATAbusErr>`__ for more details.
839
840Hotplug and power management exceptions
841~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
842
843<<TODO: fill here>>
844
845EH recovery actions
846-------------------
847
848This section discusses several important recovery actions.
849
850Clearing error condition
851~~~~~~~~~~~~~~~~~~~~~~~~
852
853Many controllers require its error registers to be cleared by error
854handler. Different controllers may have different requirements.
855
856For SATA, it's strongly recommended to clear at least SError register
857during error handling.
858
859Reset
860~~~~~
861
862During EH, resetting is necessary in the following cases.
863
864-  HSM is in unknown or invalid state
865
866-  HBA is in unknown or invalid state
867
868-  EH needs to make HBA/device forget about in-flight commands
869
870-  HBA/device behaves weirdly
871
872Resetting during EH might be a good idea regardless of error condition
873to improve EH robustness. Whether to reset both or either one of HBA and
874device depends on situation but the following scheme is recommended.
875
876-  When it's known that HBA is in ready state but ATA/ATAPI device is in
877   unknown state, reset only device.
878
879-  If HBA is in unknown state, reset both HBA and device.
880
881HBA resetting is implementation specific. For a controller complying to
882taskfile/BMDMA PCI IDE, stopping active DMA transaction may be
883sufficient iff BMDMA state is the only HBA context. But even mostly
884taskfile/BMDMA PCI IDE complying controllers may have implementation
885specific requirements and mechanism to reset themselves. This must be
886addressed by specific drivers.
887
888OTOH, ATA/ATAPI standard describes in detail ways to reset ATA/ATAPI
889devices.
890
891PATA hardware reset
892    This is hardware initiated device reset signalled with asserted PATA
893    RESET- signal. There is no standard way to initiate hardware reset
894    from software although some hardware provides registers that allow
895    driver to directly tweak the RESET- signal.
896
897Software reset
898    This is achieved by turning CONTROL SRST bit on for at least 5us.
899    Both PATA and SATA support it but, in case of SATA, this may require
900    controller-specific support as the second Register FIS to clear SRST
901    should be transmitted while BSY bit is still set. Note that on PATA,
902    this resets both master and slave devices on a channel.
903
904EXECUTE DEVICE DIAGNOSTIC command
905    Although ATA/ATAPI standard doesn't describe exactly, EDD implies
906    some level of resetting, possibly similar level with software reset.
907    Host-side EDD protocol can be handled with normal command processing
908    and most SATA controllers should be able to handle EDD's just like
909    other commands. As in software reset, EDD affects both devices on a
910    PATA bus.
911
912    Although EDD does reset devices, this doesn't suit error handling as
913    EDD cannot be issued while BSY is set and it's unclear how it will
914    act when device is in unknown/weird state.
915
916ATAPI DEVICE RESET command
917    This is very similar to software reset except that reset can be
918    restricted to the selected device without affecting the other device
919    sharing the cable.
920
921SATA phy reset
922    This is the preferred way of resetting a SATA device. In effect,
923    it's identical to PATA hardware reset. Note that this can be done
924    with the standard SCR Control register. As such, it's usually easier
925    to implement than software reset.
926
927One more thing to consider when resetting devices is that resetting
928clears certain configuration parameters and they need to be set to their
929previous or newly adjusted values after reset.
930
931Parameters affected are.
932
933-  CHS set up with INITIALIZE DEVICE PARAMETERS (seldom used)
934
935-  Parameters set with SET FEATURES including transfer mode setting
936
937-  Block count set with SET MULTIPLE MODE
938
939-  Other parameters (SET MAX, MEDIA LOCK...)
940
941ATA/ATAPI standard specifies that some parameters must be maintained
942across hardware or software reset, but doesn't strictly specify all of
943them. Always reconfiguring needed parameters after reset is required for
944robustness. Note that this also applies when resuming from deep sleep
945(power-off).
946
947Also, ATA/ATAPI standard requires that IDENTIFY DEVICE / IDENTIFY PACKET
948DEVICE is issued after any configuration parameter is updated or a
949hardware reset and the result used for further operation. OS driver is
950required to implement revalidation mechanism to support this.
951
952Reconfigure transport
953~~~~~~~~~~~~~~~~~~~~~
954
955For both PATA and SATA, a lot of corners are cut for cheap connectors,
956cables or controllers and it's quite common to see high transmission
957error rate. This can be mitigated by lowering transmission speed.
958
959The following is a possible scheme Jeff Garzik suggested.
960
961    If more than $N (3?) transmission errors happen in 15 minutes,
962
963    -  if SATA, decrease SATA PHY speed. if speed cannot be decreased,
964
965    -  decrease UDMA xfer speed. if at UDMA0, switch to PIO4,
966
967    -  decrease PIO xfer speed. if at PIO3, complain, but continue
968
969ata_piix Internals
970===================
971
972.. kernel-doc:: drivers/ata/ata_piix.c
973   :internal:
974
975sata_sil Internals
976===================
977
978.. kernel-doc:: drivers/ata/sata_sil.c
979   :internal:
980
981Thanks
982======
983
984The bulk of the ATA knowledge comes thanks to long conversations with
985Andre Hedrick (www.linux-ide.org), and long hours pondering the ATA and
986SCSI specifications.
987
988Thanks to Alan Cox for pointing out similarities between SATA and SCSI,
989and in general for motivation to hack on libata.
990
991libata's device detection method, ata_pio_devchk, and in general all
992the early probing was based on extensive study of Hale Landis's
993probe/reset code in his ATADRVR driver (www.ata-atapi.com).
v5.9
   1========================
   2libATA Developer's Guide
   3========================
   4
   5:Author: Jeff Garzik
   6
   7Introduction
   8============
   9
  10libATA is a library used inside the Linux kernel to support ATA host
  11controllers and devices. libATA provides an ATA driver API, class
  12transports for ATA and ATAPI devices, and SCSI<->ATA translation for ATA
  13devices according to the T10 SAT specification.
  14
  15This Guide documents the libATA driver API, library functions, library
  16internals, and a couple sample ATA low-level drivers.
  17
  18libata Driver API
  19=================
  20
  21:c:type:`struct ata_port_operations <ata_port_operations>`
  22is defined for every low-level libata
  23hardware driver, and it controls how the low-level driver interfaces
  24with the ATA and SCSI layers.
  25
  26FIS-based drivers will hook into the system with ``->qc_prep()`` and
  27``->qc_issue()`` high-level hooks. Hardware which behaves in a manner
  28similar to PCI IDE hardware may utilize several generic helpers,
  29defining at a bare minimum the bus I/O addresses of the ATA shadow
  30register blocks.
  31
  32:c:type:`struct ata_port_operations <ata_port_operations>`
  33----------------------------------------------------------
  34
  35Disable ATA port
  36~~~~~~~~~~~~~~~~
  37
  38::
  39
  40    void (*port_disable) (struct ata_port *);
  41
  42
  43Called from :c:func:`ata_bus_probe` error path, as well as when unregistering
  44from the SCSI module (rmmod, hot unplug). This function should do
  45whatever needs to be done to take the port out of use. In most cases,
  46:c:func:`ata_port_disable` can be used as this hook.
  47
  48Called from :c:func:`ata_bus_probe` on a failed probe. Called from
  49:c:func:`ata_scsi_release`.
  50
  51Post-IDENTIFY device configuration
  52~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  53
  54::
  55
  56    void (*dev_config) (struct ata_port *, struct ata_device *);
  57
  58
  59Called after IDENTIFY [PACKET] DEVICE is issued to each device found.
  60Typically used to apply device-specific fixups prior to issue of SET
  61FEATURES - XFER MODE, and prior to operation.
  62
  63This entry may be specified as NULL in ata_port_operations.
  64
  65Set PIO/DMA mode
  66~~~~~~~~~~~~~~~~
  67
  68::
  69
  70    void (*set_piomode) (struct ata_port *, struct ata_device *);
  71    void (*set_dmamode) (struct ata_port *, struct ata_device *);
  72    void (*post_set_mode) (struct ata_port *);
  73    unsigned int (*mode_filter) (struct ata_port *, struct ata_device *, unsigned int);
  74
  75
  76Hooks called prior to the issue of SET FEATURES - XFER MODE command. The
  77optional ``->mode_filter()`` hook is called when libata has built a mask of
  78the possible modes. This is passed to the ``->mode_filter()`` function
  79which should return a mask of valid modes after filtering those
  80unsuitable due to hardware limits. It is not valid to use this interface
  81to add modes.
  82
  83``dev->pio_mode`` and ``dev->dma_mode`` are guaranteed to be valid when
  84``->set_piomode()`` and when ``->set_dmamode()`` is called. The timings for
  85any other drive sharing the cable will also be valid at this point. That
  86is the library records the decisions for the modes of each drive on a
  87channel before it attempts to set any of them.
  88
  89``->post_set_mode()`` is called unconditionally, after the SET FEATURES -
  90XFER MODE command completes successfully.
  91
  92``->set_piomode()`` is always called (if present), but ``->set_dma_mode()``
  93is only called if DMA is possible.
  94
  95Taskfile read/write
  96~~~~~~~~~~~~~~~~~~~
  97
  98::
  99
 100    void (*sff_tf_load) (struct ata_port *ap, struct ata_taskfile *tf);
 101    void (*sff_tf_read) (struct ata_port *ap, struct ata_taskfile *tf);
 102
 103
 104``->tf_load()`` is called to load the given taskfile into hardware
 105registers / DMA buffers. ``->tf_read()`` is called to read the hardware
 106registers / DMA buffers, to obtain the current set of taskfile register
 107values. Most drivers for taskfile-based hardware (PIO or MMIO) use
 108:c:func:`ata_sff_tf_load` and :c:func:`ata_sff_tf_read` for these hooks.
 109
 110PIO data read/write
 111~~~~~~~~~~~~~~~~~~~
 112
 113::
 114
 115    void (*sff_data_xfer) (struct ata_device *, unsigned char *, unsigned int, int);
 116
 117
 118All bmdma-style drivers must implement this hook. This is the low-level
 119operation that actually copies the data bytes during a PIO data
 120transfer. Typically the driver will choose one of
 121:c:func:`ata_sff_data_xfer`, or :c:func:`ata_sff_data_xfer32`.
 122
 123ATA command execute
 124~~~~~~~~~~~~~~~~~~~
 125
 126::
 127
 128    void (*sff_exec_command)(struct ata_port *ap, struct ata_taskfile *tf);
 129
 130
 131causes an ATA command, previously loaded with ``->tf_load()``, to be
 132initiated in hardware. Most drivers for taskfile-based hardware use
 133:c:func:`ata_sff_exec_command` for this hook.
 134
 135Per-cmd ATAPI DMA capabilities filter
 136~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 137
 138::
 139
 140    int (*check_atapi_dma) (struct ata_queued_cmd *qc);
 141
 142
 143Allow low-level driver to filter ATA PACKET commands, returning a status
 144indicating whether or not it is OK to use DMA for the supplied PACKET
 145command.
 146
 147This hook may be specified as NULL, in which case libata will assume
 148that atapi dma can be supported.
 149
 150Read specific ATA shadow registers
 151~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 152
 153::
 154
 155    u8   (*sff_check_status)(struct ata_port *ap);
 156    u8   (*sff_check_altstatus)(struct ata_port *ap);
 157
 158
 159Reads the Status/AltStatus ATA shadow register from hardware. On some
 160hardware, reading the Status register has the side effect of clearing
 161the interrupt condition. Most drivers for taskfile-based hardware use
 162:c:func:`ata_sff_check_status` for this hook.
 163
 164Write specific ATA shadow register
 165~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 166
 167::
 168
 169    void (*sff_set_devctl)(struct ata_port *ap, u8 ctl);
 170
 171
 172Write the device control ATA shadow register to the hardware. Most
 173drivers don't need to define this.
 174
 175Select ATA device on bus
 176~~~~~~~~~~~~~~~~~~~~~~~~
 177
 178::
 179
 180    void (*sff_dev_select)(struct ata_port *ap, unsigned int device);
 181
 182
 183Issues the low-level hardware command(s) that causes one of N hardware
 184devices to be considered 'selected' (active and available for use) on
 185the ATA bus. This generally has no meaning on FIS-based devices.
 186
 187Most drivers for taskfile-based hardware use :c:func:`ata_sff_dev_select` for
 188this hook.
 189
 190Private tuning method
 191~~~~~~~~~~~~~~~~~~~~~
 192
 193::
 194
 195    void (*set_mode) (struct ata_port *ap);
 196
 197
 198By default libata performs drive and controller tuning in accordance
 199with the ATA timing rules and also applies blacklists and cable limits.
 200Some controllers need special handling and have custom tuning rules,
 201typically raid controllers that use ATA commands but do not actually do
 202drive timing.
 203
 204    **Warning**
 205
 206    This hook should not be used to replace the standard controller
 207    tuning logic when a controller has quirks. Replacing the default
 208    tuning logic in that case would bypass handling for drive and bridge
 209    quirks that may be important to data reliability. If a controller
 210    needs to filter the mode selection it should use the mode_filter
 211    hook instead.
 212
 213Control PCI IDE BMDMA engine
 214~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 215
 216::
 217
 218    void (*bmdma_setup) (struct ata_queued_cmd *qc);
 219    void (*bmdma_start) (struct ata_queued_cmd *qc);
 220    void (*bmdma_stop) (struct ata_port *ap);
 221    u8   (*bmdma_status) (struct ata_port *ap);
 222
 223
 224When setting up an IDE BMDMA transaction, these hooks arm
 225(``->bmdma_setup``), fire (``->bmdma_start``), and halt (``->bmdma_stop``) the
 226hardware's DMA engine. ``->bmdma_status`` is used to read the standard PCI
 227IDE DMA Status register.
 228
 229These hooks are typically either no-ops, or simply not implemented, in
 230FIS-based drivers.
 231
 232Most legacy IDE drivers use :c:func:`ata_bmdma_setup` for the
 233:c:func:`bmdma_setup` hook. :c:func:`ata_bmdma_setup` will write the pointer
 234to the PRD table to the IDE PRD Table Address register, enable DMA in the DMA
 235Command register, and call :c:func:`exec_command` to begin the transfer.
 236
 237Most legacy IDE drivers use :c:func:`ata_bmdma_start` for the
 238:c:func:`bmdma_start` hook. :c:func:`ata_bmdma_start` will write the
 239ATA_DMA_START flag to the DMA Command register.
 240
 241Many legacy IDE drivers use :c:func:`ata_bmdma_stop` for the
 242:c:func:`bmdma_stop` hook. :c:func:`ata_bmdma_stop` clears the ATA_DMA_START
 243flag in the DMA command register.
 244
 245Many legacy IDE drivers use :c:func:`ata_bmdma_status` as the
 246:c:func:`bmdma_status` hook.
 247
 248High-level taskfile hooks
 249~~~~~~~~~~~~~~~~~~~~~~~~~
 250
 251::
 252
 253    enum ata_completion_errors (*qc_prep) (struct ata_queued_cmd *qc);
 254    int (*qc_issue) (struct ata_queued_cmd *qc);
 255
 256
 257Higher-level hooks, these two hooks can potentially supersede several of
 258the above taskfile/DMA engine hooks. ``->qc_prep`` is called after the
 259buffers have been DMA-mapped, and is typically used to populate the
 260hardware's DMA scatter-gather table. Some drivers use the standard
 261:c:func:`ata_bmdma_qc_prep` and :c:func:`ata_bmdma_dumb_qc_prep` helper
 262functions, but more advanced drivers roll their own.
 263
 264``->qc_issue`` is used to make a command active, once the hardware and S/G
 265tables have been prepared. IDE BMDMA drivers use the helper function
 266:c:func:`ata_sff_qc_issue` for taskfile protocol-based dispatch. More
 267advanced drivers implement their own ``->qc_issue``.
 268
 269:c:func:`ata_sff_qc_issue` calls ``->sff_tf_load()``, ``->bmdma_setup()``, and
 270``->bmdma_start()`` as necessary to initiate a transfer.
 271
 272Exception and probe handling (EH)
 273~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 274
 275::
 276
 277    void (*eng_timeout) (struct ata_port *ap);
 278    void (*phy_reset) (struct ata_port *ap);
 279
 280
 281Deprecated. Use ``->error_handler()`` instead.
 282
 283::
 284
 285    void (*freeze) (struct ata_port *ap);
 286    void (*thaw) (struct ata_port *ap);
 287
 288
 289:c:func:`ata_port_freeze` is called when HSM violations or some other
 290condition disrupts normal operation of the port. A frozen port is not
 291allowed to perform any operation until the port is thawed, which usually
 292follows a successful reset.
 293
 294The optional ``->freeze()`` callback can be used for freezing the port
 295hardware-wise (e.g. mask interrupt and stop DMA engine). If a port
 296cannot be frozen hardware-wise, the interrupt handler must ack and clear
 297interrupts unconditionally while the port is frozen.
 298
 299The optional ``->thaw()`` callback is called to perform the opposite of
 300``->freeze()``: prepare the port for normal operation once again. Unmask
 301interrupts, start DMA engine, etc.
 302
 303::
 304
 305    void (*error_handler) (struct ata_port *ap);
 306
 307
 308``->error_handler()`` is a driver's hook into probe, hotplug, and recovery
 309and other exceptional conditions. The primary responsibility of an
 310implementation is to call :c:func:`ata_do_eh` or :c:func:`ata_bmdma_drive_eh`
 311with a set of EH hooks as arguments:
 312
 313'prereset' hook (may be NULL) is called during an EH reset, before any
 314other actions are taken.
 315
 316'postreset' hook (may be NULL) is called after the EH reset is
 317performed. Based on existing conditions, severity of the problem, and
 318hardware capabilities,
 319
 320Either 'softreset' (may be NULL) or 'hardreset' (may be NULL) will be
 321called to perform the low-level EH reset.
 322
 323::
 324
 325    void (*post_internal_cmd) (struct ata_queued_cmd *qc);
 326
 327
 328Perform any hardware-specific actions necessary to finish processing
 329after executing a probe-time or EH-time command via
 330:c:func:`ata_exec_internal`.
 331
 332Hardware interrupt handling
 333~~~~~~~~~~~~~~~~~~~~~~~~~~~
 334
 335::
 336
 337    irqreturn_t (*irq_handler)(int, void *, struct pt_regs *);
 338    void (*irq_clear) (struct ata_port *);
 339
 340
 341``->irq_handler`` is the interrupt handling routine registered with the
 342system, by libata. ``->irq_clear`` is called during probe just before the
 343interrupt handler is registered, to be sure hardware is quiet.
 344
 345The second argument, dev_instance, should be cast to a pointer to
 346:c:type:`struct ata_host_set <ata_host_set>`.
 347
 348Most legacy IDE drivers use :c:func:`ata_sff_interrupt` for the irq_handler
 349hook, which scans all ports in the host_set, determines which queued
 350command was active (if any), and calls ata_sff_host_intr(ap,qc).
 351
 352Most legacy IDE drivers use :c:func:`ata_sff_irq_clear` for the
 353:c:func:`irq_clear` hook, which simply clears the interrupt and error flags
 354in the DMA status register.
 355
 356SATA phy read/write
 357~~~~~~~~~~~~~~~~~~~
 358
 359::
 360
 361    int (*scr_read) (struct ata_port *ap, unsigned int sc_reg,
 362             u32 *val);
 363    int (*scr_write) (struct ata_port *ap, unsigned int sc_reg,
 364                       u32 val);
 365
 366
 367Read and write standard SATA phy registers. Currently only used if
 368``->phy_reset`` hook called the :c:func:`sata_phy_reset` helper function.
 369sc_reg is one of SCR_STATUS, SCR_CONTROL, SCR_ERROR, or SCR_ACTIVE.
 370
 371Init and shutdown
 372~~~~~~~~~~~~~~~~~
 373
 374::
 375
 376    int (*port_start) (struct ata_port *ap);
 377    void (*port_stop) (struct ata_port *ap);
 378    void (*host_stop) (struct ata_host_set *host_set);
 379
 380
 381``->port_start()`` is called just after the data structures for each port
 382are initialized. Typically this is used to alloc per-port DMA buffers /
 383tables / rings, enable DMA engines, and similar tasks. Some drivers also
 384use this entry point as a chance to allocate driver-private memory for
 385``ap->private_data``.
 386
 387Many drivers use :c:func:`ata_port_start` as this hook or call it from their
 388own :c:func:`port_start` hooks. :c:func:`ata_port_start` allocates space for
 389a legacy IDE PRD table and returns.
 390
 391``->port_stop()`` is called after ``->host_stop()``. Its sole function is to
 392release DMA/memory resources, now that they are no longer actively being
 393used. Many drivers also free driver-private data from port at this time.
 394
 395``->host_stop()`` is called after all ``->port_stop()`` calls have completed.
 396The hook must finalize hardware shutdown, release DMA and other
 397resources, etc. This hook may be specified as NULL, in which case it is
 398not called.
 399
 400Error handling
 401==============
 402
 403This chapter describes how errors are handled under libata. Readers are
 404advised to read SCSI EH (Documentation/scsi/scsi_eh.rst) and ATA
 405exceptions doc first.
 406
 407Origins of commands
 408-------------------
 409
 410In libata, a command is represented with
 411:c:type:`struct ata_queued_cmd <ata_queued_cmd>` or qc.
 412qc's are preallocated during port initialization and repetitively used
 413for command executions. Currently only one qc is allocated per port but
 414yet-to-be-merged NCQ branch allocates one for each tag and maps each qc
 415to NCQ tag 1-to-1.
 416
 417libata commands can originate from two sources - libata itself and SCSI
 418midlayer. libata internal commands are used for initialization and error
 419handling. All normal blk requests and commands for SCSI emulation are
 420passed as SCSI commands through queuecommand callback of SCSI host
 421template.
 422
 423How commands are issued
 424-----------------------
 425
 426Internal commands
 427    First, qc is allocated and initialized using :c:func:`ata_qc_new_init`.
 428    Although :c:func:`ata_qc_new_init` doesn't implement any wait or retry
 429    mechanism when qc is not available, internal commands are currently
 430    issued only during initialization and error recovery, so no other
 431    command is active and allocation is guaranteed to succeed.
 432
 433    Once allocated qc's taskfile is initialized for the command to be
 434    executed. qc currently has two mechanisms to notify completion. One
 435    is via ``qc->complete_fn()`` callback and the other is completion
 436    ``qc->waiting``. ``qc->complete_fn()`` callback is the asynchronous path
 437    used by normal SCSI translated commands and ``qc->waiting`` is the
 438    synchronous (issuer sleeps in process context) path used by internal
 439    commands.
 440
 441    Once initialization is complete, host_set lock is acquired and the
 442    qc is issued.
 443
 444SCSI commands
 445    All libata drivers use :c:func:`ata_scsi_queuecmd` as
 446    ``hostt->queuecommand`` callback. scmds can either be simulated or
 447    translated. No qc is involved in processing a simulated scmd. The
 448    result is computed right away and the scmd is completed.
 449
 450    For a translated scmd, :c:func:`ata_qc_new_init` is invoked to allocate a
 451    qc and the scmd is translated into the qc. SCSI midlayer's
 452    completion notification function pointer is stored into
 453    ``qc->scsidone``.
 454
 455    ``qc->complete_fn()`` callback is used for completion notification. ATA
 456    commands use :c:func:`ata_scsi_qc_complete` while ATAPI commands use
 457    :c:func:`atapi_qc_complete`. Both functions end up calling ``qc->scsidone``
 458    to notify upper layer when the qc is finished. After translation is
 459    completed, the qc is issued with :c:func:`ata_qc_issue`.
 460
 461    Note that SCSI midlayer invokes hostt->queuecommand while holding
 462    host_set lock, so all above occur while holding host_set lock.
 463
 464How commands are processed
 465--------------------------
 466
 467Depending on which protocol and which controller are used, commands are
 468processed differently. For the purpose of discussion, a controller which
 469uses taskfile interface and all standard callbacks is assumed.
 470
 471Currently 6 ATA command protocols are used. They can be sorted into the
 472following four categories according to how they are processed.
 473
 474ATA NO DATA or DMA
 475    ATA_PROT_NODATA and ATA_PROT_DMA fall into this category. These
 476    types of commands don't require any software intervention once
 477    issued. Device will raise interrupt on completion.
 478
 479ATA PIO
 480    ATA_PROT_PIO is in this category. libata currently implements PIO
 481    with polling. ATA_NIEN bit is set to turn off interrupt and
 482    pio_task on ata_wq performs polling and IO.
 483
 484ATAPI NODATA or DMA
 485    ATA_PROT_ATAPI_NODATA and ATA_PROT_ATAPI_DMA are in this
 486    category. packet_task is used to poll BSY bit after issuing PACKET
 487    command. Once BSY is turned off by the device, packet_task
 488    transfers CDB and hands off processing to interrupt handler.
 489
 490ATAPI PIO
 491    ATA_PROT_ATAPI is in this category. ATA_NIEN bit is set and, as
 492    in ATAPI NODATA or DMA, packet_task submits cdb. However, after
 493    submitting cdb, further processing (data transfer) is handed off to
 494    pio_task.
 495
 496How commands are completed
 497--------------------------
 498
 499Once issued, all qc's are either completed with :c:func:`ata_qc_complete` or
 500time out. For commands which are handled by interrupts,
 501:c:func:`ata_host_intr` invokes :c:func:`ata_qc_complete`, and, for PIO tasks,
 502pio_task invokes :c:func:`ata_qc_complete`. In error cases, packet_task may
 503also complete commands.
 504
 505:c:func:`ata_qc_complete` does the following.
 506
 5071. DMA memory is unmapped.
 508
 5092. ATA_QCFLAG_ACTIVE is cleared from qc->flags.
 510
 5113. :c:func:`qc->complete_fn` callback is invoked. If the return value of the
 512   callback is not zero. Completion is short circuited and
 513   :c:func:`ata_qc_complete` returns.
 514
 5154. :c:func:`__ata_qc_complete` is called, which does
 516
 517   1. ``qc->flags`` is cleared to zero.
 518
 519   2. ``ap->active_tag`` and ``qc->tag`` are poisoned.
 520
 521   3. ``qc->waiting`` is cleared & completed (in that order).
 522
 523   4. qc is deallocated by clearing appropriate bit in ``ap->qactive``.
 524
 525So, it basically notifies upper layer and deallocates qc. One exception
 526is short-circuit path in #3 which is used by :c:func:`atapi_qc_complete`.
 527
 528For all non-ATAPI commands, whether it fails or not, almost the same
 529code path is taken and very little error handling takes place. A qc is
 530completed with success status if it succeeded, with failed status
 531otherwise.
 532
 533However, failed ATAPI commands require more handling as REQUEST SENSE is
 534needed to acquire sense data. If an ATAPI command fails,
 535:c:func:`ata_qc_complete` is invoked with error status, which in turn invokes
 536:c:func:`atapi_qc_complete` via ``qc->complete_fn()`` callback.
 537
 538This makes :c:func:`atapi_qc_complete` set ``scmd->result`` to
 539SAM_STAT_CHECK_CONDITION, complete the scmd and return 1. As the
 540sense data is empty but ``scmd->result`` is CHECK CONDITION, SCSI midlayer
 541will invoke EH for the scmd, and returning 1 makes :c:func:`ata_qc_complete`
 542to return without deallocating the qc. This leads us to
 543:c:func:`ata_scsi_error` with partially completed qc.
 544
 545:c:func:`ata_scsi_error`
 546------------------------
 547
 548:c:func:`ata_scsi_error` is the current ``transportt->eh_strategy_handler()``
 549for libata. As discussed above, this will be entered in two cases -
 550timeout and ATAPI error completion. This function calls low level libata
 551driver's :c:func:`eng_timeout` callback, the standard callback for which is
 552:c:func:`ata_eng_timeout`. It checks if a qc is active and calls
 553:c:func:`ata_qc_timeout` on the qc if so. Actual error handling occurs in
 554:c:func:`ata_qc_timeout`.
 555
 556If EH is invoked for timeout, :c:func:`ata_qc_timeout` stops BMDMA and
 557completes the qc. Note that as we're currently in EH, we cannot call
 558scsi_done. As described in SCSI EH doc, a recovered scmd should be
 559either retried with :c:func:`scsi_queue_insert` or finished with
 560:c:func:`scsi_finish_command`. Here, we override ``qc->scsidone`` with
 561:c:func:`scsi_finish_command` and calls :c:func:`ata_qc_complete`.
 562
 563If EH is invoked due to a failed ATAPI qc, the qc here is completed but
 564not deallocated. The purpose of this half-completion is to use the qc as
 565place holder to make EH code reach this place. This is a bit hackish,
 566but it works.
 567
 568Once control reaches here, the qc is deallocated by invoking
 569:c:func:`__ata_qc_complete` explicitly. Then, internal qc for REQUEST SENSE
 570is issued. Once sense data is acquired, scmd is finished by directly
 571invoking :c:func:`scsi_finish_command` on the scmd. Note that as we already
 572have completed and deallocated the qc which was associated with the
 573scmd, we don't need to/cannot call :c:func:`ata_qc_complete` again.
 574
 575Problems with the current EH
 576----------------------------
 577
 578-  Error representation is too crude. Currently any and all error
 579   conditions are represented with ATA STATUS and ERROR registers.
 580   Errors which aren't ATA device errors are treated as ATA device
 581   errors by setting ATA_ERR bit. Better error descriptor which can
 582   properly represent ATA and other errors/exceptions is needed.
 583
 584-  When handling timeouts, no action is taken to make device forget
 585   about the timed out command and ready for new commands.
 586
 587-  EH handling via :c:func:`ata_scsi_error` is not properly protected from
 588   usual command processing. On EH entrance, the device is not in
 589   quiescent state. Timed out commands may succeed or fail any time.
 590   pio_task and atapi_task may still be running.
 591
 592-  Too weak error recovery. Devices / controllers causing HSM mismatch
 593   errors and other errors quite often require reset to return to known
 594   state. Also, advanced error handling is necessary to support features
 595   like NCQ and hotplug.
 596
 597-  ATA errors are directly handled in the interrupt handler and PIO
 598   errors in pio_task. This is problematic for advanced error handling
 599   for the following reasons.
 600
 601   First, advanced error handling often requires context and internal qc
 602   execution.
 603
 604   Second, even a simple failure (say, CRC error) needs information
 605   gathering and could trigger complex error handling (say, resetting &
 606   reconfiguring). Having multiple code paths to gather information,
 607   enter EH and trigger actions makes life painful.
 608
 609   Third, scattered EH code makes implementing low level drivers
 610   difficult. Low level drivers override libata callbacks. If EH is
 611   scattered over several places, each affected callbacks should perform
 612   its part of error handling. This can be error prone and painful.
 613
 614libata Library
 615==============
 616
 617.. kernel-doc:: drivers/ata/libata-core.c
 618   :export:
 619
 620libata Core Internals
 621=====================
 622
 623.. kernel-doc:: drivers/ata/libata-core.c
 624   :internal:
 625
 626.. kernel-doc:: drivers/ata/libata-eh.c
 627
 628libata SCSI translation/emulation
 629=================================
 630
 631.. kernel-doc:: drivers/ata/libata-scsi.c
 632   :export:
 633
 634.. kernel-doc:: drivers/ata/libata-scsi.c
 635   :internal:
 636
 637ATA errors and exceptions
 638=========================
 639
 640This chapter tries to identify what error/exception conditions exist for
 641ATA/ATAPI devices and describe how they should be handled in
 642implementation-neutral way.
 643
 644The term 'error' is used to describe conditions where either an explicit
 645error condition is reported from device or a command has timed out.
 646
 647The term 'exception' is either used to describe exceptional conditions
 648which are not errors (say, power or hotplug events), or to describe both
 649errors and non-error exceptional conditions. Where explicit distinction
 650between error and exception is necessary, the term 'non-error exception'
 651is used.
 652
 653Exception categories
 654--------------------
 655
 656Exceptions are described primarily with respect to legacy taskfile + bus
 657master IDE interface. If a controller provides other better mechanism
 658for error reporting, mapping those into categories described below
 659shouldn't be difficult.
 660
 661In the following sections, two recovery actions - reset and
 662reconfiguring transport - are mentioned. These are described further in
 663`EH recovery actions <#exrec>`__.
 664
 665HSM violation
 666~~~~~~~~~~~~~
 667
 668This error is indicated when STATUS value doesn't match HSM requirement
 669during issuing or execution any ATA/ATAPI command.
 670
 671-  ATA_STATUS doesn't contain !BSY && DRDY && !DRQ while trying to
 672   issue a command.
 673
 674-  !BSY && !DRQ during PIO data transfer.
 675
 676-  DRQ on command completion.
 677
 678-  !BSY && ERR after CDB transfer starts but before the last byte of CDB
 679   is transferred. ATA/ATAPI standard states that "The device shall not
 680   terminate the PACKET command with an error before the last byte of
 681   the command packet has been written" in the error outputs description
 682   of PACKET command and the state diagram doesn't include such
 683   transitions.
 684
 685In these cases, HSM is violated and not much information regarding the
 686error can be acquired from STATUS or ERROR register. IOW, this error can
 687be anything - driver bug, faulty device, controller and/or cable.
 688
 689As HSM is violated, reset is necessary to restore known state.
 690Reconfiguring transport for lower speed might be helpful too as
 691transmission errors sometimes cause this kind of errors.
 692
 693ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)
 694~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 695
 696These are errors detected and reported by ATA/ATAPI devices indicating
 697device problems. For this type of errors, STATUS and ERROR register
 698values are valid and describe error condition. Note that some of ATA bus
 699errors are detected by ATA/ATAPI devices and reported using the same
 700mechanism as device errors. Those cases are described later in this
 701section.
 702
 703For ATA commands, this type of errors are indicated by !BSY && ERR
 704during command execution and on completion.
 705
 706For ATAPI commands,
 707
 708-  !BSY && ERR && ABRT right after issuing PACKET indicates that PACKET
 709   command is not supported and falls in this category.
 710
 711-  !BSY && ERR(==CHK) && !ABRT after the last byte of CDB is transferred
 712   indicates CHECK CONDITION and doesn't fall in this category.
 713
 714-  !BSY && ERR(==CHK) && ABRT after the last byte of CDB is transferred
 715   \*probably\* indicates CHECK CONDITION and doesn't fall in this
 716   category.
 717
 718Of errors detected as above, the following are not ATA/ATAPI device
 719errors but ATA bus errors and should be handled according to
 720`ATA bus error <#excatATAbusErr>`__.
 721
 722CRC error during data transfer
 723    This is indicated by ICRC bit in the ERROR register and means that
 724    corruption occurred during data transfer. Up to ATA/ATAPI-7, the
 725    standard specifies that this bit is only applicable to UDMA
 726    transfers but ATA/ATAPI-8 draft revision 1f says that the bit may be
 727    applicable to multiword DMA and PIO.
 728
 729ABRT error during data transfer or on completion
 730    Up to ATA/ATAPI-7, the standard specifies that ABRT could be set on
 731    ICRC errors and on cases where a device is not able to complete a
 732    command. Combined with the fact that MWDMA and PIO transfer errors
 733    aren't allowed to use ICRC bit up to ATA/ATAPI-7, it seems to imply
 734    that ABRT bit alone could indicate transfer errors.
 735
 736    However, ATA/ATAPI-8 draft revision 1f removes the part that ICRC
 737    errors can turn on ABRT. So, this is kind of gray area. Some
 738    heuristics are needed here.
 739
 740ATA/ATAPI device errors can be further categorized as follows.
 741
 742Media errors
 743    This is indicated by UNC bit in the ERROR register. ATA devices
 744    reports UNC error only after certain number of retries cannot
 745    recover the data, so there's nothing much else to do other than
 746    notifying upper layer.
 747
 748    READ and WRITE commands report CHS or LBA of the first failed sector
 749    but ATA/ATAPI standard specifies that the amount of transferred data
 750    on error completion is indeterminate, so we cannot assume that
 751    sectors preceding the failed sector have been transferred and thus
 752    cannot complete those sectors successfully as SCSI does.
 753
 754Media changed / media change requested error
 755    <<TODO: fill here>>
 756
 757Address error
 758    This is indicated by IDNF bit in the ERROR register. Report to upper
 759    layer.
 760
 761Other errors
 762    This can be invalid command or parameter indicated by ABRT ERROR bit
 763    or some other error condition. Note that ABRT bit can indicate a lot
 764    of things including ICRC and Address errors. Heuristics needed.
 765
 766Depending on commands, not all STATUS/ERROR bits are applicable. These
 767non-applicable bits are marked with "na" in the output descriptions but
 768up to ATA/ATAPI-7 no definition of "na" can be found. However,
 769ATA/ATAPI-8 draft revision 1f describes "N/A" as follows.
 770
 771    3.2.3.3a N/A
 772        A keyword the indicates a field has no defined value in this
 773        standard and should not be checked by the host or device. N/A
 774        fields should be cleared to zero.
 775
 776So, it seems reasonable to assume that "na" bits are cleared to zero by
 777devices and thus need no explicit masking.
 778
 779ATAPI device CHECK CONDITION
 780~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 781
 782ATAPI device CHECK CONDITION error is indicated by set CHK bit (ERR bit)
 783in the STATUS register after the last byte of CDB is transferred for a
 784PACKET command. For this kind of errors, sense data should be acquired
 785to gather information regarding the errors. REQUEST SENSE packet command
 786should be used to acquire sense data.
 787
 788Once sense data is acquired, this type of errors can be handled
 789similarly to other SCSI errors. Note that sense data may indicate ATA
 790bus error (e.g. Sense Key 04h HARDWARE ERROR && ASC/ASCQ 47h/00h SCSI
 791PARITY ERROR). In such cases, the error should be considered as an ATA
 792bus error and handled according to `ATA bus error <#excatATAbusErr>`__.
 793
 794ATA device error (NCQ)
 795~~~~~~~~~~~~~~~~~~~~~~
 796
 797NCQ command error is indicated by cleared BSY and set ERR bit during NCQ
 798command phase (one or more NCQ commands outstanding). Although STATUS
 799and ERROR registers will contain valid values describing the error, READ
 800LOG EXT is required to clear the error condition, determine which
 801command has failed and acquire more information.
 802
 803READ LOG EXT Log Page 10h reports which tag has failed and taskfile
 804register values describing the error. With this information the failed
 805command can be handled as a normal ATA command error as in
 806`ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION) <#excatDevErr>`__
 807and all other in-flight commands must be retried. Note that this retry
 808should not be counted - it's likely that commands retried this way would
 809have completed normally if it were not for the failed command.
 810
 811Note that ATA bus errors can be reported as ATA device NCQ errors. This
 812should be handled as described in `ATA bus error <#excatATAbusErr>`__.
 813
 814If READ LOG EXT Log Page 10h fails or reports NQ, we're thoroughly
 815screwed. This condition should be treated according to
 816`HSM violation <#excatHSMviolation>`__.
 817
 818ATA bus error
 819~~~~~~~~~~~~~
 820
 821ATA bus error means that data corruption occurred during transmission
 822over ATA bus (SATA or PATA). This type of errors can be indicated by
 823
 824-  ICRC or ABRT error as described in
 825   `ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION) <#excatDevErr>`__.
 826
 827-  Controller-specific error completion with error information
 828   indicating transmission error.
 829
 830-  On some controllers, command timeout. In this case, there may be a
 831   mechanism to determine that the timeout is due to transmission error.
 832
 833-  Unknown/random errors, timeouts and all sorts of weirdities.
 834
 835As described above, transmission errors can cause wide variety of
 836symptoms ranging from device ICRC error to random device lockup, and,
 837for many cases, there is no way to tell if an error condition is due to
 838transmission error or not; therefore, it's necessary to employ some kind
 839of heuristic when dealing with errors and timeouts. For example,
 840encountering repetitive ABRT errors for known supported command is
 841likely to indicate ATA bus error.
 842
 843Once it's determined that ATA bus errors have possibly occurred,
 844lowering ATA bus transmission speed is one of actions which may
 845alleviate the problem. See `Reconfigure transport <#exrecReconf>`__ for
 846more information.
 847
 848PCI bus error
 849~~~~~~~~~~~~~
 850
 851Data corruption or other failures during transmission over PCI (or other
 852system bus). For standard BMDMA, this is indicated by Error bit in the
 853BMDMA Status register. This type of errors must be logged as it
 854indicates something is very wrong with the system. Resetting host
 855controller is recommended.
 856
 857Late completion
 858~~~~~~~~~~~~~~~
 859
 860This occurs when timeout occurs and the timeout handler finds out that
 861the timed out command has completed successfully or with error. This is
 862usually caused by lost interrupts. This type of errors must be logged.
 863Resetting host controller is recommended.
 864
 865Unknown error (timeout)
 866~~~~~~~~~~~~~~~~~~~~~~~
 867
 868This is when timeout occurs and the command is still processing or the
 869host and device are in unknown state. When this occurs, HSM could be in
 870any valid or invalid state. To bring the device to known state and make
 871it forget about the timed out command, resetting is necessary. The timed
 872out command may be retried.
 873
 874Timeouts can also be caused by transmission errors. Refer to
 875`ATA bus error <#excatATAbusErr>`__ for more details.
 876
 877Hotplug and power management exceptions
 878~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 879
 880<<TODO: fill here>>
 881
 882EH recovery actions
 883-------------------
 884
 885This section discusses several important recovery actions.
 886
 887Clearing error condition
 888~~~~~~~~~~~~~~~~~~~~~~~~
 889
 890Many controllers require its error registers to be cleared by error
 891handler. Different controllers may have different requirements.
 892
 893For SATA, it's strongly recommended to clear at least SError register
 894during error handling.
 895
 896Reset
 897~~~~~
 898
 899During EH, resetting is necessary in the following cases.
 900
 901-  HSM is in unknown or invalid state
 902
 903-  HBA is in unknown or invalid state
 904
 905-  EH needs to make HBA/device forget about in-flight commands
 906
 907-  HBA/device behaves weirdly
 908
 909Resetting during EH might be a good idea regardless of error condition
 910to improve EH robustness. Whether to reset both or either one of HBA and
 911device depends on situation but the following scheme is recommended.
 912
 913-  When it's known that HBA is in ready state but ATA/ATAPI device is in
 914   unknown state, reset only device.
 915
 916-  If HBA is in unknown state, reset both HBA and device.
 917
 918HBA resetting is implementation specific. For a controller complying to
 919taskfile/BMDMA PCI IDE, stopping active DMA transaction may be
 920sufficient iff BMDMA state is the only HBA context. But even mostly
 921taskfile/BMDMA PCI IDE complying controllers may have implementation
 922specific requirements and mechanism to reset themselves. This must be
 923addressed by specific drivers.
 924
 925OTOH, ATA/ATAPI standard describes in detail ways to reset ATA/ATAPI
 926devices.
 927
 928PATA hardware reset
 929    This is hardware initiated device reset signalled with asserted PATA
 930    RESET- signal. There is no standard way to initiate hardware reset
 931    from software although some hardware provides registers that allow
 932    driver to directly tweak the RESET- signal.
 933
 934Software reset
 935    This is achieved by turning CONTROL SRST bit on for at least 5us.
 936    Both PATA and SATA support it but, in case of SATA, this may require
 937    controller-specific support as the second Register FIS to clear SRST
 938    should be transmitted while BSY bit is still set. Note that on PATA,
 939    this resets both master and slave devices on a channel.
 940
 941EXECUTE DEVICE DIAGNOSTIC command
 942    Although ATA/ATAPI standard doesn't describe exactly, EDD implies
 943    some level of resetting, possibly similar level with software reset.
 944    Host-side EDD protocol can be handled with normal command processing
 945    and most SATA controllers should be able to handle EDD's just like
 946    other commands. As in software reset, EDD affects both devices on a
 947    PATA bus.
 948
 949    Although EDD does reset devices, this doesn't suit error handling as
 950    EDD cannot be issued while BSY is set and it's unclear how it will
 951    act when device is in unknown/weird state.
 952
 953ATAPI DEVICE RESET command
 954    This is very similar to software reset except that reset can be
 955    restricted to the selected device without affecting the other device
 956    sharing the cable.
 957
 958SATA phy reset
 959    This is the preferred way of resetting a SATA device. In effect,
 960    it's identical to PATA hardware reset. Note that this can be done
 961    with the standard SCR Control register. As such, it's usually easier
 962    to implement than software reset.
 963
 964One more thing to consider when resetting devices is that resetting
 965clears certain configuration parameters and they need to be set to their
 966previous or newly adjusted values after reset.
 967
 968Parameters affected are.
 969
 970-  CHS set up with INITIALIZE DEVICE PARAMETERS (seldom used)
 971
 972-  Parameters set with SET FEATURES including transfer mode setting
 973
 974-  Block count set with SET MULTIPLE MODE
 975
 976-  Other parameters (SET MAX, MEDIA LOCK...)
 977
 978ATA/ATAPI standard specifies that some parameters must be maintained
 979across hardware or software reset, but doesn't strictly specify all of
 980them. Always reconfiguring needed parameters after reset is required for
 981robustness. Note that this also applies when resuming from deep sleep
 982(power-off).
 983
 984Also, ATA/ATAPI standard requires that IDENTIFY DEVICE / IDENTIFY PACKET
 985DEVICE is issued after any configuration parameter is updated or a
 986hardware reset and the result used for further operation. OS driver is
 987required to implement revalidation mechanism to support this.
 988
 989Reconfigure transport
 990~~~~~~~~~~~~~~~~~~~~~
 991
 992For both PATA and SATA, a lot of corners are cut for cheap connectors,
 993cables or controllers and it's quite common to see high transmission
 994error rate. This can be mitigated by lowering transmission speed.
 995
 996The following is a possible scheme Jeff Garzik suggested.
 997
 998    If more than $N (3?) transmission errors happen in 15 minutes,
 999
1000    -  if SATA, decrease SATA PHY speed. if speed cannot be decreased,
1001
1002    -  decrease UDMA xfer speed. if at UDMA0, switch to PIO4,
1003
1004    -  decrease PIO xfer speed. if at PIO3, complain, but continue
1005
1006ata_piix Internals
1007===================
1008
1009.. kernel-doc:: drivers/ata/ata_piix.c
1010   :internal:
1011
1012sata_sil Internals
1013===================
1014
1015.. kernel-doc:: drivers/ata/sata_sil.c
1016   :internal:
1017
1018Thanks
1019======
1020
1021The bulk of the ATA knowledge comes thanks to long conversations with
1022Andre Hedrick (www.linux-ide.org), and long hours pondering the ATA and
1023SCSI specifications.
1024
1025Thanks to Alan Cox for pointing out similarities between SATA and SCSI,
1026and in general for motivation to hack on libata.
1027
1028libata's device detection method, ata_pio_devchk, and in general all
1029the early probing was based on extensive study of Hale Landis's
1030probe/reset code in his ATADRVR driver (www.ata-atapi.com).