SDHOST
======

This is a description of the "sdhost" controller present in BCM283x, as
reverse-engineered from the Linux driver at drivers/mmc/host/bcm2835-sdhost.c,
with some additional notes derived empirically.

The sdhost register base address is 0x7E202000 (as viewed from VideoCore,
for example for DMA access), 0x20202000 (BCM2835 ARM physical address),
0x3F202000 (BCM2836/BCM2837 ARM physical address) or 0xFE202000 (BCM2838
ARM physical address).

Registers are read and written using 32-bit accesses. Reads should always be
followed by a CP15DSB, and writes should always be preceded by a CP15DSB.

Interrupts are routed to GPU interrupt 56.

Data can be transferred to or from the controller's FIFO  in either PIO or DMA
modes: for DMA, use one of the BCM283x's general-purpose DMA channels to target
the SDDATA register. DMA transfers should be configured to use DMA request
number (peripheral mapping) 13 to mediate non-incrementing reads or writes (as
applicable) of this register. Writes to the FIFO register should be configured
to wait for a write response; writes to RAM should use 128-bit writes.

The controller has a serious bug which is triggered on every command that
reads multiple data blocks from the device. Following the final block interrupt
of the transfer (which is triggered when at FSM state "READCRC"), rather than
transitioning to state "GENPULSES" and shortly thereafter to "DATAMODE" (which
is what happens for single-block reads), it transitions to "READWAIT" and
remains there until the timeout configured via SDTOUT has expired.

Because this would introduce a significant time overhead to every operation,
it is desirable to use the "FORCE_DATA_MODE" mechanism in this situation.
However, while in the single-block case, the DMA request line is presumably
asserted irrespective of the FIFO level once the transfer completes, in order
to fully drain the FIFO, for a multi-block read the SD controller still thinks
it is in an inter-block state. In practice, the FIFO has a level which is the
next even number of words below READ_THRESHOLD (implying that the DMA
controller would normally remove data in 64-bit chunks by preference) and these
words are discarded when we forcibly transition to "DATAMODE".

One solution to this is to reduce the amount of data transferred by DMA by at
least this many words, and to perform the remainder of the transfer by PIO.
In practice, you can use (as Linux does) READ_THRESHOLD-1, which allows one
extra word to be transferred by DMA when READ_THRESHOLD is even. Presumably
some additional logic comes into play when the DMA controller only has one
word left to fetch at the end of a transfer?

The simplest solution, however, is to set READ_THRESHOLD to 2, which permits
the entire transfer to be performed by DMA. If READ_THRESHOLD is set any lower
than this, the DMA controller will fetch more data from the FIFO than is
available, intersperse the data in the destination RAM with garbage, and cause
the SD controller to raise FIFO errors.

The Compute Module datasheet states that "[sdhost] does not support SDIO" but
it is not clear why it makes this assertion. This may reflect the fact that
SDCLK stops oscillating (it is held high) outside host-initiated commands.
It is conventional to leave SDCLK running for SDIO devices, so some devices
may rely on it to clock their normal operations. It's also possible that while
bit definitions in the Linux sources suggest sdhost supports card interrupts,
it may only sample them on edges of SDCLK. It's impossible to say at the time
of writing, as the Linux driver doesn't attempt to use card interrupts, and no
RISC OS drivers yet exist for removable SDIO cards that could be used to
confirm experimentally. It may however be possible to work around any such
limitation by polling the SDIO interrupt status register on a regular basis,
for example from TickerV.

The controller reset procedure is as follows:
* Power down by writing 0 to SDVDD
* Clear registers SDCMD, SDARG, SDCDIV, SDHCFG, SDHBCT, SDHBLC to 0
* Set SDTOUT to a high value
* Clear interrupts by setting relevant bits in SDHSTS
* Set the read and write thresholds in SDEDM
* Wait 10 ms
* Power up by writing 1 to SDVDD
* Wait 10 ms


Register map
------------

Address     Register name  Description
0x7E202000  SDCMD          Command to SD card
0x7E202004  SDARG          Argument to SD card
0x7E202008  SDTOUT         Start value for timeout counter
0x7E20200C  SDCDIV         Start value for clock divider
0x7E202010  SDRSP0         SD card response [31:0]
0x7E202014  SDRSP1         SD card response [63:32]
0x7E202018  SDRSP2         SD card response [95:64]
0x7E20201C  SDRSP3         SD card response [127:96]
0x7E202020  SDHSTS         Host status
0x7E202024  --
0x7E202028  --
0x7E20202C  --
0x7E202030  SDVDD          Power control
0x7E202034  SDEDM          Emergency debug mode
0x7E202038  SDHCFG         Host configuration
0x7E20203C  SDHBCT         Host byte count
0x7E202040  SDDATA         Data to/from SD card
0x7E202044  --
0x7E202048  --
0x7E20204C  --
0x7E202050  SDHBLC         Host block count


SDCMD (0x7E202000)
------------------

Bit(s)  Name           Type  Description
31:16   -              -     Reserved, write as 0.
15      NEW_FLAG       RW    Set by software to trigger a new command. Cleared
                             by host controller when command is complete.
                             Suggested timeout for this bit to clear is 100 ms
                             after receipt of final interrupt.
14      FAIL_FLAG      R     Indicates an error has occurred. Refer to SDHSTS
                             to determine type of error.
13:12   -              -     Reserved, write as 0.
11      BUSYWAIT       W     Check busy on DAT0 after response.
10      NO_RESPONSE    W     Command has no response.
9       LONG_RESPONSE  W     Command has 136-bit response.
8       -              -     Reserved, write as 0.
7       WRITE_CMD      W     Command features data transfer from host to card.
6       READ_CMD       W     Command features data transfer from card to host.
5:0     CMD            W     Command index.


SDARG (0x7E202004)
------------------

Bit(s)  Name           Type  Description
31:0    ARG            W     Argument bits to insert into command. Should be
                             written prior to SDCMD.


SDTOUT (0x7E202008)
-------------------

Bit(s)  Name           Type  Description
31:0    TOUT           W     Start value for data line timeout counter, in
                             ticks of the clock (as divided by SDCDIV).
                             Suggested timeout to use is 500 ms.


SDCDIV (0x7E20200C)
-------------------

Bit(s)  Name           Type  Description
31:11   -              -     Reserved, write as 0.
10:0    CDIV           W     Clock divider, minus 2. The frequency of the base
                             clock that is divided from can be obtained using
                             the mailbox, using tag "Get clock rate" for
                             clock id "CORE"; in practice this is supposed to be
                             250 MHz. Having said that, practical measurements
                             suggest the true clock speed is 400 MHz.

In practice, more recent versions of the firmware offer an extra, undocumented
tag for setting the divider. This is:

Set SDHOST clock
* Tag: 0x00038042
* Request:
  o Length: 4
  o Value:
    * u32: requested frequency (in Hz)
* Response:
  o Length: 12
  o Value:
    * u32: requested frequency (in Hz)
    * u32: selected frequency (in Hz)
    * u32: selected frequency (in Hz)

The range of frequencies available is the same as via CDIV (i.e. maximum
125 MHz = 250 MHz / (0+2), minimum 122 kHz = 250 MHz / (2047+2)). It is not
clear what the difference between the last two returned u32 values are, but
you should take the maximum of the two to be the actual clock speed.

If you think there's a danger that you might be running on firmware that's too
old to support this tag, you can use an extra query with implausible results
pre-filled into the response buffer to test it.


SDRSP0 (0x7E202010)
-------------------

For 48-bit responses, the following is valid once NEW_FLAG has been cleared,
provided FAIL_FLAG is not set.

Bit(s)  Name           Type  Description
31:0    RSP0_48        R     Bits 39:8 of response to the command.

For 136-bit responses, the following is valid once NEW_FLAG has been cleared,
provided FAIL_FLAG is not set.

Bit(s)  Name           Type  Description
31:0    RSP0_136       R     Bits 31:0 of response to the command (transmitted
                             last on the bus).


SDRSP1 (0x7E202014)
-------------------

For 48-bit responses, the following is valid once NEW_FLAG has been cleared,
provided FAIL_FLAG is not set.

Bit(s)  Name           Type  Description
31:16   -              -     Reserved.
15:8    INDEX          R     Bits 47:40 of response to the command.
7       -              -     Reserved.
6:0     CRC            R     Bits 7:1 of response to the command.

For 136-bit responses, the following is valid once NEW_FLAG has been cleared,
provided FAIL_FLAG is not set.

Bit(s)  Name           Type  Description
31:0    RSP1_136       R     Bits 63:32 of response to the command.


SDRSP2 (0x7E202018)
-------------------

For 136-bit responses, the following is valid once NEW_FLAG has been cleared,
provided FAIL_FLAG is not set.

Bit(s)  Name           Type  Description
31:0    RSP2_136       R     Bits 95:64 of response to the command.


SDRSP3 (0x7E20201C)
-------------------

For 136-bit responses, the following is valid once NEW_FLAG has been cleared,
provided FAIL_FLAG is not set.

Bit(s)  Name           Type  Description
31:0    RSP3_136       R     Bits 127:96 of response to the command
                             (transmitted first on the bus).

Bits 135:128 of 136-bit responses are not available (but they should have a
fixed pattern so convey no extra information).


SDHSTS (0x7E202020)
-------------------

Bit(s)  Name           Type  Description
31:11   -              -     Reserved, write as 0.
10      BUSY_IRPT      RW    Read: 1 => card has finished signalling busy on
                             DAT0, and busy interrupt is enabled in SDHCFG.
                             Write 1 to clear.
9       BLOCK_IRPT     RW    Read: 1 => all bytes in a block transfer (either
                             read or write) have been transferred, and block
                             interrupt is enabled in SDHCFG. Write 1 to clear.
8       SDIO_IRPT      RW    Not used by Linux driver. [Presumably, 1 =>
                             card interrupt signalled via DAT1, and card
                             interrupt is enabled in SDHCFG.] Write 1 to clear.
7       REW_TIME_OUT   RW    Read/Erase/Write [?] timeout. Write 1 to clear.
6       CMD_TIME_OUT   RW    Command/Response timeout. Write 1 to clear.
5       CRC16_ERROR    RW    CRC error on DAT lines. Write 1 to clear.
4       CRC7_ERROR     RW    CRC error on CMD lines. Write 1 to clear.
3       FIFO_ERROR     RW    Error from controller's FIFO. [Maybe overflow?]
                             Write 1 to clear.
2:1     -              -     Reserved, write as 0.
0       DATA_FLAG      R     Read: 1 => the FIFO is ready for data to be read
                             or written (for read operations, the FIFO level is
                             READ_THRESHOLD words or more; for write
                             operations, the FIFO level is WRITE_THRESHOLD
                             words or less). Writing does *not* appear to
                             clear. This is a status bit, and is gated by
                             DATA_IRPT_EN before generating an interrupt.

The error bits REW_TIME_OUT, CMD_TIME_OUT, CRC16_ERROR, CRC7_ERROR and
FIFO_ERROR may not be valid when in FSM states READDATA, WRITEDATA, READWAIT,
READCRC, WRITESTART1 or WRITESTART2.


SDVDD (0x7E202030)
------------------

Bit(s)  Name           Type  Description
31:1    -              -     Reserved, write as 0.
0       POWER          W     0 => power off, 1 => power on.


SDEDM (0x7E202034)
------------------

Bit(s)  Name            Type  Description
31:22   -               -     Reserved, do not modify.
21      BYPASS          ?     Not used by Linux driver, do not modify.
20      CLOCK_PULSE     ?     Not used by Linux driver, do not modify.
19      FORCE_DATA_MODE W     To recover from the condition where a command
                              has completed (the last event of the following:
                              an error reported from command issuing, the
                              NEW_FLAG being cleared, a busy interrupt
                              indicating that CMD line is finished with, or
                              the final block interrupt indicating that the DAT
                              lines are finished with) and the state reads as
                              READWAIT or WRITESTART1, set this bit. States of
                              IDENTMODE or DATAMODE indicate the controller is
                              ready to issue another command. You should wait
                              further if the state has any other value.
18:14   READ_THRESHOLD  W     Minimum FIFO threshold for setting the DATA_FLAG
                              during read operations, in words. Linux uses 4.
13:9    WRITE_THRESHOLD W     Maximum FIFO threshold for setting the DATA_FLAG
                              during write operations. in words. Linux uses 4.
8:4     FIFO_LEVEL      R     Number of 32-bit words in read/write FIFO.
                              Should range between 0 and 16.
3:0     FSM             R     State:
                              0x0 IDENTMODE
                                  state throughout initial bus negotiation
                                  (until first CMD7_SELECT_DESELECT_CARD)
                              0x1 DATAMODE
                                  state between normal commands, or during
                                  tranmission of the command on CMD, or
                                  (for write or non-data commands) reception of
                                  the response on CMD
                              0x2 READDATA
                                  state during reception of data bits in a read
                                  operation
                              0x3 WRITEDATA
                                  state during transmission of data bits in a
                                  write operation
                              0x4 READWAIT
                                  state during a read operation before, between
                                  or after reception of data blocks, including
                                  pull-up periods, start and end bits; overlaps
                                  with reception of response on CMD
                              0x5 READCRC
                                  state during reception of CRC16 at the end of
                                  each data block in a read operation
                              0x6 WRITECRC
                                  state during transmission of CRC16 at the end
                                  of each data block in a write operation, as
                                  well as during reception of corresponding
                                  CRC status bits from card
                              0x7 WRITEWAIT1
                                  state during busy signalling (DAT0 low)
                                  following any data block in a write operation
                              0x8 POWERDOWN
                                  state has not been observed in practice
                              0x9 POWERUP
                                  state for first 2 us after POWER set to 1
                              0xa WRITESTART1
                                  state after reception of response up to but
                                  not including transmission of first data
                                  start bit in write operations
                              0xb WRITESTART2
                                  state during transmission of start bit for
                                  each block in a write operation
                              0xc GENPULSES
                                  state for 8 clock cycles following reading
                                  of CRC16 in single-block read operations;
                                  speculation: this ensures additional CLK
                                  transitions in case a device requires it?
                              0xd WRITEWAIT2
                                  state following WRITEWAIT1 for each block
                                  in a write operation where the card has
                                  finished pulling DAT0 low and the line goes
                                  high, required so that the start bit of any
                                  following block can be distinguished
                              0xe <not defined>
                                  state has not been observed in practice
                              0xf STARTPOWERDOWN
                                  initial state, or state after POWER set to 0


SDHCFG (0x7E202038)
-------------------

Bit(s)  Name           Type  Description
31:11   -              -     Reserved.
10      BUSY_IRPT_EN   W     Enables BUSY_IRPT bit in SDHSTS.
9       -              -     Reserved.
8       BLOCK_IRPT_EN  W     Enables BLOCK_IRPT bit in SDHSTS.
7:6     -              -     Reserved.
5       SDIO_IRPT_EN   W     Enables SDIO_IRPT bit in SDHSTS (and is not used
                             by the Linux driver).
4       DATA_IRPT_EN   W     Gates the DATA_FLAG bit in SDHSTS to generate an
                             interrupt.
3       SLOW_CARD      W     When 0, the controller dynamically selects either
                             the bottom 3 bits or the full 11 bits of CDIV
                             depending on whether the bus is in card
                             identification or data transfer mode - presumably
                             by monitoring the commands issued. This bit was
                             presumably originally intended to support slow
                             cards by leaving the clock speed at 400 kHz in
                             data transfer mode, but with core clocks of above
                             225 MHz (including the BCM2835 which uses
                             250 MHz) 3 bits is not enough to divide down to
                             25 MHz, which is a common bus speed. So the Linux
                             driver always sets this to 1 and explicitly
                             reprograms the clock divider when changing bus
                             operation mode.
2       WIDE_EXT_BUS   W     Data bus is 4 lines wide rather than 1 line.
1       WIDE_INT_BUS   W     Always set to 1 by Linux driver.
0       REL_CMD_LINE   W     Always set to 0 by Linux driver.


SDHBCT (0x7E20203C)
-------------------

Bit(s)  Name           Type  Description
31:0    HBCT           W     Number of bytes in a block (on the DAT lines).


SDDATA (0x7E202040)
-------------------

Bit(s)  Name           Type  Description
31:0    DATA           RW    Used to transfer data 32 bits at a time from/to
                             the read/write FIFO. It is recommended that
                             data is read or written in bursts of not more
                             than 8 words at a time (refer to FIFO_LEVEL in
                             SDEDM). The time required for the FIFO to fill or
                             drain to a sufficient level can be estimated
                             using the clock rate and bus width. During any
                             such waits is a good time to poll SDHSTS for
                             errors.

SDHBLC (0x7E202050)
-------------------

Bit(s)  Name           Type  Description
31:9    -              -     Reserved, write as 0.
8:0     HBLC           W     Number of blocks in command.
Unconfirmed: bits 15:0 all appear to be writeable, so perhaps the block limit
is compatible with SDHCI?
