brintos

brintos / linux-shallow public Read only

0
0
Text · 36.8 KiB · 5da27a7 Raw
994 lines · plain
1========================2libATA Developer's Guide3========================4 5:Author: Jeff Garzik6 7Introduction8============9 10libATA is a library used inside the Linux kernel to support ATA host11controllers and devices. libATA provides an ATA driver API, class12transports for ATA and ATAPI devices, and SCSI<->ATA translation for ATA13devices according to the T10 SAT specification.14 15This Guide documents the libATA driver API, library functions, library16internals, and a couple sample ATA low-level drivers.17 18libata Driver API19=================20 21:c:type:`struct ata_port_operations <ata_port_operations>`22is defined for every low-level libata23hardware driver, and it controls how the low-level driver interfaces24with the ATA and SCSI layers.25 26FIS-based drivers will hook into the system with ``->qc_prep()`` and27``->qc_issue()`` high-level hooks. Hardware which behaves in a manner28similar to PCI IDE hardware may utilize several generic helpers,29defining at a bare minimum the bus I/O addresses of the ATA shadow30register blocks.31 32:c:type:`struct ata_port_operations <ata_port_operations>`33----------------------------------------------------------34 35Post-IDENTIFY device configuration36~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~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 SET45FEATURES - XFER MODE, and prior to operation.46 47This entry may be specified as NULL in ata_port_operations.48 49Set PIO/DMA mode50~~~~~~~~~~~~~~~~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. The61optional ``->mode_filter()`` hook is called when libata has built a mask of62the possible modes. This is passed to the ``->mode_filter()`` function63which should return a mask of valid modes after filtering those64unsuitable due to hardware limits. It is not valid to use this interface65to add modes.66 67``dev->pio_mode`` and ``dev->dma_mode`` are guaranteed to be valid when68``->set_piomode()`` and when ``->set_dmamode()`` is called. The timings for69any other drive sharing the cable will also be valid at this point. That70is the library records the decisions for the modes of each drive on a71channel 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/write80~~~~~~~~~~~~~~~~~~~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 hardware89registers / DMA buffers. ``->tf_read()`` is called to read the hardware90registers / DMA buffers, to obtain the current set of taskfile register91values. Most drivers for taskfile-based hardware (PIO or MMIO) use92:c:func:`ata_sff_tf_load` and :c:func:`ata_sff_tf_read` for these hooks.93 94PIO data read/write95~~~~~~~~~~~~~~~~~~~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-level103operation that actually copies the data bytes during a PIO data104transfer. Typically the driver will choose one of105:c:func:`ata_sff_data_xfer`, or :c:func:`ata_sff_data_xfer32`.106 107ATA command execute108~~~~~~~~~~~~~~~~~~~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 be116initiated in hardware. Most drivers for taskfile-based hardware use117:c:func:`ata_sff_exec_command` for this hook.118 119Per-cmd ATAPI DMA capabilities filter120~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~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 status128indicating whether or not it is OK to use DMA for the supplied PACKET129command.130 131This hook may be specified as NULL, in which case libata will assume132that atapi dma can be supported.133 134Read specific ATA shadow registers135~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~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 some144hardware, reading the Status register has the side effect of clearing145the interrupt condition. Most drivers for taskfile-based hardware use146:c:func:`ata_sff_check_status` for this hook.147 148Write specific ATA shadow register149~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~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. Most157drivers don't need to define this.158 159Select ATA device on bus160~~~~~~~~~~~~~~~~~~~~~~~~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 hardware168devices to be considered 'selected' (active and available for use) on169the 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` for172this hook.173 174Private tuning method175~~~~~~~~~~~~~~~~~~~~~176 177::178 179    void (*set_mode) (struct ata_port *ap);180 181 182By default libata performs drive and controller tuning in accordance183with 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 do186drive timing.187 188    **Warning**189 190    This hook should not be used to replace the standard controller191    tuning logic when a controller has quirks. Replacing the default192    tuning logic in that case would bypass handling for drive and bridge193    quirks that may be important to data reliability. If a controller194    needs to filter the mode selection it should use the mode_filter195    hook instead.196 197Control PCI IDE BMDMA engine198~~~~~~~~~~~~~~~~~~~~~~~~~~~~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 arm209(``->bmdma_setup``), fire (``->bmdma_start``), and halt (``->bmdma_stop``) the210hardware's DMA engine. ``->bmdma_status`` is used to read the standard PCI211IDE DMA Status register.212 213These hooks are typically either no-ops, or simply not implemented, in214FIS-based drivers.215 216Most legacy IDE drivers use :c:func:`ata_bmdma_setup` for the217:c:func:`bmdma_setup` hook. :c:func:`ata_bmdma_setup` will write the pointer218to the PRD table to the IDE PRD Table Address register, enable DMA in the DMA219Command register, and call :c:func:`exec_command` to begin the transfer.220 221Most legacy IDE drivers use :c:func:`ata_bmdma_start` for the222:c:func:`bmdma_start` hook. :c:func:`ata_bmdma_start` will write the223ATA_DMA_START flag to the DMA Command register.224 225Many legacy IDE drivers use :c:func:`ata_bmdma_stop` for the226:c:func:`bmdma_stop` hook. :c:func:`ata_bmdma_stop` clears the ATA_DMA_START227flag in the DMA command register.228 229Many legacy IDE drivers use :c:func:`ata_bmdma_status` as the230:c:func:`bmdma_status` hook.231 232High-level taskfile hooks233~~~~~~~~~~~~~~~~~~~~~~~~~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 of242the above taskfile/DMA engine hooks. ``->qc_prep`` is called after the243buffers have been DMA-mapped, and is typically used to populate the244hardware's DMA scatter-gather table. Some drivers use the standard245:c:func:`ata_bmdma_qc_prep` and :c:func:`ata_bmdma_dumb_qc_prep` helper246functions, but more advanced drivers roll their own.247 248``->qc_issue`` is used to make a command active, once the hardware and S/G249tables have been prepared. IDE BMDMA drivers use the helper function250:c:func:`ata_sff_qc_issue` for taskfile protocol-based dispatch. More251advanced drivers implement their own ``->qc_issue``.252 253:c:func:`ata_sff_qc_issue` calls ``->sff_tf_load()``, ``->bmdma_setup()``, and254``->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 other266condition disrupts normal operation of the port. A frozen port is not267allowed to perform any operation until the port is thawed, which usually268follows a successful reset.269 270The optional ``->freeze()`` callback can be used for freezing the port271hardware-wise (e.g. mask interrupt and stop DMA engine). If a port272cannot be frozen hardware-wise, the interrupt handler must ack and clear273interrupts unconditionally while the port is frozen.274 275The optional ``->thaw()`` callback is called to perform the opposite of276``->freeze()``: prepare the port for normal operation once again. Unmask277interrupts, 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 recovery285and other exceptional conditions. The primary responsibility of an286implementation 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 any290other actions are taken.291 292'postreset' hook (may be NULL) is called after the EH reset is293performed. Based on existing conditions, severity of the problem, and294hardware capabilities,295 296Either 'softreset' (may be NULL) or 'hardreset' (may be NULL) will be297called 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 processing305after executing a probe-time or EH-time command via306:c:func:`ata_exec_internal`.307 308Hardware interrupt handling309~~~~~~~~~~~~~~~~~~~~~~~~~~~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 the318system, by libata. ``->irq_clear`` is called during probe just before the319interrupt handler is registered, to be sure hardware is quiet.320 321The second argument, dev_instance, should be cast to a pointer to322:c:type:`struct ata_host_set <ata_host_set>`.323 324Most legacy IDE drivers use :c:func:`ata_sff_interrupt` for the irq_handler325hook, which scans all ports in the host_set, determines which queued326command 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 the329:c:func:`irq_clear` hook, which simply clears the interrupt and error flags330in the DMA status register.331 332SATA phy read/write333~~~~~~~~~~~~~~~~~~~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 shutdown347~~~~~~~~~~~~~~~~~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 port357are initialized. Typically this is used to alloc per-port DMA buffers /358tables / rings, enable DMA engines, and similar tasks. Some drivers also359use this entry point as a chance to allocate driver-private memory for360``ap->private_data``.361 362Many drivers use :c:func:`ata_port_start` as this hook or call it from their363own :c:func:`port_start` hooks. :c:func:`ata_port_start` allocates space for364a legacy IDE PRD table and returns.365 366``->port_stop()`` is called after ``->host_stop()``. Its sole function is to367release DMA/memory resources, now that they are no longer actively being368used. 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 other372resources, etc. This hook may be specified as NULL, in which case it is373not called.374 375Error handling376==============377 378This chapter describes how errors are handled under libata. Readers are379advised to read SCSI EH (Documentation/scsi/scsi_eh.rst) and ATA380exceptions doc first.381 382Origins of commands383-------------------384 385In libata, a command is represented with386:c:type:`struct ata_queued_cmd <ata_queued_cmd>` or qc.387qc's are preallocated during port initialization and repetitively used388for command executions. Currently only one qc is allocated per port but389yet-to-be-merged NCQ branch allocates one for each tag and maps each qc390to NCQ tag 1-to-1.391 392libata commands can originate from two sources - libata itself and SCSI393midlayer. libata internal commands are used for initialization and error394handling. All normal blk requests and commands for SCSI emulation are395passed as SCSI commands through queuecommand callback of SCSI host396template.397 398How commands are issued399-----------------------400 401Internal commands402    Once allocated qc's taskfile is initialized for the command to be403    executed. qc currently has two mechanisms to notify completion. One404    is via ``qc->complete_fn()`` callback and the other is completion405    ``qc->waiting``. ``qc->complete_fn()`` callback is the asynchronous path406    used by normal SCSI translated commands and ``qc->waiting`` is the407    synchronous (issuer sleeps in process context) path used by internal408    commands.409 410    Once initialization is complete, host_set lock is acquired and the411    qc is issued.412 413SCSI commands414    All libata drivers use :c:func:`ata_scsi_queuecmd` as415    ``hostt->queuecommand`` callback. scmds can either be simulated or416    translated. No qc is involved in processing a simulated scmd. The417    result is computed right away and the scmd is completed.418 419    ``qc->complete_fn()`` callback is used for completion notification. ATA420    commands use :c:func:`ata_scsi_qc_complete` while ATAPI commands use421    :c:func:`atapi_qc_complete`. Both functions end up calling ``qc->scsidone``422    to notify upper layer when the qc is finished. After translation is423    completed, the qc is issued with :c:func:`ata_qc_issue`.424 425    Note that SCSI midlayer invokes hostt->queuecommand while holding426    host_set lock, so all above occur while holding host_set lock.427 428How commands are processed429--------------------------430 431Depending on which protocol and which controller are used, commands are432processed differently. For the purpose of discussion, a controller which433uses taskfile interface and all standard callbacks is assumed.434 435Currently 6 ATA command protocols are used. They can be sorted into the436following four categories according to how they are processed.437 438ATA NO DATA or DMA439    ATA_PROT_NODATA and ATA_PROT_DMA fall into this category. These440    types of commands don't require any software intervention once441    issued. Device will raise interrupt on completion.442 443ATA PIO444    ATA_PROT_PIO is in this category. libata currently implements PIO445    with polling. ATA_NIEN bit is set to turn off interrupt and446    pio_task on ata_wq performs polling and IO.447 448ATAPI NODATA or DMA449    ATA_PROT_ATAPI_NODATA and ATA_PROT_ATAPI_DMA are in this450    category. packet_task is used to poll BSY bit after issuing PACKET451    command. Once BSY is turned off by the device, packet_task452    transfers CDB and hands off processing to interrupt handler.453 454ATAPI PIO455    ATA_PROT_ATAPI is in this category. ATA_NIEN bit is set and, as456    in ATAPI NODATA or DMA, packet_task submits cdb. However, after457    submitting cdb, further processing (data transfer) is handed off to458    pio_task.459 460How commands are completed461--------------------------462 463Once issued, all qc's are either completed with :c:func:`ata_qc_complete` or464time 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 may467also 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 the476   callback is not zero. Completion is short circuited and477   :c:func:`ata_qc_complete` returns.478 4794. :c:func:`__ata_qc_complete` is called, which does480 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 exception490is 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 same493code path is taken and very little error handling takes place. A qc is494completed with success status if it succeeded, with failed status495otherwise.496 497However, failed ATAPI commands require more handling as REQUEST SENSE is498needed to acquire sense data. If an ATAPI command fails,499:c:func:`ata_qc_complete` is invoked with error status, which in turn invokes500:c:func:`atapi_qc_complete` via ``qc->complete_fn()`` callback.501 502This makes :c:func:`atapi_qc_complete` set ``scmd->result`` to503SAM_STAT_CHECK_CONDITION, complete the scmd and return 1. As the504sense data is empty but ``scmd->result`` is CHECK CONDITION, SCSI midlayer505will invoke EH for the scmd, and returning 1 makes :c:func:`ata_qc_complete`506to return without deallocating the qc. This leads us to507: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 active515and has not failed yet. Such a qc will be marked with AC_ERR_TIMEOUT such that516EH will know to handle it later. Then it calls low level libata driver's517:c:func:`error_handler` callback.518 519When the :c:func:`error_handler` callback is invoked it stops BMDMA and520completes the qc. Note that as we're currently in EH, we cannot call521scsi_done. As described in SCSI EH doc, a recovered scmd should be522either retried with :c:func:`scsi_queue_insert` or finished with523:c:func:`scsi_finish_command`. Here, we override ``qc->scsidone`` with524: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 but527not deallocated. The purpose of this half-completion is to use the qc as528place 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 invoking532:c:func:`__ata_qc_complete` explicitly. Then, internal qc for REQUEST SENSE533is issued. Once sense data is acquired, scmd is finished by directly534invoking :c:func:`scsi_finish_command` on the scmd. Note that as we already535have completed and deallocated the qc which was associated with the536scmd, we don't need to/cannot call :c:func:`ata_qc_complete` again.537 538Problems with the current EH539----------------------------540 541-  Error representation is too crude. Currently any and all error542   conditions are represented with ATA STATUS and ERROR registers.543   Errors which aren't ATA device errors are treated as ATA device544   errors by setting ATA_ERR bit. Better error descriptor which can545   properly represent ATA and other errors/exceptions is needed.546 547-  When handling timeouts, no action is taken to make device forget548   about the timed out command and ready for new commands.549 550-  EH handling via :c:func:`ata_scsi_error` is not properly protected from551   usual command processing. On EH entrance, the device is not in552   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 mismatch556   errors and other errors quite often require reset to return to known557   state. Also, advanced error handling is necessary to support features558   like NCQ and hotplug.559 560-  ATA errors are directly handled in the interrupt handler and PIO561   errors in pio_task. This is problematic for advanced error handling562   for the following reasons.563 564   First, advanced error handling often requires context and internal qc565   execution.566 567   Second, even a simple failure (say, CRC error) needs information568   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 drivers573   difficult. Low level drivers override libata callbacks. If EH is574   scattered over several places, each affected callbacks should perform575   its part of error handling. This can be error prone and painful.576 577libata Library578==============579 580.. kernel-doc:: drivers/ata/libata-core.c581   :export:582 583libata Core Internals584=====================585 586.. kernel-doc:: drivers/ata/libata-core.c587   :internal:588 589.. kernel-doc:: drivers/ata/libata-eh.c590 591libata SCSI translation/emulation592=================================593 594.. kernel-doc:: drivers/ata/libata-scsi.c595   :export:596 597.. kernel-doc:: drivers/ata/libata-scsi.c598   :internal:599 600ATA errors and exceptions601=========================602 603This chapter tries to identify what error/exception conditions exist for604ATA/ATAPI devices and describe how they should be handled in605implementation-neutral way.606 607The term 'error' is used to describe conditions where either an explicit608error condition is reported from device or a command has timed out.609 610The term 'exception' is either used to describe exceptional conditions611which are not errors (say, power or hotplug events), or to describe both612errors and non-error exceptional conditions. Where explicit distinction613between error and exception is necessary, the term 'non-error exception'614is used.615 616Exception categories617--------------------618 619Exceptions are described primarily with respect to legacy taskfile + bus620master IDE interface. If a controller provides other better mechanism621for error reporting, mapping those into categories described below622shouldn't be difficult.623 624In the following sections, two recovery actions - reset and625reconfiguring transport - are mentioned. These are described further in626`EH recovery actions <#exrec>`__.627 628HSM violation629~~~~~~~~~~~~~630 631This error is indicated when STATUS value doesn't match HSM requirement632during issuing or execution any ATA/ATAPI command.633 634-  ATA_STATUS doesn't contain !BSY && DRDY && !DRQ while trying to635   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 CDB642   is transferred. ATA/ATAPI standard states that "The device shall not643   terminate the PACKET command with an error before the last byte of644   the command packet has been written" in the error outputs description645   of PACKET command and the state diagram doesn't include such646   transitions.647 648In these cases, HSM is violated and not much information regarding the649error can be acquired from STATUS or ERROR register. IOW, this error can650be 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 as654transmission 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 indicating660device problems. For this type of errors, STATUS and ERROR register661values are valid and describe error condition. Note that some of ATA bus662errors are detected by ATA/ATAPI devices and reported using the same663mechanism as device errors. Those cases are described later in this664section.665 666For ATA commands, this type of errors are indicated by !BSY && ERR667during command execution and on completion.668 669For ATAPI commands,670 671-  !BSY && ERR && ABRT right after issuing PACKET indicates that PACKET672   command is not supported and falls in this category.673 674-  !BSY && ERR(==CHK) && !ABRT after the last byte of CDB is transferred675   indicates CHECK CONDITION and doesn't fall in this category.676 677-  !BSY && ERR(==CHK) && ABRT after the last byte of CDB is transferred678   \*probably\* indicates CHECK CONDITION and doesn't fall in this679   category.680 681Of errors detected as above, the following are not ATA/ATAPI device682errors but ATA bus errors and should be handled according to683`ATA bus error <#excatATAbusErr>`__.684 685CRC error during data transfer686    This is indicated by ICRC bit in the ERROR register and means that687    corruption occurred during data transfer. Up to ATA/ATAPI-7, the688    standard specifies that this bit is only applicable to UDMA689    transfers but ATA/ATAPI-8 draft revision 1f says that the bit may be690    applicable to multiword DMA and PIO.691 692ABRT error during data transfer or on completion693    Up to ATA/ATAPI-7, the standard specifies that ABRT could be set on694    ICRC errors and on cases where a device is not able to complete a695    command. Combined with the fact that MWDMA and PIO transfer errors696    aren't allowed to use ICRC bit up to ATA/ATAPI-7, it seems to imply697    that ABRT bit alone could indicate transfer errors.698 699    However, ATA/ATAPI-8 draft revision 1f removes the part that ICRC700    errors can turn on ABRT. So, this is kind of gray area. Some701    heuristics are needed here.702 703ATA/ATAPI device errors can be further categorized as follows.704 705Media errors706    This is indicated by UNC bit in the ERROR register. ATA devices707    reports UNC error only after certain number of retries cannot708    recover the data, so there's nothing much else to do other than709    notifying upper layer.710 711    READ and WRITE commands report CHS or LBA of the first failed sector712    but ATA/ATAPI standard specifies that the amount of transferred data713    on error completion is indeterminate, so we cannot assume that714    sectors preceding the failed sector have been transferred and thus715    cannot complete those sectors successfully as SCSI does.716 717Media changed / media change requested error718    <<TODO: fill here>>719 720Address error721    This is indicated by IDNF bit in the ERROR register. Report to upper722    layer.723 724Other errors725    This can be invalid command or parameter indicated by ABRT ERROR bit726    or some other error condition. Note that ABRT bit can indicate a lot727    of things including ICRC and Address errors. Heuristics needed.728 729Depending on commands, not all STATUS/ERROR bits are applicable. These730non-applicable bits are marked with "na" in the output descriptions but731up 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/A735        A keyword the indicates a field has no defined value in this736        standard and should not be checked by the host or device. N/A737        fields should be cleared to zero.738 739So, it seems reasonable to assume that "na" bits are cleared to zero by740devices and thus need no explicit masking.741 742ATAPI device CHECK CONDITION743~~~~~~~~~~~~~~~~~~~~~~~~~~~~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 a747PACKET command. For this kind of errors, sense data should be acquired748to gather information regarding the errors. REQUEST SENSE packet command749should be used to acquire sense data.750 751Once sense data is acquired, this type of errors can be handled752similarly to other SCSI errors. Note that sense data may indicate ATA753bus error (e.g. Sense Key 04h HARDWARE ERROR && ASC/ASCQ 47h/00h SCSI754PARITY ERROR). In such cases, the error should be considered as an ATA755bus 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 NCQ761command phase (one or more NCQ commands outstanding). Although STATUS762and ERROR registers will contain valid values describing the error, READ763LOG EXT is required to clear the error condition, determine which764command has failed and acquire more information.765 766READ LOG EXT Log Page 10h reports which tag has failed and taskfile767register values describing the error. With this information the failed768command can be handled as a normal ATA command error as in769`ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION) <#excatDevErr>`__770and all other in-flight commands must be retried. Note that this retry771should not be counted - it's likely that commands retried this way would772have completed normally if it were not for the failed command.773 774Note that ATA bus errors can be reported as ATA device NCQ errors. This775should be handled as described in `ATA bus error <#excatATAbusErr>`__.776 777If READ LOG EXT Log Page 10h fails or reports NQ, we're thoroughly778screwed. This condition should be treated according to779`HSM violation <#excatHSMviolation>`__.780 781ATA bus error782~~~~~~~~~~~~~783 784ATA bus error means that data corruption occurred during transmission785over ATA bus (SATA or PATA). This type of errors can be indicated by786 787-  ICRC or ABRT error as described in788   `ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION) <#excatDevErr>`__.789 790-  Controller-specific error completion with error information791   indicating transmission error.792 793-  On some controllers, command timeout. In this case, there may be a794   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 of799symptoms 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 to801transmission error or not; therefore, it's necessary to employ some kind802of heuristic when dealing with errors and timeouts. For example,803encountering repetitive ABRT errors for known supported command is804likely 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 may808alleviate the problem. See `Reconfigure transport <#exrecReconf>`__ for809more information.810 811PCI bus error812~~~~~~~~~~~~~813 814Data corruption or other failures during transmission over PCI (or other815system bus). For standard BMDMA, this is indicated by Error bit in the816BMDMA Status register. This type of errors must be logged as it817indicates something is very wrong with the system. Resetting host818controller is recommended.819 820Late completion821~~~~~~~~~~~~~~~822 823This occurs when timeout occurs and the timeout handler finds out that824the timed out command has completed successfully or with error. This is825usually 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 the832host and device are in unknown state. When this occurs, HSM could be in833any valid or invalid state. To bring the device to known state and make834it forget about the timed out command, resetting is necessary. The timed835out command may be retried.836 837Timeouts can also be caused by transmission errors. Refer to838`ATA bus error <#excatATAbusErr>`__ for more details.839 840Hotplug and power management exceptions841~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~842 843<<TODO: fill here>>844 845EH recovery actions846-------------------847 848This section discusses several important recovery actions.849 850Clearing error condition851~~~~~~~~~~~~~~~~~~~~~~~~852 853Many controllers require its error registers to be cleared by error854handler. Different controllers may have different requirements.855 856For SATA, it's strongly recommended to clear at least SError register857during error handling.858 859Reset860~~~~~861 862During EH, resetting is necessary in the following cases.863 864-  HSM is in unknown or invalid state865 866-  HBA is in unknown or invalid state867 868-  EH needs to make HBA/device forget about in-flight commands869 870-  HBA/device behaves weirdly871 872Resetting during EH might be a good idea regardless of error condition873to improve EH robustness. Whether to reset both or either one of HBA and874device 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 in877   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 to882taskfile/BMDMA PCI IDE, stopping active DMA transaction may be883sufficient iff BMDMA state is the only HBA context. But even mostly884taskfile/BMDMA PCI IDE complying controllers may have implementation885specific requirements and mechanism to reset themselves. This must be886addressed by specific drivers.887 888OTOH, ATA/ATAPI standard describes in detail ways to reset ATA/ATAPI889devices.890 891PATA hardware reset892    This is hardware initiated device reset signalled with asserted PATA893    RESET- signal. There is no standard way to initiate hardware reset894    from software although some hardware provides registers that allow895    driver to directly tweak the RESET- signal.896 897Software reset898    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 require900    controller-specific support as the second Register FIS to clear SRST901    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 command905    Although ATA/ATAPI standard doesn't describe exactly, EDD implies906    some level of resetting, possibly similar level with software reset.907    Host-side EDD protocol can be handled with normal command processing908    and most SATA controllers should be able to handle EDD's just like909    other commands. As in software reset, EDD affects both devices on a910    PATA bus.911 912    Although EDD does reset devices, this doesn't suit error handling as913    EDD cannot be issued while BSY is set and it's unclear how it will914    act when device is in unknown/weird state.915 916ATAPI DEVICE RESET command917    This is very similar to software reset except that reset can be918    restricted to the selected device without affecting the other device919    sharing the cable.920 921SATA phy reset922    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 done924    with the standard SCR Control register. As such, it's usually easier925    to implement than software reset.926 927One more thing to consider when resetting devices is that resetting928clears certain configuration parameters and they need to be set to their929previous 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 setting936 937-  Block count set with SET MULTIPLE MODE938 939-  Other parameters (SET MAX, MEDIA LOCK...)940 941ATA/ATAPI standard specifies that some parameters must be maintained942across hardware or software reset, but doesn't strictly specify all of943them. Always reconfiguring needed parameters after reset is required for944robustness. Note that this also applies when resuming from deep sleep945(power-off).946 947Also, ATA/ATAPI standard requires that IDENTIFY DEVICE / IDENTIFY PACKET948DEVICE is issued after any configuration parameter is updated or a949hardware reset and the result used for further operation. OS driver is950required to implement revalidation mechanism to support this.951 952Reconfigure transport953~~~~~~~~~~~~~~~~~~~~~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 transmission957error 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 continue968 969ata_piix Internals970===================971 972.. kernel-doc:: drivers/ata/ata_piix.c973   :internal:974 975sata_sil Internals976===================977 978.. kernel-doc:: drivers/ata/sata_sil.c979   :internal:980 981Thanks982======983 984The bulk of the ATA knowledge comes thanks to long conversations with985Andre Hedrick (www.linux-ide.org), and long hours pondering the ATA and986SCSI 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 all992the early probing was based on extensive study of Hale Landis's993probe/reset code in his ATADRVR driver (www.ata-atapi.com).994