\chapter{Debug Module (DM)} \label{dm}

\begin{steps}{The Debug Module implements a translation interface between abstract debug
    operations and their specific implementation. It might support the following
    operations:}
\item Give the debugger necessary information about the implementation. (Required)
\item Allow any individual hart to be halted and resumed. (Required)
\item Provide status on which harts are halted. (Required)
\item Provide abstract read and write access to a halted hart's GPRs. (Required)
\item Provide access to a reset signal that allows debugging from the very
    first instruction after reset. (Required)
\item Provide a mechanism to allow debugging harts immediately out of reset
      (regardless of the reset cause). (Optional)
\item Provide abstract access to non-GPR hart registers. (Optional)
\item Provide a Program Buffer to force the hart to execute arbitrary instructions. (Optional)
\item Allow multiple harts to be halted, resumed, and/or reset at the same time. (Optional)
\item Allow memory access from a hart's point of view. (Optional)
\item Allow direct System Bus Access. (Optional)
\item Group harts. When any hart in the group halts, they all halt. (Optional)
\item Respond to external triggers by halting each hart in a configured group. (Optional)
\item Signal an external trigger when a hart in a group halts. (Optional)
\end{steps}

\begin{steps}{In order to be compliant with this specification an
    implementation must:}
\item Implement all the required features listed above.
\item Implement at least one of Program Buffer, System Bus Access, or Abstract
    Access Memory command mechanisms.
\item
    \begin{steps}{Do at least one of:}
        \item Implement the Program Buffer.
        \item Implement abstract access to all registers that are visible to
            software running on the hart including all the registers that are
            present on the hart and listed in Table~\ref{tab:regno}.
        \item Implement abstract access to at least all GPRs, \RcsrDcsr, and
            \RcsrDpc, and advertise the implementation as conforming to the
            ``Minimal RISC-V Debug Specification \versionnum'', instead of the
            ``RISC-V Debug Specification \versionnum''.
    \end{steps}
\end{steps}

A single DM can debug up to $2^{20}$ harts.

\section{Debug Module Interface (DMI)} \label{dmi}

Debug Modules are slaves to a bus called the Debug Module Interface (DMI). The
master of the bus is the Debug Transport Module(s).
The Debug Module Interface can be a trivial bus with one master and one slave,
or use a more full-featured bus like TileLink or the AMBA Advanced Peripheral
Bus. The details are left to the system designer.

The DMI uses between 7 and 32 address bits.  It supports read and write
operations.  The bottom of the address space is
used for the first (and usually only) DM. Extra space can be used for custom
debug devices, other cores, additional DMs, etc. If there are additional DMs
on this DMI, the base address of the next DM in the DMI address space is given
in \RdmNextdm.

The Debug Module is controlled via register accesses to its DMI address space.

\section{Reset Control} \label{reset}

There are two methods that allow a debugger to reset harts.
\FdmDmcontrolNdmreset resets all the harts in the system, as well as all other
parts of the system except for the Debug Modules, Debug Transport Modules,
and Debug Module Interface.
Exactly what is affected by this reset is implementation dependent, but it
must be possible to debug programs from the first instruction executed.
\FdmDmcontrolHartreset resets all the currently selected harts. In this case an
implementation may reset more harts than just the ones that are selected. The
debugger can discover which other harts are reset (if any) by selecting them
and checking \FdmDmstatusAnyhavereset and \FdmDmstatusAllhavereset.

To perform either of these resets, the debugger first asserts the bit, and then
clears it. The actual reset may start as soon as the bit is asserted, but may
start an arbitrarily long time after the bit is deasserted. The reset itself
may also take an arbitrarily long time.  While the reset is
on-going, harts are either in the running state, indicating it's possible to
perform some abstract commands during this time, or in the unavailable state,
indicating it's not possible to perform any abstract commands during this time.
Once a hart's reset is complete, {\tt havereset} becomes set.  When a hart comes out
of reset and \FdmDmcontrolHaltreq or \Fresethaltreq are set, the hart will
immediately enter Debug Mode (halted state). Otherwise it will execute normally
(running state).

\begin{commentary}
    There is no general, reliable way for the debugger to know when reset has
    actually begun.
\end{commentary}

The halt state of harts should be
maintained across system reset provided that \FdmDmcontrolDmactive is 1,
although trigger CSRs may be cleared.

The Debug Module's own state and registers should only be
reset at power-up and while
\FdmDmcontrolDmactive in \RdmDmcontrol is 0. If there is another mechanism to
reset the DM, this mechanism must also reset all the harts accessible to the
DM.

Due to clock and power domain crossing issues,
it may not be possible to perform arbitrary DMI accesses across
system reset.
While \FdmDmcontrolNdmreset or any external reset is asserted, the only supported DM
operations are reading and writing \RdmDmcontrol. The behavior of other accesses
is undefined.

When harts have been reset, they must set a sticky {\tt havereset} state bit.
The conceptual {\tt havereset} state bits can be read for selected harts in
\FdmDmstatusAnyhavereset and \FdmDmstatusAllhavereset in \RdmDmstatus.
These bits must be set regardless of the cause of the reset.
The {\tt havereset} bits for the selected harts
can be cleared by writing 1 to \FdmDmcontrolAckhavereset in \RdmDmcontrol.
The {\tt havereset} bits may or may not be cleared
when \FdmDmcontrolDmactive is low.

\section{Selecting Harts} \label{selectingharts}

Up to $2^{20}$ harts can be connected to a single DM. The debugger
selects a hart, and then subsequent halt, resume, reset, and debugging
commands are specific to that hart.

To enumerate all the harts, a debugger must first determine {\tt HARTSELLEN}
by writing  all ones to \Fhartsel (assuming the maximum size) and reading back
the value to see which bits were actually set.  Then it selects each hart
starting from 0 until either \FdmDmstatusAnynonexistent in \RdmDmstatus is 1, or the
highest index (depending on {\tt HARTSELLEN}) is reached.

The debugger can discover the mapping between hart indices and
\Rmhartid by using the interface to read \Rmhartid, or by
reading the system's configuration string.

\subsection {Selecting a Single Hart}

All debug modules must support selecting a single hart.
The debugger can select a hart by writing its index to \Fhartsel.
Hart indexes start at 0 and are contiguous until the final index.

\subsection {Selecting Multiple Harts} \label{hartarraymask}

Debug Modules may implement a Hart Array Mask register to allow selecting
multiple harts at once. The $n$th bit in the Hart Array Mask register applies to
the hart with index $n$. If the bit is 1 then the hart is selected.  Usually a DM
will have a Hart Array Mask register exactly wide enough to select all the
harts it supports, but it's allowed to tie any of these bits to 0.

The debugger can set bits in the hart array mask register using \RdmHawindowsel
and \RdmHawindow, then apply actions to all selected harts by setting \FdmDmcontrolHasel. If
this feature is supported, multiple harts can be halted, resumed, and reset
simultaneously. The state of the hart array mask register is not affected by
setting or clearing \FdmDmcontrolHasel.

Only the actions initiated by \RdmDmcontrol can apply to multiple harts
at once, Abstract Commands apply only to the hart selected by
\Fhartsel.

\section{Hart DM States}

Every hart that can be selected is in exactly one of the following four DM states:
non-existent, unavailable, running, or halted. Which state
the selected harts are in is reflected by \FdmDmstatusAllnonexistent,
\FdmDmstatusAnynonexistent, \FdmDmstatusAllunavail, \FdmDmstatusAnyunavail,
\FdmDmstatusAllrunning, \FdmDmstatusAnyrunning, \FdmDmstatusAllhalted, and
\FdmDmstatusAnyhalted.

Harts are nonexistent if they will never be part of this system, no matter how
long a user waits. E.g.\ in a simple single-hart system only one hart exists,
and all others are nonexistent. Debuggers may assume that a system has no harts
with indexes higher than the first nonexistent one.

Harts are unavailable if they might exist/become available at a later time, or
if there are other harts with higher indexes than this one. Harts may be
unavailable for a variety of reasons including being reset, temporarily powered
down, and not being plugged into the system.
Systems with very large number of harts may
permanently disable some during manufacturing, leaving holes in the otherwise
continuous hart index space. In order to let the debugger discover all harts,
they must show up as unavailable even if there is no chance of them ever
becoming available.

Harts are running when they are executing normally, as if no debugger was
attached. This includes being in a low power mode or waiting for an interrupt,
as long as a halt request will result in the hart being halted.

Harts are halted when they are in Debug Mode, only performing tasks on behalf
of the debugger.

Which states a hart that is reset goes through is implementation dependent.
Harts may be unavailable while reset is asserted, and some time after reset is
deasserted. They might transition to running for some time after reset is
deasserted. Finally they end up either running or halted, depending on
\FdmDmcontrolHaltreq and \Fresethaltreq.

\section{Run Control} \label{runcontrol}

For every hart, the Debug Module tracks 4 conceptual bits of state: halt
request, resume ack, halt-on-reset request,  and hart reset.
(The hart reset and halt-on-reset request bits are optional.)
These 4 bits reset to 0, except for resume ack, which may reset to either 0 or 1.
The DM receives halted, running, and havereset signals from each hart.
The debugger can observe the state of resume ack in \FdmDmstatusAllresumeack and
\FdmDmstatusAnyresumeack, and the state of halted, running, and havereset signals
in \FdmDmstatusAllhalted, \FdmDmstatusAnyhalted, \FdmDmstatusAllrunning, \FdmDmstatusAnyrunning, \FdmDmstatusAllhavereset,
and \FdmDmstatusAnyhavereset. The state of the other bits cannot be observed directly.

When a debugger writes 1 to \FdmDmcontrolHaltreq, each selected hart's halt request bit is
set.
When a running hart, or a hart just coming out of reset, sees its halt request
bit high, it responds by halting, deasserting its running signal, and asserting
its halted signal.
Halted harts ignore their halt request bit.

When a debugger writes 1 to \FdmDmcontrolResumereq, each selected hart's resume ack bit is
cleared and each selected, halted hart is sent a resume request. Harts respond
by resuming, clearing their halted signal, and asserting their running signal.
At the end of this process the resume ack bit is set.  These
status signals of all selected harts are reflected in \FdmDmstatusAllresumeack,
\FdmDmstatusAnyresumeack, \FdmDmstatusAllrunning, and \FdmDmstatusAnyrunning. Resume requests are ignored by
running harts.

When halt or resume is requested, a hart must respond in
less than one second, unless it is unavailable.
(How this is implemented is not further specified. A few
clock cycles will be a more typical latency).

The DM can implement optional halt-on-reset bits for each hart,
which it indicates by setting \FdmDmstatusHasresethaltreq to 1.
This means the DM implements the \FdmDmcontrolSetresethaltreq and \FdmDmcontrolClrresethaltreq bits.
Writing 1 to \FdmDmcontrolSetresethaltreq sets the halt-on-reset request bit for each
selected hart.
When a hart's halt-on-reset request bit is set, the hart will immediately enter
debug mode on the next deassertion of its reset. This is true regardless of
the reset's cause.
The hart's halt-on-reset request bit remains set
until cleared by the debugger writing 1 to \FdmDmcontrolClrresethaltreq
while the hart is selected, or by DM reset.

\section{Halt Groups and External Triggers}

An optional feature allows a debugger to create halt groups. When any hart in a
halt group halts all the other harts in that group will quickly halt, even if
they are currently in the process of resuming. Adding a hart to a halt group
does not automatically halt that hart, even if other harts in the group are
already halted.

It is also possible to add external triggers to a halt group. External triggers
are abstract concepts that can signal the DM and/or receive signals from the
DM.  When an external trigger fires, all harts in its halt group are quickly
halted. When a hart in a halt group halts, the external triggers in the same
halt group are notified.

\begin{commentary}
    External triggers could be used to implement near simultaneous halting of
    all cores in a system, when not all cores are RISC-V cores.
\end{commentary}

Halt group 0 is special, and has none of this behavior. Harts in halt group 0
halt as if halt groups aren't implemented at all.

To near simultaneously resume all harts in a group, the debugger can select all
the harts, and write 1 to \FdmDmcontrolResumereq as described above. An implementation
must guarantee that all harts in the group halt again as soon as one of them
halts, even if that hart halts before all harts have resumed.

\section{Abstract Commands} \label{abstractcommands}

The DM supports a set of abstract commands, most of which
are optional. Depending on the implementation, the debugger may
be able to perform
some abstract commands even when the selected hart is not halted.
Debuggers can only determine which abstract commands
are supported by a given hart in a given state (running, halted, or held in reset) by attempting them
and then looking at \FdmAbstractcsCmderr in \RdmAbstractcs to see if they were successful.
Commands may be supported with some options set, but not with other options
set. If a command has unsupported options set or if bits that are defined as 0
aren't 0, then the DM must set \FdmAbstractcsCmderr to 2 (not supported).

\begin{commentary}
    Example: Every system must support the Access Register command, but may not
    support accessing CSRs. If the debugger requests to read a CSR in that
    case, the command will return ``not supported.''
\end{commentary}

Debuggers execute abstract commands by writing them to \RdmCommand.  They
can determine whether an abstract command is complete by reading \FdmAbstractcsBusy in
\RdmAbstractcs. If the debugger starts a new command while \FdmAbstractcsBusy is set,
\FdmAbstractcsCmderr becomes 1 (busy), the currently executing command still gets to
run to completion, but any error generated by the currently executing command is lost.
After completion, \FdmAbstractcsCmderr indicates whether the command was
successful or not. Commands may fail because a hart is not halted, not running,
unavailable, or because they encounter an error during execution.

If the command takes arguments, the debugger
must write them to the {\tt data} registers before writing to \RdmCommand. If a
command returns results, the Debug Module must ensure they are placed
in the {\tt data} registers before \FdmAbstractcsBusy is cleared.
Which {\tt data} registers are used for the arguments is
described in Table~\ref{tab:datareg}.  In all cases the least-significant word
is placed in the lowest-numbered {\tt data} register. The argument width
depends on the command being executed, and is DXLEN where not explicitly
specified.

\begin{table}[htp]
    \centering
    \caption{Use of Data Registers}
    \label{tab:datareg}
    \begin{tabulary}{\textwidth}{|r|l|l|l|}
        \hline
        Argument Width & arg0/return value & arg1 & arg2 \\
        \hline
        32 & \RdmDataZero & {\tt data1} & {\tt data2} \\
        \hline
        64 & \RdmDataZero, {\tt data1} & {\tt data2}, {\tt data3} & {\tt data4}, {\tt data5} \\
        \hline
        128 & \RdmDataZero--{\tt data3} & {\tt data4}--{\tt data7} & {\tt data8}--{\tt data11} \\
        \hline
    \end{tabulary}
\end{table}

\begin{commentary}
    The Abstract Command interface is designed to allow a debugger to write
    commands as fast as possible, and then later check whether they completed
    without error.  In the common case the debugger will be much slower than
    the target and commands succeed, which allows for maximum throughput. If
    there is a failure, the interface ensures that no commands execute after
    the failing one.  To discover which command failed, the debugger has to
    look at the state of the DM (e.g.\ contents of \RdmDataZero) or hart (e.g.\ 
    contents of a register modified by a Program Buffer program) to determine
    which one failed.
\end{commentary}

Before starting an abstract command, a debugger must ensure that \FdmDmcontrolHaltreq,
\FdmDmcontrolResumereq, and \FdmDmcontrolAckhavereset are all 0.

While an abstract command is executing (\FdmAbstractcsBusy in \RdmAbstractcs is high), a
debugger must not change \Fhartsel, and must not write 1 to \FdmDmcontrolHaltreq,
\FdmDmcontrolResumereq, \FdmDmcontrolAckhavereset, \FdmDmcontrolSetresethaltreq, or \FdmDmcontrolClrresethaltreq.

If an abstract command does not complete in the expected time and appears to be
hung, the debugger can try to reset the hart (using \FdmDmcontrolHartreset or
\FdmDmcontrolNdmreset). If that doesn't clear \FdmAbstractcsBusy, then it
can try resetting the Debug Module (using \FdmDmcontrolDmactive).

If an abstract command is started while the selected hart is unavailable or if
a hart becomes unavailable while executing an abstract command, then the
Debug Module may terminate the abstract command, setting \FdmAbstractcsBusy low, and
\FdmAbstractcsCmderr to 4 (halt/resume). Alternatively, the command could just appear to be
hung (\FdmAbstractcsBusy never goes low).

\subsection{Abstract Command Listing}

This section describes each of the different abstract commands
and how their fields should be interpreted when
they are written to \RdmCommand.

Each abstract command is a 32-bit value. The top 8 bits contain \FdmCommandCmdtype which
determines the kind of command. Table~\ref{tab:cmdtype} lists all commands.

\begin{table}[htp]
    \centering
    \caption{Meaning of \FdmCommandCmdtype}
    \label{tab:cmdtype}
    \begin{tabulary}{\textwidth}{|r|l|l|l|}
        \hline
        \FdmCommandCmdtype & Command & Page \\
        \hline
        0 & Access Register Command & \pageref{acAccessregister} \\
        \hline
        1 & Quick Access & \pageref{acQuickaccess} \\
        \hline
        2 & Access Memory Command & \pageref{acAccessmemory} \\
        \hline
        3 & Feature Discovery & \pageref{feature discovery} \\
        \hline
    \end{tabulary}
\end{table}

\input{abstract_commands.tex}

\section{Feature Discovery Structure} \label{featurestructure}

The structure is encoded in a series of bytes. Where a multi-byte value is
required, those are stored with least-significant byte at the lowest address.

\index{varnum} \index{Variable Numbers} Many numbers in this structure will
usually be very small, but could be very large on unusual systems. To
accommodate this, Variable Numbers (varnums) are used. To decode a varnum, the
debugger first needs to look at the least significant bits of the first byte.
Table~\ref{tab:varnum} describes this encoding. The actual numerical value is
determined by combining the remaining bits in the first byte with between 0 and
16 additional bytes of data that follow. If there are bits remaining in the
first byte, those bits are used as the least significant bits of the number.
Then the 8 bits in each additional byte are used to fill in the next 8 least
significant bits in the number. Table~\ref{tab:varexample} contains some
examples, and Section~\ref{varnumcode} contains code to read/write varnums.

All parsers must support varnums encoding numbers up to 32 bits in size. In
addition parsers should also support varnums encoding numbers as wide as the
GPRs as well as virtual and physical addresses.

\begin{table}[htp]
    \centering
    \caption{Variable number (varnum) encoding}
    \label{tab:varnum}
    \begin{tabulary}{\textwidth}{|r|l|l|l|}
        \hline
        LSBs & Number Size & Number LSBs & Remaining data \\ \hline
        0 & 7 bits & top 7 bits of first byte & None \\ \hline
        01 & 14 bits & top 6 bits of this byte & in the next byte \\ \hline
        011 & 21 bits & top 5 bits of this byte & in the next 2 bytes \\ \hline
        0111 & 28 bits & top 4 bits of this byte & in the next 3 bytes \\ \hline
        01111 & 35 bits & top 3 bits of this byte & in the next 4 bytes \\ \hline
        00011111 & 40 bits & None & in the next 5 bytes \\ \hline
        00111111 & 48 bits & None & in the next 6 bytes \\ \hline
        01011111 & 56 bits & None & in the next 7 bytes \\ \hline
        01111111 & 64 bits & None & in the next 8 bytes \\ \hline
        10011111 & 80 bits & None & in the next 10 bytes \\ \hline
        10111111 & 96 bits & None & in the next 12 bytes \\ \hline
        11011111 & 112 bits & None & in the next 14 bytes \\ \hline
        11111111 & 128 bits & None & in the next 16 bytes \\ \hline
    \end{tabulary}
\end{table}

\begin{table}[htp]
    \centering
    \caption{Variable number (varnum) examples}
    \label{tab:varexample}
    \begin{tabulary}{\textwidth}{|l|l|}
        \hline
        Bytes (Hex) & Number \\ \hline
        54 & 42 \\ \hline
        49 13 & 1234 \\ \hline
        d7 fe 45 08 & 8675309 \\ \hline
        ff 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 &
        0x01020304050607080910111213141516 \\ \hline
    \end{tabulary}
\end{table}

The structure consists of a series of sections. Parsers don't have to support
all sections. They should skip sections of a type they do not support.

Each section consists of a header followed by a body. The header consists of 2
varnums.  The first varnum contains the size of the section including the type
and the body, in bytes.  The second varnum describes the section type. Known
section types are listed in Table~\ref{tab:sectiontype}.  A section size of 0
indicates indicates the end of the structure is reached. Marking the end of the
structure is optional if the end can be determined some other way.

\begin{commentary}
    Section type numbers are chosen such that types common on tiny
    implementations can be encoded in a single byte varnum.
\end{commentary}

\begin{table}[htp]
    \centering
    \caption{Feature discovery structure section types}
    \label{tab:sectiontype}
    \begin{tabulary}{\textwidth}{|r|l|l|}
        \hline
        Type & Name & Page \\
        \hline
        0x10 & Hart Select & \pageref{sectionHartSelect} \\ \hline
        0x29 & Magic & \pageref{sectionMagic} \\ \hline
        0x30 & Abstract Command Support & \pageref{sectionAbstractCommandSupport} \\ \hline
        0x31 & Trigger Support & \pageref{sectionTriggerSupport} \\ \hline
        0x32 & Hart Index to Hartid Map & \pageref{sectionHartMap} \\ \hline
        0x100 & Absolute Jump & \pageref{sectionJump} \\ \hline
        0x101 & Relative Jump & \pageref{sectionJump} \\ \hline
        0x102 & Absolute Include & \pageref{sectionInclude} \\ \hline
        0x103 & Relative Include & \pageref{sectionInclude} \\ \hline
        0x1000 -- 0x1fff & CSR Value & \pageref{sectionCsr} \\ \hline
    \end{tabulary}
\end{table}

\subsection{Hart Select} \label{sectionHartSelect}

This section is optional, and never needed on single-hart systems.

A parser must maintain a selected hart list. At the beginning of parsing this
defaults to including all harts in the system. As new Hart Select sections are
encountered, the list is updated accordingly. Each section applies to the harts
that are the result of cumulatively parsing all Hart Select sections that
precede it.

Hart select records consist of a type byte, and one or more varnum arguments
which refer to harts by their hart id. Note that hart id may not be the same as
hart index, which is used in much of the Debug Specification. The records are
described in Table~\ref{tab:hartselect}.

\begin{table}[htp]
    \centering
    \caption{Hart Select Record Types}
    \label{tab:hartselect}
    \begin{tabulary}{\textwidth}{|r|r|L|}
        \hline
        \makecell{Type\\Byte} & \makecell{Number of\\arguments} & Description \\
        \hline
        0 & 1 & Empty the hart list, then select just the hart specified by
        arg0. \\ \hline
        1 & 2 & Add the range of harts from arg0 to arg1 (inclusive) to the
        hart list. \\ \hline
        2 & 2 & Remove the range of harts from arg0 to arg1 (inclusive) from
        the hart list. \\ \hline
    \end{tabulary}
\end{table}

\subsection{Magic} \label{sectionMagic}

The optional magic section should be ignored by parsers. It can be used to put
in the beginning of files so that other tools can identify the file type.
Suggested verbatim sequences (including the section header) are 0x52 0x04 0x56
0x05 for a 4-byte magic sequence, and 0x52 0x0c 0x49 0x53 0x43 0x2d 0x56 0x00
for an 8-byte magic sequence. In ASCII, those look like
"R\textbackslash{}x04V\textbackslash{}x05" and
"R\textbackslash{}0x0cISC-V\textbackslash{}0".

\subsection{Abstract Command Support} \label{sectionAbstractCommandSupport}

This optional section describes which abstract commands (full register contents
of \RdmCommand) are supported for the harts currently in the selected list. If
it is present the structure must describe every implemented abstract command.
This section should exist if abstract commands are implemented.

The contents consist of a series of 32-bit words.  The words at even indices
consist of a sample supported command. The words at odd indices contain a mask
that applies to the previous sample command. A command (full contents of
\RdmCommand) C is supported if and only if there is a $|sample|/$|mask| pair in
the data structure where $(C \BitAnd |mask|) = (|sample| \BitAnd |mask|)$. See
an example in Table~\ref{tab:command_discovery}.

Because the CSR space is sparsely populated, it is allowed and recommended to
list the Access Register CSR command as supported for all CSRs even though not
every CSR exists.

\begin{table}[htp]
    \centering
    \caption{Example Feature Discovery Structure}
    \label{tab:command_discovery}
    \begin{tabulary}{\textwidth}{|l|l|L|}
        \hline
        Index: Sample & Index: Mask & Comment \\
        \hline
        0: 0x201000 & 1: 0xfff8ffe0 & 32-bit GPR access, with all combinations
        of postexec, transfer, and write \\
        \hline
        2: 0x2200000 & 3: 0xfff6ffff & 32-bit memory access, read/write with
        optional postincrement \\
        \hline
    \end{tabulary}
\end{table}

\subsection{Trigger Support} \label{sectionTriggerSupport}

This optional section describes which triggers (full contents of \RcsrTdataOne)
are supported for the harts currently in the selected list. If it is
present the structure must describe every implemented trigger. Triggers
that are not described here should be assumed not to be implemented. This
section should exist if triggers are implemented. All selected harts must have
the same DXLEN.

The data structure consists of a series of trigger records. Each record
consists of a type byte followed by data depending on the record type. The
records are described in Table~\ref{tab:triggersupport}.

\begin{table}[htp]
    \centering
    \caption{Hart Select Record Types}
    \label{tab:triggersupport}
    \begin{tabulary}{\textwidth}{|r|l|L|}
        \hline
        \makecell{Type\\Byte} & Arguments & Description \\
        \hline
        0x00 & $|id|$ & $|id|$ is a varnum. Empty the trigger list, then select
        just the trigger specified by $|id|$. \\ \hline
        0x01 & $|low|$ $|high|$ & $|low|$ and $|high|$ are varnums. Add the
        range of triggers from $|low|$ to $|high|$ (inclusive) to the trigger
        list. \\ \hline
        0x02 & $|low|$ $|high|$ & $|low|$ and $|high|$ are varnums. Remove the
        range of triggers from $|low|$ to $|high|$ (inclusive) from the trigger
        list. \\ \hline
        0x10 & $|data|$ $|mask|$ & $|data|$ and $|mask|$ are 32-bit values.
        They indicate that for the currently selected triggers, on the
        currently selected harts, every trigger T is supported if $(T \BitAnd
        |mask|) = (|sample| \BitAnd |mask|)$. This implies DXLEN is 32. \\ \hline
        0x11 & $|data|$ $|mask|$ & $|data|$ and $|mask|$ are 64-bit values.
        They indicate that for the currently selected triggers, on the
        currently selected harts, every trigger T is supported if $(T \BitAnd
        |mask|) = (|sample| \BitAnd |mask|)$. This implies DXLEN is 64. \\ \hline
    \end{tabulary}
\end{table}

\subsection{Hart Index to Hartid Map} \label{sectionHartMap}

The external debug interface uses hart indices, which may not be the same as
hart ids. To make this structure useful for an external debugger, it must know
the mapping between the two, and this section is the simplest way of doing
that.

This optional section contains the hartid of every hart in the system in hart
index order with no gaps. Each hartid consists of a single varnum.

If this section exists but does not include every hart in the system, then the
unlisted harts must have a hartid that's equal to their hart index. Simple
systems where hartids and hart indices are equal can describe this by including
this section with a size of 0.

\subsection{Jump/Include} \label{sectionJump} \label{sectionInclude}

Jump sections tell a parser to continue parsing at a different address. Include
sections tell a parser to start parsing at a different address, and when the
end of that structure is reached to resume at the next section immediately
after the Include section. Include sections require the parser to maintain a
stack of addresses to return from. Parsers must support a stack at least 2
addresses deep, and structures must never go more than 8 addresses deep.

The body of all these packets contains a single varnum, which is to be
interpreted as an address jump to or include. If the section type is relative,
then the address varnum is interpreted as a signed two's complement number that
is added to the address where the next section would start. Addresses do not
wrap.

\subsection{CSR Value} \label{sectionCsr}

These optional sections contain the value of exactly one CSR register as it
would be when the most features are enabled. It's intended for registers that
contain a lot of information about the hart like \Rmvendorid, \Rmarchid,
\Rmimpid, and \Rmisa. The size of the register (in bytes) is given by the size
of the section, while bits 11:0 of the section number encode the CSR number in
question.

This section should exist describing \Rmisa for each hart. If it does not exist
a debugger will have to halt each hart to discover XLEN.

\begin{commentary}
    While the number of CSRs whose contents are useful is small, we reserve
    space for all of them so that arbitrary extensions that describe features
    through CSRs can be described in this structure without requiring an
    explicit mention in this description.
\end{commentary}

\section{Program Buffer} \label{programbuffer}

To support executing arbitrary instructions on a halted hart,
a Debug Module can include a Program Buffer that a debugger
can write small programs to. Systems
that support all necessary functionality using abstract commands
only may choose to omit the Program Buffer.

A debugger can write a small program to the Program Buffer, and then
execute it exactly once with the Access Register Abstract Command,
setting the \FacAccessregisterPostexec bit in \RdmCommand.
The debugger can write whatever program it likes (including jumps out of the
Program Buffer), but the program must end with
{\tt ebreak} or {\tt c.ebreak}. An implementation may support
an implied {\tt ebreak} that is executed when a hart runs off the end of the
Program Buffer. This is indicated by \FdmDmstatusImpebreak. With this feature, a Program
Buffer of just 2 32-bit words can offer efficient debugging.

If \FdmAbstractcsProgbufsize is 1, \FdmDmstatusImpebreak must be 1. It is possible that the Program
Buffer can hold only one 32- or 16-bit instruction, so the debugger must only
write a single instruction in this case, regardless of its size.
This instruction can be a 32-bit
instruction, or a compressed instruction in the lower 16 bits accompanied by a
compressed {\tt nop} in the upper 16 bits.

\begin{commentary}
    The slightly inconsistent behavior with a Program Buffer of size 1 is to
    accommodate hardware designs that prefer to stuff instructions directly
    into the pipeline when halted, instead of having the Program Buffer exist
    in the address space somewhere.
\end{commentary}

While these programs are executed, the hart does not leave Debug Mode (see
Section~\ref{debugmode}).  If an exception is encountered during execution of
the Program Buffer, no more instructions are executed, the hart remains in Debug
Mode, and \FdmAbstractcsCmderr is set to 3 ({\tt exception error}).  If the debugger
executes a program that doesn't terminate with an {\tt ebreak} instruction, the
hart will remain in Debug Mode and the debugger will lose control of the hart.

Executing the Program Buffer may clobber \RcsrDpc. If that is the case, it must be
possible to read/write \RcsrDpc using an abstract command with \FacAccessregisterPostexec not set.
The debugger must attempt to save \RcsrDpc between halting and
executing a Program Buffer, and then restore \RcsrDpc before leaving Debug Mode.

\begin{commentary}
    Allowing Program Buffer execution to clobber \RcsrDpc allows for direct
    implementations that don't have a separate PC register, and do need to use
    the PC when executing the Program Buffer.
\end{commentary}

The Program Buffer may be implemented as RAM which is accessible to the
hart. A debugger can determine if this is the case by executing small
programs that attempt to write and read back relative to \Rpc while executing
from the Program Buffer.
If so, the debugger has more flexibility in what it can do with the program buffer.

\section{Overview of Hart Debug States}

Figure~\ref{fig:abstract_sm} shows a conceptual view of the states
passed through by a hart during run/halt debugging as influenced
by the different fields of \RdmDmcontrol, \RdmAbstractcs, \RdmAbstractauto, and
\RdmCommand.

\begin{figure}
   \centering
   \includegraphics[width=\textwidth]{fig/abstract_commands.pdf}
   \caption[Run/Halt Debug State Machine]{Run/Halt Debug State Machine for single-hart systems.
     As only a small amount of state is visibile to the debugger,
     the states and transitions are conceptual.}
   \label{fig:abstract_sm}
\end{figure}

\section{System Bus Access} \label{systembusaccess}

A debugger can access memory from a hart's point of view using a Program Buffer or
the Abstract Access Memory command. (Both these features are optional.)
A Debug Module may also include a System Bus Access block to provide memory
access without
involving a hart, regardless of whether Program Buffer is implemented.
The System Bus Access block uses physical addresses.

The System Bus Access block may support 8-, 16-, 32-, 64-, and 128-bit
accesses. Table~\ref{tab:sbdatabits} shows which bits in {\tt sbdata} are used
for each access size.

\begin{table}[htp]
    \centering
    \caption{System Bus Data Bits}
    \label{tab:sbdatabits}
    \begin{tabulary}{\textwidth}{|r|l|}
        \hline
        Access Size & Data Bits \\
        \hline
        8 & \RdmSbdataZero bits 7:0 \\
        \hline
        16 & \RdmSbdataZero bits 15:0 \\
        \hline
        32 & \RdmSbdataZero \\
        \hline
        64 & \RdmSbdataOne, \RdmSbdataZero \\
        \hline
        128 & \RdmSbdataThree, \RdmSbdataTwo, \RdmSbdataOne, \RdmSbdataZero \\
        \hline
    \end{tabulary}
\end{table}

Depending on the microarchitecture, data accessed through System Bus Access may
not always be coherent with that observed by each hart. It is up to the
debugger to enforce coherency if the implementation does not. This
specification does not define a standard way to do this.
Possibilities may include
writing to special memory-mapped
locations, or executing special instructions via the Program Buffer.

\begin{commentary}
Implementing a System Bus Access block has several benefits even
when a Debug Module also implements a Program Buffer.
First, it is possible to
access memory in a running system with minimal impact.  Second, it may improve
performance when accessing memory.
Third, it may provide
access to devices that a hart does not have access to.
\end{commentary}

\section{Minimally Intrusive Debugging}

Depending on the task it is performing, some harts can only be halted very briefly.
There are several mechanisms that allow accessing resources in such a running system
with a minimal impact on the running hart.

First, an implementation may allow some abstract commands to execute without halting the hart.

Second, the Quick Access abstract command can be used to halt a hart, quickly
execute the contents of the Program Buffer, and let the hart run again.
Combined with instructions that allow Program Buffer code to access the
{\tt data} registers, as described in \ref{hartinfo}, this can be used to quickly
perform a memory or register access. For some systems this will be too
intrusive, but many systems that can't be halted can bear an occasional hiccup
of a hundred or less cycles.

Third, if the System Bus Access block is implemented, it can be used while a
hart is running to access system memory.

\section{Security}

To protect intellectual property it may be desirable to lock access to the
Debug Module.  To allow access during a manufacturing process and not
afterwards, a reasonable solution could be to add a fuse bit to the Debug
Module that can be used to be permanently disable it. Since this is technology
specific, it is not further addressed in this spec.

Another option is to allow the DM to be unlocked only by users who have an
access key. Between \FdmDmstatusAuthenticated, \FdmDmstatusAuthbusy, and \RdmAuthdata arbitrarily
complex authentication mechanism can be supported.  When \FdmDmstatusAuthenticated is
clear, the DM must not interact with the rest of the platform, nor expose
details about the harts connected to the DM. All DM registers should read 0,
while writes should be ignored, with the following mandatory exceptions:
\begin{steps}{}
    \item \FdmDmstatusAuthenticated in \RdmDmstatus is readable.
    \item \FdmDmstatusAuthbusy in \RdmDmstatus is readable.
    \item \FdmDmstatusVersion in \RdmDmstatus is readable.
    \item \FdmDmcontrolDmactive in \RdmDmcontrol is readable and writable.
    \item \RdmAuthdata is readable and writable.
\end{steps}

\section{Version Detection}

\begin{steps}{To detect the version of the Debug Module with a minimum of side
    effects, use the following procedure:}
    \item Read \RdmDmcontrol.
    \item Write \RdmDmcontrol, preserving \FdmDmcontrolHartreset, \FdmDmcontrolHasel, \FdmDmcontrolHartsello, and
        \FdmDmcontrolHartselhi from the value that was read, setting \FdmDmcontrolDmactive, and
        clearing all the other bits.
    \item Read \RdmDmstatus, which contains \FdmDmstatusVersion.
\end{steps}

\begin{steps}{This has the following unavoidable side effects:}
    \item \FdmDmcontrolHaltreq is cleared, potentially preventing a halt request made by a
        previous debugger from taking effect.
    \item \FdmDmcontrolResumereq is cleared, potentially preventing a resume request made
        by a previous debugger from taking effect.
    \item \FdmDmcontrolNdmreset is deasserted, releasing the system from reset if a
        previous debugger had set it.
    \item \FdmDmcontrolDmactive is asserted, releasing the DM from reset. This in itself
        is not observable by any harts.
\end{steps}

This procedure is guaranteed to work in future versions of this spec.  The
meaning of the \RdmDmcontrol bits where \FdmDmcontrolHartreset, \FdmDmcontrolHasel, \FdmDmcontrolHartsello, and
\FdmDmcontrolHartselhi currently reside might change, but preserving them will have no
side effects. Clearing the bits of \RdmDmcontrol not explicitly mentioned here
will have no side effects beyond the ones mentioned above.

\section{Debug Module Registers} \label{dmdebbus}

The registers described in this section are accessed over the DMI bus.  Each DM
has a base address (which is 0 for the first DM). The register addresses below
are offsets from this base address.

When read, unimplemented Debug Module DMI Registers return 0. Writing them has
no effect.

For each register it is possible to determine that it is implemented by reading
it and getting a non-zero value (e.g.\ \RdmSbcs), or by checking bits in another
register (e.g.\ \FdmAbstractcsProgbufsize).

\input{dm_registers.tex}
