\chapter{Introduction}
\label{sec:intro}

When a design progresses from simulation to hardware implementation, a user's
control and understanding of the system's current state drops dramatically.
To help bring up and debug low level software and hardware,
it is critical to have good debugging support built into the hardware.
When a robust OS is running on a core, software can handle many
debugging tasks. However, in many scenarios, hardware support is essential.

This document outlines a standard architecture for debug support
on RISC-V hardware platforms. This architecture allows a variety of implementations and
tradeoffs, which is complementary to the wide range of RISC-V implementations.
At the same time, this specification defines common interfaces to
allow debugging tools and components to target a variety of hardware
platforms based on the RISC-V ISA.

System designers may choose to add additional hardware debug support,
but this specification defines a standard interface for common
functionality.

\section{Terminology}

\begin{description}[style=nextline]
    \item[advanced feature]
        An advanced feature for advanced users. Most users will not be able to
        take advantage of it.
    \item[AMO]
        Atomic Memory Operation.
    \item[BYPASS]
        JTAG instruction that selects a single bit data register, also called BYPASS.
    \item[component]
        A RISC-V core, or other part of a hardware platform.
        Typically all components will be connected to a single system
        bus.
    \item[CSR]
        Control and Status Register.
    \item[DM]
        Debug Module (see Chapter \ref{chap:dm}).
    \item[DMI]
        Debug Module Interface (see Section \ref{dmi}).
    \item[DR]
        JTAG Data Register.
    \item[DTM]
        Debug Transport Module (see Section \ref{dtm}).
    \item[DXLEN]
        Debug XLEN, which is the widest XLEN a hart supports, ignoring the
        current value of \Fmxl in \Rmisa.
    \item[essential feature]
        An essential feature must be present in order for debug to work correctly.
    \item[GPR]
        General Purpose Register.
    \item[hardware platform]
        A single system consisting of one or more \emph{components}.
    \item[hart]
        A hardware thread in a RISC-V core.
    \item[IDCODE]
        32-bit Identification CODE, and a JTAG instruction that returns the IDCODE value.
    \item[IR]
        JTAG Instruction Register.
    \item[JTAG]
        Refers to work done by IEEE's Joint Test Action Group, described in
        IEEE 1149.1.
    \item[legacy feature]
        A legacy feature should only be implemented to support legacy hardware
        that is present in a system.
    \item[Minimal RISC-V Debug Specification]
        A subset of the full Debug Specification that allows for very small
        implementations. See Chapter~\ref{chap:dm}.
    \item[MR]
        Message Register, described in Section~\ref{sec:mr}.
    \item[NAPOT]
        Naturally Aligned Power-Of-Two.
    \item[NMI]
        Non-Maskable Interrupt.
    \item[physical address]
        An address that is directly usable on the system bus.
    \item[recommended feature]
        A recommended feature is not required for debug to work correctly, but
        it is so useful that it should not be omitted without good reason.
    \item[SBA]
        System Bus Access (see Section \ref{systembusaccess}).
    \item[specialized feature]
        A specialized feature, that only makes sense in the context of some
        specific hardware.
    \item[TAP]
        Test Access Port, defined in IEEE 1149.1.
    \item[TM]
        Trigger Module (see Section \ref{sec:trigger}).
    \item[virtual address]
        An address as a hart sees it. If the hart is using address translation this
        may be different from the physical address. If there is no
        translation then it will be the same.
    \item[\Rxepc]
        The exception program counter CSR (e.g. \Rmepc) that is appropriate for
        the mode being trapped to.
\end{description}

\section{Context}

This document is written to work with all RISC-V ISA extensions ratified
through 2021.

\subsection{Versions}

Version 0.13 of this document was ratified by the RISC-V Foundation's board.
Versions 0.13.$x$ are bug fix releases to that ratified specification.

Version 0.14 was a working version that was never officially ratified.

Version 1.0 is almost entirely forwards and backwards compatible with Version 0.13.

\newcommand{\PR}[1]{\href{https://github.com/riscv/riscv-debug-spec/pull/#1}{\##1}}

\subsubsection{Bugfixes from 0.13 to 1.0}

\begin{steps}{Changes that fix a bug in the spec:}
    \item Fix order of operations described in \RdmSbdataZero. \PR{392}
    \item Resume ack is set after resume, in Section~\ref{runcontrol}. \PR{400}
    \item \FcsrTextraThirtytwoSselect applies to \FcsrTextraThirtytwoSvalue. \PR{402}
    \item \FcsrTcontrolMte only applies when action=0. \PR{411}
    \item \FacAccessmemoryAamsize does not affect Argument Width. \PR{420}
    \item Clarify that harts halt out of reset if \FdmDmcontrolHaltreq=1. \PR{419}
\end{steps}

\subsubsection{Incompatible Changes from 0.13 to 1.0}

\begin{steps}{Changes that are not backwards-compatible. Debuggers or
hardware implementations that implement 0.13 will have to change something in
order to implement 1.0:}
    \item Make haltsum0 optional if there is only one hart. \PR{505}
    \item System bus autoincrement only happens if an access actually
    takes place. (\RdmSbdataZero) \PR{507}
    \item Bump \FdmDmstatusVersion to 3. \PR{512}
    \item Require debugger to poll \FdmDmcontrolDmactive after lowering it. \PR{566}
    \item Add \FcsrIcountPending to \RcsrIcount. \PR{574}
    \item When a selected trigger is disabled, \RcsrTdataTwo and \RcsrTdataThree
    can be written with any value supported by any of the types this trigger
    supports. \PR{721}
    \item \RcsrTcontrol fields only apply to breakpoint traps, not any trap. \PR{723}
    \item If \FcsrTinfoVersion is greater than 0, then \FcsrMcontrolSixHitZero
        (previously called \RcsrMcontrolSix.$|hit|$) now contains 0 when a trigger
        fires more than one instruction after the instruction that matched.  (This
        information is now reflected in \FcsrMcontrolSixHitOne.) \PR{795}
    \item If \FcsrTinfoVersion is greater than 0, then bit 20 of
        \RcsrMcontrolSix is no longer used for timing information. (Previously
        the bit was called \RcsrMcontrolSix.$|timing|$.) \PR{807}
    \item If \FcsrTinfoVersion is greater than 0, then the encodings of
        \FcsrMcontrolSixSize for sizes greater than 64 bit have changed. \PR{807}
\end{steps}

\subsubsection{Minor Changes from 0.13 to 1.0}

\begin{steps}{Changes that slightly modify defined behavior. Technically backwards
incompatible, but unlikely to be noticeable:}
    \item \FcsrDcsrStopcount only applies to hart-local counters. \PR{405}
    \item \FdmDmstatusVersion may be invalid when \FdmDmcontrolDmactive=0. \PR{414}
    \item Address triggers (\RcsrMcontrol) may fire on any accessed address. \PR{421}
    \item All trigger registers (Section~\ref{csrTrigger}) are optional. \PR{431}
    \item When extending IR, \RdtmBypass still is all ones. \PR{437}
    \item \FcsrDcsrEbreaks and \FcsrDcsrEbreaku are WARL. \PR{458}
    \item NMIs are disabled by \FcsrDcsrStepie. \PR{465}
    \item R/W1C fields should be cleared by writing every bit high. \PR{472}
    \item Specify trigger priorities in Table~\ref{tab:priority} relative to exceptions. \PR{478}
    \item Time may pass before \FdmDmcontrolDmactive becomes high. \PR{500}
    \item Clear MPRV when resuming into lower privilege mode. \PR{503}
    \item Halt state may not be preserved across reset. \PR{504}
    \item Hardware should clear trigger action when \FcsrTdataOneDmode is
        cleared and action is 1. \PR{501}
    \item Change quick access exceptions to halt the target in
    Section~\ref{acQuickaccess}. \PR{585}
    \item Writing 0 to \RcsrTdataOne forces a state where \RcsrTdataTwo and
        \RcsrTdataThree are writable. \PR{598}
    \item Solutions to deal with reentrancy in Section~\ref{sec:nativetrigger}
        prevent triggers from {\em matching}, not merely {\em firing}. This primarily
        affects \RcsrIcount behavior. \PR{722}
    \item Attempts to access a non-existent CSR raise an illegal instruction
        exception. \PR{791}
\end{steps}

\subsubsection{New Features from 0.13 to 1.0}

\begin{steps}{New backwards-compatible feature that did not exist before:}
    \item Add halt groups and external triggers in Section~\ref{hrgroups}. \PR{404}
    \item Reserve some DMI space for non-standard use. See \RdmCustom, and
        \RdmCustomZero through \RdmCustomFifteen. \PR{406}
    \item Reserve trigger \FcsrTdataOneType values for non-standard use. \PR{417}
    \item Add \FcsrItriggerNmi bit to \RcsrItrigger. \PR{408} and \PR{709}
    \item Recommend matching on every accessed address. \PR{449}
    \item Add resume groups in Section~\ref{hrgroups}. \PR{506}
    \item Add \FdmAbstractcsRelaxedpriv. \PR{536}
    \item Move \RcsrScontext, renaming original to \RcsrMscontext, and create
        \RcsrHcontext. \PR{535}
    \item Add \RcsrMcontrolSix, deprecating \RcsrMcontrol. \PR{538}
    \item Add hypervisor support: \FcsrDcsrEbreakvs, \FcsrDcsrEbreakvu,
        \FcsrDcsrV, \RcsrHcontext, \RcsrMcontrol, \RcsrMcontrolSix, and
        \RvirtPriv. \PR{549}
    \item Optionally make \FdmDmstatusAnyunavail and \FdmDmstatusAllunavail
    sticky, controlled by \FdmDmstatusStickyunavail. \PR{520}
    \item Add \RcsrTmexttrigger to support trigger module external trigger
        inputs. \PR{543}
    \item Describe \RcsrMcontrol and \RcsrMcontrolSix behavior with atomic instructions. \PR{561}
    \item Trigger hit bits must be set on fire, may be set on match. \PR{593}
    \item Add \FcsrTextraThirtytwoSbytemask and \FcsrTextraSixtyfourSbytemask
        to \RcsrTextraThirtytwo and \RcsrTextraSixtyfour. \PR{588}
    \item Allow debugger to request harts stay alive with keepalive bit in
        Section~\ref{keepalive}. \PR{592}
    \item Add \FdmDmstatusNdmresetpending to allow a debugger to determine
        when ndmreset is complete. \PR{594}
    \item Add \FcsrTmexttriggerIntctl to support triggers from an interrupt controller. \PR{599}
\end{steps}

\subsubsection{Incompatible Changes During 1.0 Stable}

\begin{steps}{Backwards-incompatible changes between two versions that are both
called 1.0 stable.}
\item \FcsrItriggerNmi was moved from \RcsrEtrigger to \RcsrItrigger, and is now
subject to the mode bits in that trigger.
\item DM {\tt data} registers are now Message Registers (see
Section~\ref{sec:mr}). Debuggers must not assume they can read back the same
value that they wrote, and must not assume that the result of the last abstract
command is available as argument to the next abstract command. \PR{728}
\item It may not be possible to read the contents of the Program Buffer using
the {\tt progbuf} registers. \PR{731}
\end{steps}

\section{About This Document}

\subsection{Structure}

This document contains two parts. The main part of the document is the
specification, which is given in the numbered chapters. The second part
of the document is a set of appendices. The information
in the appendices is intended to clarify and provide examples, but is
not part of the actual specification.

\subsection{ISA vs. non-ISA}

This specification contains both ISA and non-ISA parts. The ISA parts define
self-contained ISA extensions. The other parts of the document describe the
non-ISA external debug extension.
Chapters whose contents are solely one or the other are labeled as such in their
title. Chapters without such a label apply to both ISA and non-ISA.

\subsection{Register Definition Format}

All register definitions in this document follow the format shown below.  A
simple graphic shows which fields are in the register. The upper and lower bit
indices are shown to the top left and top right of each field. The total number
of bits in the field are shown below it.

After the graphic follows a table which for each field lists its name,
description, allowed accesses, and reset value. The allowed accesses are listed
in Table~\ref{tab:access}. The reset value is either a constant or ``Preset.''
The latter means it is an implementation-specific legal value.

Parts of the register which are currently unused are labeled with the number 0.
Software must only write 0 to those fields, and ignore their value while
reading. Hardware must return 0 when those fields are read, and ignore the
value written to them.

\begin{commentary}
This behavior enables us to use those fields later without having to increase
the values in the version fields.
\end{commentary}

Names of registers and their fields are hyperlinks to their definition, and are
also listed in the index on page \pageref{index}.

\input{sample_registers.tex}

\begin{table}[htp]
    \centering
    \caption{Register Access Abbreviations}
    \label{tab:access}
    \begin{tabulary}{\textwidth}{|l|L|}
        \hline
        R & Read-only. \\
        \hline
        R/W & Read/Write. \\
        \hline
        R/W1C & Read/Write Ones to Clear. Writing 0 to every bit has no effect.
        Writing 1 to every bit clears the field. The result of other writes is
        undefined. \\
        \hline
        WARZ & Write any, read zero. A debugger may write any value. When read
        this field returns 0. \\
        \hline
        W1 & Write-only. Only writing 1 has an effect. When read the returned
        value should be 0. \\
        \hline
        WARL & Write any, read legal. A debugger may write any value. If a
        value is unsupported, the implementation converts the value to one that
        is supported. \\
        \hline
    \end{tabulary}
\end{table}

%\input{reading_order.tex}

\section{Background}

There are several use cases for dedicated debugging hardware, both
internal to a CPU core and with an external connection.
This specification addresses the use cases listed below. Implementations
can choose not to implement every feature, which means some use cases might
not be supported.

\begin{itemize}

\item Debugging low-level software in the absence of an OS or other software.

\item Debugging issues in the OS itself.

\item Bootstrapping a hardware platform to test, configure, and program components before
  there is any executable code path in the hardware platform.

\item Accessing hardware on a hardware platform without a working CPU.

\end{itemize}

In addition, even without a hardware debugging interface,
architectural support in a RISC-V CPU can aid software debugging and
performance analysis by allowing hardware triggers and breakpoints.

\section{Supported Features}

The debug interface described in this specification supports the following features:

\begin{enumerate}
   \item All hart registers (including CSRs) can be read/written.
   \item Memory can be accessed either from the hart's point of view, through
       the system bus directly, or both.
   \item RV32, RV64, and future RV128 are all supported.
   \item Any hart in the hardware platform can be independently debugged.
   \item A debugger can discover almost\footnote{Notable exceptions include
       information about the memory map and peripherals.} everything it needs
       to know itself, without user configuration.
   \item Each hart can be debugged from the very first instruction executed.
   \item A RISC-V hart can be halted when a software breakpoint instruction is
       executed.
   \item Hardware single-step can execute one instruction at a time.
   \item Debug functionality is independent of the debug transport used.
   \item The debugger does not need to know anything about the microarchitecture
       of the harts it is debugging.

   \item Arbitrary subsets of harts can be halted and resumed simultaneously.
       (Optional)
   \item Arbitrary instructions can be executed on
       a halted hart. That means no new debug functionality is needed when a
       core has additional or custom instructions or state, as
       long as there exist programs
       that can move that state into GPRs. (Optional)
   \item Registers can be accessed without halting. (Optional)
   \item A running hart can be directed to execute a short sequence
       of instructions, with little overhead. (Optional)
   \item A system bus manager allows memory access without
       involving any hart. (Optional)
   \item A RISC-V hart can be halted when a trigger matches the PC,
       read/write address/data, or an instruction opcode. (Optional)
    \item Harts can be grouped, and harts in the same group will all halt when
        any of them halts. These groups can also react to or notify external
        triggers. (Optional)
\end{enumerate}

This document does not suggest a strategy or implementation for hardware test,
debugging or error detection techniques. Scan, built-in self test (BIST), etc. are out of scope of
this specification, but this specification does not intend to limit their use
in RISC-V systems.

It is possible to debug code that uses software threads, but there is no
special debug support for it.
